Question

Basically there are multiple options to catch "onclick" events with javascript.

The html:

<div id='menu'>
  <button>Title</button>
</div>

The following few jQuery options:

<script>
var menu = $('#menu');
var buttons = menu.find('button').click(menuEvent);

function menuEvent() {
  ..
}
</script>

<script>
var menu = $('#menu');
var buttons = menu.find('button');

buttons.click(function() {
  ..
});
</script>

<script>
var menu = $('#menu');
var buttons = menu.find('button');

buttons.get(0).onclick = function() {
  ..
});
</script>

Now they all look the same and they are probably not really faster than one another. So which of these three would be the "best" approach or maybe there is a better way?

I know you can do this with just javascript, but I plan on using jQuery anyway so it might complicate things when it doesn't have to.

Was it helpful?

Solution

Best one would be :

buttons.on("click", function(event){
// code to run on click
});

More info here : http://api.jquery.com/on/

OTHER TIPS

I don't know if there is conceptually a best approach in the ones you expose. It more depends on the context.

  • If you want to attach an event handler to only the buttons, this way od doing is okay:

    buttons.click(function() {
      ..
    });
    
  • If the same handler should be shared for different groups of elements, you can define the handler separately and use for the different groups:

    function myClickHandler() {
        ...
    }
    
    buttons.click(myClickHandler);
    otherButtons.click(myClickHandler);
    
  • .on() is for event delegation. When an event handler should be added to elements inserted in the DOM after your bind occurs, you should turn to event delegation. Basically, you "bind" the event to a parent container, restraining its execution using a selector to the elements in question:

    container.on('click', '.button', function() {
        // will execute when clicking on elements with class .button
        // present inside the container
    });
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top