Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the click handler of this image?

I have the following HTML:

<img src='img.png' onclick='document.write("Hi there!")' />

...and the following JavaScript:

$(document).ready(function() {

    // Change the click handler
    $('img').click(function() {

        alert("Hi there!");

    });

});

What I am expecting to happen is that the click handler for the image is replaced and that clicking it will produce an alert dialog. Instead, the page content changes, as dictated by the click handler in the tag.

How can I change the click handler at runtime?

Note: Here is an interactive demo you can play with:
http://jsfiddle.net/ykmaG/

like image 698
Nathan Osman Avatar asked Feb 25 '23 05:02

Nathan Osman


1 Answers

You need to remove the original onclick:

$('img').removeAttr('onclick').click(function() { ... });
like image 176
SLaks Avatar answered Mar 08 '23 16:03

SLaks