johnathan Mhehdi johnathan Mhehdi - 3 months ago 7
Javascript Question

Why JS doesn't want to scroll?

here is my code:

function trailer() {
window.scroll(0,1750);
}


and the html

<li> <a href="#" onclick="trailer()">Trailer GTA 4</a></li>


..When I click on the link, it scrolls to (0,0) instead of scrolling to (0,1750)
why ???

Answer

You have two possible solutions, you can link the ID of the element in a a tag, as such,

HTML Example

<a href="#myDiv">Jump to DIV</a>

<div id="myDiv">DIV!</div>

Example

JSFiddle

You need to prevent the default behavior of the link by using return false or event.preventDefault();.

The JavaScript alternative is to use scrollTo, though as @mplungjan has pointed out the difference between scroll and scrollTo is no difference.

Comments