How we can prioritize jQuery events?

To prioritize jQuery events, use the event.stopPropagation() method. This method prevents an event from bubbling up the DOM tree, allowing you to control which event handlers execute and in what order.

Event prioritization in jQuery is essential when you have multiple event handlers attached to nested elements. By default, events bubble up from the target element to its parent elements. The stopPropagation() method stops this bubbling behavior, effectively giving priority to the current event handler.

Example

You can try to run the following code to learn how to prioritize using stopPropagation() method ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            
            var timer;
            function out(s) {
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }
                $("#demo").append(s + "<br>");
                timer = setTimeout(function() {
                    $("#demo").append("-------" + "<br>");
                    timer = null;
                }, 100);
            }

            $(".li").find('input').click(function(e){
                out('li>input');
                if ($(this).parent().hasClass("stop")) {
                    e.stopPropagation();
                }
            });

            $(".li").click(function(e){
                out('li');
            });

            $('input').click(function(e){
                out('input');
                if ($(this).parent().hasClass("stop")) {
                    e.stopPropagation();
                }
            });
        });
    </script>
</head>
<body>
    <ul>
        <li class="li">
            <input type="checkbox" />
            <span>Demo</span>
        </li>
        <li class="li stop">
            <input type="checkbox" />
            <span>Demo using stop propagation method</span>
        </li>
    </ul>
    <div id="demo"></div>
</body>
</html>

In this example, clicking the first checkbox will trigger both the input and li event handlers due to event bubbling. However, clicking the second checkbox (which has the "stop" class) will only trigger the input event handler because stopPropagation() prevents the event from bubbling up to the parent li element.

Conclusion

Using event.stopPropagation() is an effective way to prioritize jQuery events by controlling the event flow and preventing unwanted event handlers from executing during the bubbling phase.

Updated on: 2026-03-13T19:03:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements