4

As a relative noob to javascript and jQuery, I was curious if it is wrong to attach 2 click handlers to the same element? I know I CAN do it, but I am just curious if this is a violation of 'best practices'

Example HTML:

<ul>
    <li id="all"   class="click_listener"> All Items </li>
    <li id="item1" class="click_listener"> Item 1    </li>
    <li id="item2" class="click_listener"> Item 2    </li>
    <li id="item3" class="click_listener"> Item 3    </li>
</ul>

Example jQuery (in document ready):

$(".click_listener").click(
    function() {
       var productCode = $(this).id;
       filter(productCode);
    }
);

$("#all").click(
    function() {
       closeMenu();
    }
);

Other jQuery functions:

function filter(productCode) {
    // Displays selected product, or if 'all' was passed in, displays all products.
}

function closeMenu() {
    // Closes the menu by slideUp-ing the parent <ul>
}

In my attempt to simplify the code, I may have made a mistake or 2, but everything is working on the actual site. When you click an item in the list menu, it properly displays the item you clicked. When you click the li with the id #all, it properly displays all the items AND closes up the menu with a nice little slideUp animation.

So yes, it works, but it just 'feels' like the wrong way to do it. Is this an acceptable best practices approach?

I could also trigger the closeMenu() function inside the filter() function when I detect All was clicked, but if the above approach is OK, then I'd rather not spend the time (the actual site is considerably more complex than the above example, so I'd have to do this in a bunch of places).

MD XF
  • 7,860
  • 7
  • 40
  • 71
DocBrody
  • 43
  • 3
  • Possible duplicate of [Can multiple event listeners/handlers be added to the same element using javascript?](http://stackoverflow.com/questions/5411055/can-multiple-event-listeners-handlers-be-added-to-the-same-element-using-javascr) – Martin Schröder Apr 18 '17 at 18:56

2 Answers2

3

It's not wrong. In fact, it is a good practice to have each javascript "component" set it's own event handlers. So you'd have different javascript files potentially adding an event handler. This is better than manually merging the code just to avoid one even handler.

In other words, do what is clearest.

Jeanne Boyarsky
  • 12,156
  • 2
  • 49
  • 59
  • the only problem you could run into is if one of your bound functions breaks the event bubble or returns false – nderscore Jun 20 '13 at 03:47
1

There is nothing wrong with this approach.

This approach is more readable and understandable, else you will have add more conditions in your click handler to check whether it is the all element then call the specific method

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531