How to reference original bound element in plugin callback?
I have plugin that simply opens a modal box and allows users to select a value form a picklist. The plugin attaches an event listen to open the select/modal box. This selected value will then be returned to a callback function. In this call back I would also like to reference the actual element the plugin was bound to but I am not sure how to do this. In the code see this section: "//************How do I "
This is one of my first plugins so if there is a better way to do this please let me know.
Thanks,
Jason
Here is the code on jsBin: http://jsbin.com/welcome/70094/edit
Also here is the code:
- <html>
- <body>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
- <!-- plugin -->
- <script>
- (function( $ ){
- $.fn.pillSelector = function( options ) {
-
- // Create some defaults
- var settings = $.extend( {
- 'onSelect' : function(){}
- }, options);
-
- //Create event lister for select button when user selects value form a list
- $('#selectBtn').click(function(){
- //Return the selected value to the call back function
- settings.onSelect( $('#selectList').find('option:selected').val() );
-
- //Hide the select box / fake modal box
- $('#selectBox').hide();
- });
-
- //For each element this plugin is attached to create event that will open selector box
- return this.each(function() {
-
- //Add event listen that will open select box
- $(this).bind('click',function(){
- $('#selectBox').show();
- });
-
- });
- };
- })( jQuery );
- </script>
-
- <!-- user script -->
- <script>
- $(document).ready(function(){
- $('.openSelector').pillSelector({
- onSelect : function(color){
- console.log(color + ' selected');
-
- //************How do I reference the original .openSelector element this plugin was bound to?
- console.log($(this));
- console.log(this);
-
- //Do I need to some how store it in the plugin and return it in the function?
- }
- });
- });
- </script>
-
- <a href="#" id="select1" class="openSelector">open selector</a>
-
- <a href="#" id="select2" class="openSelector">open selector</a>
-
- <!-- pretend this is some kind of modal box -->
- <div id="selectBox" style="display: none;">
- <select id="selectList">
- <option value="red">red pill</option>
- <option value="blue">blue pill</option>
- </select>
-
- <input type="button" id="selectBtn" value="this would select something"/>
- </div>
-
- </body>
- </html>