Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add click event by class name?

Tags:

jquery

I have a example html menu:

<div class="mmenu">
    <ul>
        <li>
            <div  class="menu_button" id="m1" >A</div>
        </li>
        <li>
            <div  class="menu_button" id="m2" >B</div>
        </li>
        <li>
            <div  class="menu_button" id="m3" >C</div>
    </ul>
</div>

Can I add click event for each element of menu by class name ?

 $('.menu_button').click(function() {
     if ( id == "m1" ) ....
 })
like image 463
Bdfy Avatar asked Oct 07 '11 10:10

Bdfy


2 Answers

Optimize your code by not using live() as we cannot stop propagation of live() events

Use on() (jQuery 1.7+) or delegate() (below 1.7)

Most efficient solution for your scenario in this case would be:

//  $('.mmenu').on("click", ".menu_button", function() {   // jQuery 1.7 & up
    $('.mmenu').delegate(".menu_button", "click", function() {
        var id = $(this).attr('id') // or this.id
        if ( id == "m1" ) {
            // ..code
        }
    });

In this way, you have only one click event bound to the main div $('.mmenu'), which will also work if you add elements (new li with divs) in the future

like image 148
Om Shankar Avatar answered Sep 19 '22 03:09

Om Shankar


I would suggest to use the live function, instead of the .click, because the elements added on run-time will also be clickable.

$('.menu_button').live('click', function() {
  var id = $(this).attr('id');
  if (id == "m1") {
      //do your stuff here
  }
});
like image 28
rlc Avatar answered Sep 21 '22 03:09

rlc