1

I have a website which displays search results. The results are displayed with headline information of the full item. The html of each search result looks like this:

<article class="search_result" onclick="location.href='#';" style="cursor: pointer;">

// Search result data

</article>

As you can see, I have made it so that you can click anywhere and access the result in more detail

However, within the search result, I have also included a button which performs another function.

The problem I have is when you click on the button, both the button and the search result receive the click event and act upon it. If the button is clicked, I dont want the search result to handle it as well.

How can I sort this?

Ben Thompson
  • 4,743
  • 7
  • 35
  • 52

1 Answers1

2

JavaScript events bubble up the DOM by default, so events triggered on a children will be triggered on the parent.

To prevent this, you need to stop the propagation of the event.

This is done by:

event.stopPropagation();

Note that event is usually passed as a parameter to your callback functions. (Meaning, don't use onclick="" attributes so you get function callback)

Full documentation: https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation
(IE < 8 fallback: Prototype Event.StopPropagation for IE >= 8)

Community
  • 1
  • 1
Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134