Which of these scrollTo's is correct?

Also, does it have to be placed in both the javascript and the html for it to work in the code?

1

<div onclick="scrollToTop()">Element</div>

function scrollToTop(){
    window.scrollTo(0, 0);
}

2

<div onclick="window.scrollTo(0, 0);">Element</div>

function scrollToTop(){
    window.scrollTo(0, 0);
}

You will normally write the in JS script tags, and call them in the onclick or any other event.

In this case whichever you use is indifferent, so I’d go for the simplest (shortest) case.

Most of what you ask, can potentially be found by testing which is good for learning, I found jsfiddle great for that. It is not laggy as other sites.

1 Like

I have this just in the javascript, nothing in the html.

https://jsfiddle.net/arwp7Lhm/

function exitClickHandler() {
window.scrollTo(0, 0);
}

Would this need to be in the html also?

or, if it works without it, means I don’t need it?

<div onclick="window.scrollTo(0, 0);">Element</div>

In this example, there is a confusion. One thing is your own defined functions, another thing is the browser “pre-loaded” methods and apis.

This code:

window.scrollTo(0, 0)

Is understood by the browser

But your custom code:

<div onclick="myFn"></div>

is not as the browser has no idea what myFn is unless you define it elsewhere.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.