Open In App

How to Stop Event Propagation with Inline Onclick Attribute in JavaScript?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The stopPropagation() method in the HTML DOM is used to stop an event from propagating (or “bubbling”). This method is particularly useful when using an inline onclick attribute in JavaScript.

HTML DOM stopPropagation() Event Method

The stopPropagation() method is used to stop propagation of event calling i.e. the parent event is called we can stop the propagation of calling its children by using the stopPropagation() method and vice-versa.

Syntax:

event.stopPropagation()

Example 1: This example stops the event propagation by adding the stopPropagation method on onclick the <span> element.

html
<!DOCTYPE HTML>
<html>

<head>
    <title>
        How to stop event propagation with
        inline onclick attribute
    </title>

    <style>
        div {
            background: green;
        }

        span {
            background: red;
            color: white;
        }
    </style>
</head>

<body style="text-align:center;">

    <h1 style="color:green;">
        GeeksForGeeks
    </h1>

    <div onclick="alert('you clicked the div')">
        <span onclick="event.stopPropagation(); 
            alert('you clicked Span element(inside the div)');">
            Span Content
        </span>
    </div>
</body>

</html>

Output:

output

Example 2: This example stops the event propagation by adding stopPropagation() method on onclick to the <span> element. This example handles the Internet Explorer case by setting window.event.cancelBubble to true.

html
<!DOCTYPE HTML>
<html>

<head>
    <title>
        How to stop event propagation with
        inline onclick attribute
    </title>

    <style>
        div {
            background: green;
        }

        span {
            background: red;
            color: white;
        }
    </style>
</head>

<body style="text-align:center;">

    <h1 style="color:green;">
        GeeksForGeeks
    </h1>

    <div onclick="alert('you clicked the div')">
        <span onclick="StopEventPropagation(event);
            alert('you clicked Span element(inside the div)');">
            Span Content
        </span>
    </div>

    <br>
    <script>
        function StopEventPropagation(event) {
            if (event.stopPropagation) {
                event.stopPropagation();
            }
            else if (window.event) {
                window.event.cancelBubble = true;
            }
        }     
    </script>
</body>

</html>

Output:

output



Similar Reads