jeudi 26 mars 2015

How can I add a class to the selected element on click event with select2?


We are using Select2 version 4.0.0-rc2


To improve mobile usage we would like to implement adding a class to the clicked item in the drop down.


I tried reacting to the select2 events like this:



element.select2({}).on('select2:open', function(){
this.addClass('my-class');
}


However, the problem with this is that 'this' is the option and not the rendered select li. I believe 'this' is because Select2 delegates/passes the event down to the select option.


I also tried directly targeting the result item like this:



$('.select2-results li ["aria-selected=true"]').on('click', function(){
this.addClass('my-class');
}


But I get the same problem as above. 'This' and even Event.target are option.


I found some suggestions from older versions of select2 and tried this:



element.select2({}).on('select2:open', function(e){
$('.search-results li [aria-selected=true]').on('mouseup', function(e){
e.stopPropagation();
this.addClass('my-class');
}


This one only seemed to work on the second click. So, I clicked to open the list, I select an item, nothing happens, I select another item, it then gets the class.



  • Note: Some of the selectors above may not be accurate but its just to give an example. All of my code worked except that I couldnt get my event to fire on the right element.


Could anyone suggest a fix?


Alternatively, on the Select2 page (http://ift.tt/1yf24TR) , they suggest that in version 4 you can write plugins using an adapter. Im not familiar with adapters and can only assume they mean the adapter pattern? I dont understand how I would even start with this. I understand the concept, I write a wrapper so that my functions are called and I can modify them and also pass through to the library methods? If anyone could provide any further info on how I could do that, it would be greatly appreciated.





Aucun commentaire:

Enregistrer un commentaire