0

The alert doesn't get fire because the openClose() function is missing and it throw an error.

<div class="spoilertop" onclick="openClose('cbd6c32c3118dbbdc3fbdc37e0805292')">

How I can I unbind or better remove the onclick tag?

$('.spoilertop').click(function(){
    $(this).attr('onclick','').unbind('click');

    alert('f');
})

I tried $(this).attr('onclick','').unbind('click'); and e.preventDefault() but doesn't work.

mike19911
  • 101
  • 1
  • 7
  • 1
    can't really understand this : I want to add a click event to a class but the tag is from somewhere else – beNerd Dec 08 '14 at 10:25
  • see this: http://stackoverflow.com/questions/1756425/prevent-onclick-action-with-jquery – beNerd Dec 08 '14 at 10:28

2 Answers2

2

Your code works - the onclick attribute is removed after the first click fires. However, onclick fires before the click in jQuery so openClose will always fire the first time, see this example. You'll see that the foo alert only shows for the first click.

To avoid this you either need to remove that attribute from the element on load, or better yet, remove it from the HTML completely.

To remove it from the .spoliertop elements on load, you can do this:

$(function() {
    $('.spoilertop').attr('onclick','').unbind('click');
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • I can't remove the attr because it's from somewhere else.. or you are saying i remove it before the click event? – mike19911 Dec 08 '14 at 10:29
  • I've added example code to show how to remove it on load of the page: http://jsfiddle.net/yg5790uw/1/ – Rory McCrossan Dec 08 '14 at 10:30
  • I've having problem to remove it coz I'm using ajax call then bind the result to the dom. I put in .finally() still couldn't get the onclick removed. – mike19911 Dec 08 '14 at 10:37
  • I'd suggest you open a new question detailing the full process you go through, including JSON calls etc. I'd say this question has been covered now. – Rory McCrossan Dec 08 '14 at 10:39
0
$('.spoilertop').click(function(){
    $(this).unbind('click');
    $(this).removeAttr('onclick');
    alert('Off');
});

Demo

Tegos
  • 405
  • 6
  • 14