In jQuery I'm creating a whole suite of elements to include in my project. The suite will contain various elements such as buttons, input elements, modal popups and others.
Now, the first control which I'm writing is a select (dropdown), which has the following syntax:
<div class="dropdown" style="height: 20px; width: 100px;">
<div class="legend"></div>
<ul class="elements">
<li>Blue</li>
<li>Green</li>
<li>LightBlue</li>
<li>Orange</li>
<li>Purple</li>
<li>Red</li>
<li>Turquoise</li>
</ul>
</div>
Now, I have various JavaScript methods to lets this work, adding the necessary classes and other things to ensure a proper working.
Now, I do have created a method that should execute a piece of code, placed as an attribute on the element.
$('.elements li', dropdownElement).click(function() {
var selectedLiText = $(this).html();
$('.legend', dropdownElement).html(selectedLiText);
var attribute = $(dropdownElement).attr('data-on-change');
if (typeof attribute !== 'undefined' && attribute != '') { eval(attribute); }
$(dropdownElement).ToggleOpen();
});
So, the code above does show that when there's an attribute called 'data-on-change' on the element, it will translate it into a JavaScript function and execute it.
In order to make it work, the HTML should be adapted like the following:
<div class="dropdown" style="height: 20px; width: 100px;" data-on-change="alert('demo');">
<div class="legend"></div>
<ul class="elements">
<li>Blue</li>
<li>Green</li>
<li>LightBlue</li>
<li>Orange</li>
<li>Purple</li>
<li>Red</li>
<li>Turquoise</li>
</ul>
</div>
This would make a popup open with the text 'Demo'.
See this JsFiddle for the workings. Note: There's no styling so it doesn't really looks like a DropDown but just click an element in the UL and the popup will show.
What I would like to do is the following, expose something
in my plugin that enables me to get the selected item.
So I would like to be able to form my data-on-change function like so:
data-on-change="alert(selectedItem)"
Or maybe
data-on-change="alert(this.selectedItem)".
All ideas are welcome.