jQuery .toggle() button only toggles every other element -


my code generates different elements on click of 1 button. 1 of elements generated buttons want toggle on , off parts of text generated. jquery .toggle() function works first element generated. works latest element generated , every other 1 before (say, 5 elements generated, work on 5, 3, 1 not 2 , 4). seems issue class, think, because can, web console in firefox use .toggle() command manually remove it. guess mean button not triggering. @ loss.

here jsfiddle showing behaviour http://jsfiddle.net/jalbr/1/ here code:

recursioncounter = 0 $(document).ready(function(){  $("#compute").click(function(){      //add toggle data     $("#buttons").append("<input type=button value=\"toggle\" class=\"removebtn\" id=\"recursion" + recursioncounter + "\">")     //add recursion counter div element     $("#recursion" + recursioncounter).data("recurs", recursioncounter)      //make new section toggling purposed     $("#results").append("<o" + (recursioncounter) + ">")     //this code write results screen     $("o" + (recursioncounter)).append("<br><br> <b>recursion " + (recursioncounter) + "</b>")     $("o" + (recursioncounter)).append("<br> symmetric")  //toggles recursion info $(".removebtn").on("click", function() {     var count = $(this).data("recurs")     $("o" + count).toggle()    })   recursioncounter = recursioncounter + 1 })  }) 

with appropriate 's on html, seen in fiddle.

i think due nesting call of click inside of click? tried moving out of "compute" click, wouldn't toggle @ (maybe because of scope?) but, problem shows on toggling. if make .toggle() .hide(), buttons work. if separate show/hide buttons, works fine. if write if..else statement toggling behaviour (using .is(:visible)) not work.

jquery doesn't replace event handlers. if attach 2 event handlers:

$('#foo').click(function() {     console.log('a'); });  $('#foo').click(function() {     console.log('a'); }); 

and click on #foo, both of them fire.

each time add new element, every .removebtn element gets another event handler toggles visibility of respective element. when end clicking on button, of event handlers fire 1 after , element toggles or odd number of times, depending on how many buttons you've added.

to fix it, remove event handler out of .click() callback , attach event delegation:

$('#buttons').on("click", ".removebtn", function () {     var count = $(this).data("recurs");     $("o" + count).toggle() }); 

event delegation attaches event handler #buttons, delegates event element clicked. account elements match selector, if they're added later on.

demo: http://jsfiddle.net/jalbr/4/


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -