2

I have a span on top of a div. The div has an onclick event, and the span also has an onclick event. If I click on the span, I want only the span-onclick event to be triggered, unfortunately, both the onclick of the div and the one of the span are triggered. How can this be fixed?

        <div class="listRow" onclick="document.location = 'index.php?c=rooms&a=displayForm&roomID=3&returnTo=%2FschoolTool%2Findex.php%3Fc%3Drooms%26a%3DshowList';">
            <span class="tools listCell">
                <span class="tool" onclick="if(confirm('Vil du virkelig slette dette rommet?')) { document.location = 'index.php?c=rooms&a=delete&roomID=3'; }">
                    Slett
                </span>
            </span>
        </div>
rasmusrim
  • 115
  • 1
  • 10

2 Answers2

4

The answer you are looking for is simple, but I'm gonna give you a wider swath of advice.

First, you should separate your Javascript from the HTML. Inline Javascript is generally considered bad, see here for example.

Once you move the Javascript to a separate file, just put your methods inside variables and call them from the onclick handler. I made a simple fiddle to demonstrate this.

Now, the actual answer you're looking for is the stopPropagation() method. This gets called on an event object to stop it from bubbling up the DOM and getting handled again. That's the basic answer, from there topics on stopImmediatePropagation() and preventDefault() often popup. So I recommend reading the related jquery docs and checking out this blog post I wrote :)

Hope this helps answer your question and make you a better developer! Cheers!

Community
  • 1
  • 1
trentmwillis
  • 651
  • 4
  • 6
2

The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object).

Syntax:

event.stopPropagation() 

For more details :-

https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation

Neel
  • 11,625
  • 3
  • 43
  • 61