3

I have div which has an onlcick event. Now when i click the div i want to change its onlick function with .click attribute of jquery. I am able to change it dynamically, but when i apply it the new event also gets fired. Is there any work around so that the new is not fired but just applied to the div with new function? Here is what i am trying to do

i have a div

<script type="text/javascript">

function testMe(data)
{
   alert(data);
   $('#testMe').unbind('click');
   $('#testMe').click(function(){ testMe('2');  });
}

</script>
    <div id='testMe' onclick='testMe(1)' >click on me, I will disappear.</div>

when I execute theabove code i still get value 1 om alert box THANKS EveryOne

Also i tried the below code but it is not working for me

 function testMe(data)
{
   alert(data);
   $('#testMe').unbind('click');
   $('#testMe').click( testMe(2) );
}

Though the code is updating the onlick event from 'testMe(1)' to 'testMe(2)' but it continuously alerts value 2. The work around this problem is traditional JS script code as:

 document.getElementById('testMe').onclick =  testMe(2) ;

And its working without alerts.

1
  • Could you show the code you're using? Commented Oct 29, 2010 at 14:44

4 Answers 4

6

use the 'one' function

$('element').one('click',function()
{
    alert('old click handler');
    $(this).click(function(){
        alert('new click handler, yarrrr');
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

interesting way to remove the need to write the unbind line of code...i didn't know of this
one is intended to be fired only once (i dont get why they didnt call it once, but still ^_^)
2

maybe try this.

$('div').click(function(){
    $(this).unbind('click');
    $(this).click(function(){
        // new click function here
    });
});

1 Comment

what if there are other click handlers which he dont want to remove ? doing this using namespaces would be more functional - $('div').bind('click.once', function() { $(this).unbind('click.once').click(function() { <new function> }); }); - or use the 'one' function i gave.
0

Try using the bind event http://api.jquery.com/bind/

If you want to remove the previous event use the unbind event: Best way to remove an event handler in jQuery?

Comments

0

unbind old functionality first. Than bind the new event to it should do the trick.

Do you mean the the event is also fired when you bind it to the element?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.