Below is some jQuery code I wrote for an animated navigation scheme.
The code worked well when I had it written out for testing like so:
$("#about").click(function(e) {
e.preventDefault();
if ( !$(".current").hasClass("about") ){
$("body").css("overflow-x","hidden");
$(".current").animate({left:'-1500px'}, 500).slideUp(500);
$(".about").animate({left:'+3000px'}, 1).delay(500).slideDown();
$(".about").animate({left:'0px'}, 500, function(){
$(".current").removeClass("current");
$(".about").addClass("current");
$("body").css("overflow-x","visible");
});
}
});
But when I tried to put it in a loop and use variables in the jquery selectors, it stopped working.
Each string in the sections array corresponds to an anchor tag's id and its matching div element's class.
It runs up until line 7, but lines 8 and 9, starting with $("."+sections[i]), do not work.
var sections = ["about","photography","contact"];
for (var i=0; i<sections.length; i++) {
$("#"+sections[i]).click(function(e) {
e.preventDefault();
if ( !$(".current").hasClass(sections[i]) ){
$("body").css("overflow-x","hidden");
$(".current").animate({left:'-1500px'}, 500).slideUp(500);
$("."+sections[i]).animate({left:'+3000px'}, 1).delay(500).slideDown();
$("."+sections[i]).animate({left:'0px'}, 500, function(){
$(".current").removeClass("current");
$("."+sections[i]).addClass("current");
$("body").css("overflow-x","visible");
});
}
});
}
console.log( $("."+sections[i]).attr("class") ) gives me undefined. I think the problem is with the selector, but I can't figure out what it is. The id selector seems to work fine, just not the class selector. Any suggestions appreciated!
console.log($("."+sections[i]))output? It should tell you what the selector is and the length (amongst a number of other things).console.log($("."+sections[i]))returned[prevObject: x.fn.x.init[1], context: document, selector: ".undefined", jquery: "1.10.1", constructor: function…] context: document length: 0 prevObject: x.fn.x.init[1] selector: ".undefined" __proto__: Object[0]I got the code to run with an answer below, but I would still like to figure out why it didnt work in the first place, since I am just starting out with jQuery