Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery click inside <a> tag not working

My HTML code is

<a href='someValidLink' class="link">
    <img src='imageUrl'/>
</a>

and js script is

$('.link').click(function(e) {
    console.log("log something");
    return false;
});

Now clicking on the image should not redirect me to new page, but somehow it is

So far i have tried putting same class in img tag, using id instead of class, e.preventDefault instead of just returning false etc...

However if I remove the img node and put some text instead then it is working fine as it should, but what to do for preventing image links from redirecting

like image 844
rockstarjindal Avatar asked Oct 19 '13 19:10

rockstarjindal


1 Answers

If the HTML is being created dynamically, you cannot use a standard static binding which will only work on elements that exist and can be selected at DOM ready.

$(document).ready(function() {
    $(document).on("click", ".link", function(e) {
        console.log("log something");
        return false;
    });
}

http://api.jquery.com/on/

jQuery's "on" is the preferred way to handle this.

like image 127
Chris Allen Avatar answered Sep 28 '22 08:09

Chris Allen