views:

50

answers:

4

I had a image which calls add_cart() javascript function when onclick()

<img src="images/add.png" onclick="add_cart()">

I want the user to click the image only one time. When the user clicks it first time, add_cart function should be called. If he clicks second time NO EVENT SHOULD HAPPEN

Plz help, any help will be appreciated

A: 
window.onload = function() {
    document.getElementById('myImageId').onclick = handleImageClick;
}

var handleImageClick = function(e) {
    var target;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    if(target) {
        target.onclick = function(){}

        // do your stuff here
    }
}
mmanco
+2  A: 
<img src="images/add.png" onclick="add_cart(); this.onclick=null;">
Anurag
A: 

Using

<img src="images/add.png" onclick="this.onclick = function(){};add_cart();">
Bang Dao
A: 

If you want to use jQuery they have a method called one. It binds an event and the event is only usable once. http://api.jquery.com/one/

Codler