I just did my first jQuery plugin which hides content that is too long.
You can view the fiddle at http://jsfiddle.net/denislexic/bT4dH/6/.
When you check it out and click on the “…”, you ll notice that the first one toggles three times, the second toggles two times and the third one is correct (so just once).
I have no idea why it’s doing that. I tried e.preventDefault(), stopPropagation(), etc. Nothing seems to work.
Here is the code that seems to be the problem:
$("." + opts.clickZoneClass).on("click", function (e) {
_debugger(1);
var element = $(this).parent('div').children('div.status');
// I know you can use is(':visible'), but it doesn't work in Internet Explorer 8 somehow...
if (element.hasClass('open')) {
_debugger(2);
element.animate({
height:element.attr('data-toggle')
}, 'fast');
//$(this).html();
element.removeClass('open');
} else {
_debugger(3);
element.animate({
height:element.attr('data-height')
}, 'fast');
element.addClass('open');
}
return false;
});
It’s because you’re executing the above code in a $.each loop. If you pull out your binding code and just run it once your plugin works great.
I just pulled it out and moved it to the document ready function to illustrate…
http://jsfiddle.net/bT4dH/10/