I am reading contents from JSON file and adding to div with unique IDs. I need to call jquery slide down effects to each div. Lets us consider the case, on clicking (div id=A1) it should slide down and show (div id=B1), in that way I have div with IDs A(1..N) and B(1..N).
var i=1;
$.each(items, function (index, item) {
$(document).ready(function(){
$("#A"+i).click(function(){
$("#B"+i).slideToggle();
});
});
$("#allContents").append('<div id="A'+i+'">' + item.Name + '</div>');
$("#allContents").append('<div id="B'+i+'">' + item.Details + '</div>');
i++;
});
This is the closest code I could derive to, but it is not working. If anyone could help me fix or suggest a better way to get this thing working it would be great. Thanks a lot!
A little explain
div[id^=A]point out thosedivwhoseidstart withA.this.idretrieve theidof clicked element.this.id.replace('A','')replaceAform theidand get the numeric index which equal to index ofB.$('div#B' + this.id.replace('A',''))point to elementid=B1,id=B2and so on.Full code
Working Sample
Note
As you’re creating
divfromA(1..N)andB(1..N)dynamically so you need delegate event handler (aka live event).Syntax of jQuery
.on()for delegate event is like following: