1

I am currently trying to implement a menu with many clickable buttons - appetizers, soups, etc. By using parameters, I can send the type of food to my JavaScript.
These are the buttons.
http://puu.sh/kugEs/5048221343.jpg

This is the code when I click on appetizers.

function scroll(type) {
    var test = "('#" + type + "')";
    alert(test); //('#appetizers')

    $("html, body").animate({ scrollTop: $test.offset().top-150 }, 600); //this doesnt work
    $("html, body").animate({ scrollTop: $('#appetizers').offset().top-150 }, 600); //this works
}

Of course I want to make it so that I don't have to manually use the working line. I want to use the one that doesn't work that it can be applied to all buttons running the same function with only different parameters.

How can I use the var test in order to run the line that doesn't work?

3
  • In creating your variable, test, you are using parentheses as string. Instead, define test as just the selector you want: test = '#'+type. Then $(test).offset().top.... Commented Oct 1, 2015 at 2:41
  • You can use inspector element in google chrome and add a break point to your code. i think that is probably the easiest way. Commented Oct 1, 2015 at 2:41
  • Thanks for the quick replies everyone! fixed it. Commented Oct 1, 2015 at 2:47

3 Answers 3

4

You should use $ and take care about your quotes::

var $test = $('#' + type);  // Now it's a jQuery Object

In your example:

function scroll(type) {
    var $test = $('#' + type);
    $("html, body").animate({ scrollTop: $test.offset().top-150 }, 600);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You should define $test as an object, instead of a string.

function scroll(type) {
    var test = $('#' + type);
    alert($test.attr("id")); // appetizers
    $("html, body").animate({ scrollTop: $test.offset().top-150 }, 600);
}

Comments

-1

Try it with this code. It should work.

function scroll(type) {
    var test = "('#" + type + "')";      
    alert(test); //('#appetizers')
    $("html, body").animate({ scrollTop: $('#'+type).offset().top-150 }, 600);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.