0

In the below code I have a couple of unordered lists, and in the plugin I am attempting to fire a click event when the li element is clicked. How can I do this inside the plugin and still have access to the main ul jquery object?

See comments in code for further explanation

    <ul class="testing">

        <li>clicking this should fire a click event</li>

    </ul>

   <ul class="testing">

        <li>clicking this should fire a click event</li>

    </ul>


    (function($) {
       $.fn.myPlugin = function(options) {


         return this.each(function() {

            //how should I trigger the onClick when the li is clicked???

         });

          function onClick(){

             console.log('you clicked an li');
             //I also need access to the main ul element inside here
          }

       }
    })(jQuery);



    $(function() {
       $('.testing').myPlugin();
    });

2 Answers 2

2
(function($) {
   $.fn.myPlugin = function(options) {
     return this.find('li').click(onClick)
      function onClick(){
         console.log('you clicked an li');           
         $(this).parent(); // This is the <ul>
      }

   }
})(jQuery);

$(".testing").myPlugin()
Sign up to request clarification or add additional context in comments.

Comments

0

Copy the following example and see if this helps solidify what you are attempting to accomplish.

The proof of getting to the main ul tags are the alerts. You will see I have created 'testing1' and 'testing2' classes. Depending on which li tag is clicked, the user will receive an alert of what class is associated to the parent ul tag of the clicked li tag.

I hope this helps!

<ul class="testing1">

    <li>clicking this should fire a click event</li>

</ul>

<ul class="testing2">

    <li>clicking this should fire a click event</li>

</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $('ul')
    .on('click', 'li', function() {
        $(this).myPlugin();
    });
});
$.fn.myPlugin = function(options) {
    return this.each(function() {
        //how should I trigger the onClick when the li is clicked???
        onClick(this);
    });
    function onClick(jqObj) {
        console.log('you clicked an li');
        //I also need access to the main ul element inside here
        alert($(jqObj).parent('ul').attr('class'));
    }
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.