Practical Web Programming

Wednesday, April 03, 2013

JQuery: How to prevent click event handler from being bound multiple times

A simple trick is to add a class to the element and bound only if the element don't have that class yet.

<script type="text/javascript">
    $('#button:not(.bound)')
        .addClass('bound')
        .bind('click', onClick);
 
 
    function onClick() {
        alert('You clicked me!');
    }
</script>

0 comments:

Recent Post