Skip to content Skip to sidebar Skip to footer

Jquery Attr('onclick')

I'am trying to change 'onclick' attribute in jQuery but it doesn't change, here is my code: $('#stop').click(function() { $('next').attr('onclick','stopMoving()'); } I have a

Solution 1:

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

Solution 2:

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

Solution 3:

The easyest way is to change .attr() function to a javascript function .setAttribute()

$('#stop').click(function() {
    $('next')[0].setAttribute('onclick','stopMoving()');
}

Solution 4:

Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use

$('#next').die().live('click', stopMoving);

this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.

Post a Comment for "Jquery Attr('onclick')"