1

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!

2
  • what does console.log($("."+sections[i])) output? It should tell you what the selector is and the length (amongst a number of other things). Commented Jul 5, 2013 at 4:06
  • 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 Commented Jul 5, 2013 at 4:25

1 Answer 1

2

The reason why your code doesnot work is because you are just registering the event in the for loop but not creating the closure variable i to be used in the respective handler. By the time your handler executes. "i" will be 3, after the last iteration increment of the for loop (after registering the event for the last element in the array) and it stays there so you are trying to look for sections[3] always which is undefined.

Keep it simple:

Join the selectors at once and just register your handler once, and inside your handler you are trying to referring to its own id by doing sections[i] you could just use this.id to get the id and use it in the handler.

var sections = ["about", "photography", "contact"];
var selector = '#' + sections.join(',#'); //get your selector joined here.

    $(selector).click(function (e) {
        e.preventDefault();
        var id = this.id; // in your code sections[i] is same as id of the clicked element. SO just use this id.
        if (!$(".current").hasClass(id)) { 
            $("body").css("overflow-x", "hidden");
            $(".current").animate({
                left: '-1500px'
            }, 500).slideUp(500);
            $("." + id).animate({
                left: '+3000px'
            }, 1).delay(500).slideDown();
            $("." + id).animate({
                left: '0px'
            }, 500, function () {
                $(".current").removeClass("current");
                $("." + id).addClass("current");
                $("body").css("overflow-x", "visible");
            });
        }
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Looks much cleaner, runs beautifully, and gets rid of the for loop. Thank you! But I am still not clear on why my original code did not work. :/
@B.B. You are welcome. i explained in the first para. do a console.log(i) inside your handler you will see it printing 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.