Matt Rockwell
Matt Rockwell

Reputation: 456

How to disable a click on a link from also calling a JavaScript event that is hooked up to its parent container?

I have a row inside of a table in html that is hooked up to the following JavaScript function:

<script type='text/javascript'>
        $(window).load(function () {
            $(".clickable").click(function () {

                $(this).next().toggle();

            });
        }); 

This function expands some content directly below this row. I also have a link in this row that is used to click through to another page. It looks like this:

enter image description here

When I click the link it will quickly expand the content right before it navigates to the page that it is supposed to go to.

How can I change it so that if the link is clicked, it goes to that page without calling the JavaScript function that expands the extra content?

Upvotes: 2

Views: 318

Answers (1)

Jamiec
Jamiec

Reputation: 136104

On the link, you want to stop propagation:

$('.myNavLink').click(function(e){
   e.stopPropagation();
});

Doc link: http://api.jquery.com/event.stopPropagation/

EDIT As you're having trouble implementing this here is a live example:

http://jsfiddle.net/Vs5B8/

You'll see it has a table with 1 row, with a link in one of the cells:

<table>
    <tr class="clickable">
        <td> one </td>
        <td> two </td>
        <td> <a href='http://www.google.co.uk' class="myNavLink"> click me </a> </td>
    </tr>
</table>

I have hooked up a click event on the row:

$('.clickable').click(function(){
   alert("row click");
});

Therefore a click anywhere in the row will alert row click, and even do so when you click the hyperlink. However adding a click event to the a to stop propagation will stop this behaviour (ie, not show the alert when clicking the link):

$('.myNavLink').click(function(e){
   e.stopPropagation();
});

Upvotes: 5

Related Questions