Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 an element with id="stop" and when user clicks on it I want to change an onclick attribute on element which has id="next".

If someone knows where is the solution please help!

like image 844
Shark Avatar asked Apr 25 '11 18:04

Shark


3 Answers

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.

like image 66
Felix Kling Avatar answered Sep 22 '22 14:09

Felix Kling


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

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}
like image 37
Tim Avatar answered Sep 22 '22 14:09

Tim


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

$('#stop').click(function() {
    $('next')[0].setAttribute('onclick','stopMoving()');
}
like image 37
Artnik Avatar answered Sep 22 '22 14:09

Artnik