Passing parameter to function in Javascript

365 views Asked by At

I want to call the following in my code somewhere.

scrollIntoViewElement(main-nav);

The following is the function:

// Element to scroll into view
scrollIntoViewElement(element) {
    document.getElementById('element').scrollIntoView();
}

The function should scroll the page into the view of the provided element id.

Is this correct? Or should it be...

// Element to scroll into view
scrollIntoViewElement(element) {
    document.getElementById("\'" + element + "\'").scrollIntoView();
}
1

There are 1 answers

0
T.J. Crowder On BEST ANSWER

The code scrollIntoViewElement(main-nav); means "Take the value of main, subtract the value of nav, and then call scrollIntoViewElement passing the result in as a parameter. If you want to pass in the string main-nav, you need quotes to tell the JavaScript parser you're using a literal string: scrollIntoViewElement("main-nav");

Within the function, you don't use quotes, because you want to use the value of the parameter, not the literal string "element".

So:

scrollIntoViewElement("main-nav");

and

// Element to scroll into view
scrollIntoViewElement(element) {
    document.getElementById(element).scrollIntoView();
}

This assumes you have an element with id="main-nav" in your document. It'll throw an exception if you don't, because getElementById will return null.