how to ignore first event and skip to second?

10,971

Solution 1

If you were using jQuery, it would be that simple (suppose you have set and id='row' for tr element, and id='link' for a element):

$('#row').click(someaction);
$('#link').click(function(event){event.stopPropagation()});

You can look at this example: http://jsfiddle.net/VDQMm/

Without jQuery, it is almost the same, but you have to get each element's handle first, then use addEventListener method to attach an event listener (make the row handler to use bubbling instead of capturing by setting the last parameter to false), and then the same old event.stopPropagation().

It would be something like this ( http://jsfiddle.net/VDQMm/2 ):

var row = document.getElementById('row');
var link = document.getElementById('link');
row.addEventListener('click',alert('clicked row!'),false)
link.addEventListener('click',function(event){event.stopPropagation()},false)

Solution 2

Add event.stopPropagation() to the mousedown event of the link. That will stop the event from bubbling up to the tr.

Here is an example.

Share:
10,971
Trevor
Author by

Trevor

Updated on June 05, 2022

Comments

  • Trevor
    Trevor almost 2 years

    I have a table-row that has a Javascript action attached to mouse clicks anywhere inside the table row:

    <tr onmousedown="someAction(this)">
        <td>cell 1</td>
        <td>cell 2</td>
        <td><a href="page2.html">cell 3</a></td>
    </tr>
    

    If a user clicks anywhere in the row, I want the Javascript action, someAction(this), to be followed. However, if a user clicks on the link to page2, then I want the action ignored and the link followed.

    Unfortunately, the action is being observed first, which happens to move the linked text's position just enough for the click to be dropped. In other words, the user cannot actually click on the link and go to page2, in this case.

    How can I disable the mousedown action for clicks over the link?

    Thanks!

    Update: Based on the answers, I ultimately included the following JavaScript in the end of the HTML, which registered an event handler to stop propagation as suggested, like so:

    ...
    <script type="text/javascript" language="javascript">
    //<![CDATA[
    function stopEvent(ev) {
        ev.stopPropagation();
    }
    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        links[i].addEventListener("onmousedown", stopEvent, false);
    }
    //]]>
    </html>
    

    This could have easily been included in the document's onload event, but the CDATA section was already required for other reasons, so I added what I needed here.

    Thanks for all the help and good suggestions! :)