Javascript onclick () bubbling event - works or not?

I have a table in which a table row tag is decorated with an onclick () handler. If you click a line at any time, it will load another page. In one of the line items, this is a binding, which also leads to another page.

The behavior is preferably that if they click on the link, "delete.html" is loaded. If they click elsewhere in the line, "edit.html" is loaded.

Problem lies in the fact that sometimes (according to users) both the link and onclick () are launched at the same time, which leads to a problem at the back of the code. They swear that they do not double click.

I'm not well versed in events related to Javascript events, processing, and even knowing where to start with this bizarre problem, so I ask for help. Here is a fragment of the displayed page showing a line with an inline link and a script tag associated with it. Any suggestions are welcome:

<tr id="tableRow_3339_0" class="odd"> <td class="l"></td> <td>PENDING</td> <td>Yabba Dabba Doo</td> <td>Fred Flintstone</td> <td> <a href="/delete.html?requestId=3339"> <div class="deleteButtonIcon"></div> </a> </td> <td class="r"></td> </tr> <script type="text/javascript">document.getElementById("tableRow_3339_0").onclick = function(event) { window.location = '//edit.html?requestId=3339'; };</script> 
+4
source share
2 answers

The bubbling event works like this. If element A is contained in element B and element A is clicked, the click event fires for element A, and then it bubbles and fires for element B. This is because you technically click both elements.

So basically, if they click on the link, the click event bubbles up to the tr element. Depending on how quickly your next page loads from a click, the tr click event may occur.

You can stop the bubbles inside the event handler: How to stop the event propagation using the onclick built-in attribute?

+5
source

There are three main ways to handle JavaScript events:

  • Event handlers
  • Event listeners
  • Event delegation

Event handlers are things like onclick that fit directly into HTML. Event listeners use the addEventListener method to attach a list to an element and listen for events in the browser. The delegation of events (includes bubbles) according to your question and allows us to listen to the parent elements for events that occur with their children.

You are basically trying to combine # 1 and # 3 here. You can use any of the three, but C # 2 may be easier for you:

Try something like this:

 rows = document.getElementsByTagName("tr"); rows.('click', function(event) { window.location = '//edit.html?requestId=3339'; }; 

This post in JavaScript events will focus on a more detailed description of this question if you need to better understand 3 ways. (Disclaimer: I wrote it).

0
source

All Articles