-1

I created a function but then realised I had to call it three times with two different parameters so I decided to create two different arrays and modify the function so it is called once. After modifiying the function it doesn't work so I am not sure what is happening. Here it is:

function scrll(selector,speed){
                for (var i = 0; i < selector.length; i++){
                    var findIt = '.find("a")';
                    var selected = selector[i];
                    selected += findIt;
                    selected.click(function(e) {
                        e.preventDefault();
                        var section = $(this).attr("href");
                        $("html, body").animate({
                            scrollTop: $(section).offset().top - 54
                        },speed[i]);
                    });
                };
            };
var selector = ['$(".navbar")','$(".click")','$("#foot")'];
            var speed = [2000,1000,2000];
            scrll(selector,speed);

Here is a jsfiddle example: http://jsfiddle.net/theMugician/31fws6kd/16/

Biffen
  • 6,249
  • 6
  • 28
  • 36
Grzes Slania
  • 588
  • 1
  • 11
  • 28

1 Answers1

1

You seem to be under the impression that you can combine some strings together and the result will be what you would have gotten by executing the contents of that string.

JavaScript doesn't work like that.

This is how you can use selectors like you were trying to do.

function scrll(selectors, speed) {
    for (var i = 0; i < selectors.length; i++) {
        var selected = $(selectors[i]);
        var link = selected.find("a");

        link.click(function(e) {
            e.preventDefault();
            var section = $(this).attr("href");
            $("html, body").animate({
                scrollTop: $(section).offset().top - 54
            }, speed[i]);
        });
    }
}
var selectors = [".navbar", ".click", "#foot"];
var speed = [2000, 1000, 2000];
scrll(selectors, speed);

There's still a bug here, because i is a closure variable and by the time the events run, it will have the value 3 and everything will be broken. An easy way to fix this is to use forEach():

function scrll(selectors, speed) {
    selectors.forEach(function (selector, i) {
        var selected = $(selector);
        var link = selected.find("a");

        link.click(function(e) {
            e.preventDefault();
            var section = $(this).attr("href");
            $("html, body").animate({
                scrollTop: $(section).offset().top - 54
            }, speed[i]);
        });
    });
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thank you for the answer. The solution was simpler than I thought. I am still trying to fully grasp Javascript closures. – Grzes Slania Feb 12 '15 at 19:23