american-ninja-warrior
american-ninja-warrior

Reputation: 8195

jquery: how to scroll a div by n pixels

Using jQuery, how do you scroll a div by N more pixels?

So far I tried

$("div.foo").scrollTop(75);   //scroll down by 75 pixels

Upvotes: 4

Views: 10022

Answers (3)

David Voráč
David Voráč

Reputation: 1421

If you are looking for Vanilla JavaScript solution like I was, here it is.

const selectedElement = document.querySelector('div.foo');
selectedElement.scrollTop = 75;

querySelector documentation, scrollTop documentation

Upvotes: 7

Max Pauly
Max Pauly

Reputation: 168

From the jQuery docs for scrollTop:

Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.

The version of the function you are calling sets the vertical position of the scroll bar from the top of the element, not from the current position. So in order to scroll down from the current position you first have to retrieve your current position. There are a few ways to do that, but you could do something like:

var $foo = $("div.foo");
$foo.scrollTop($foo.scrollTop() + 75); // scroll 75px down from current

Upvotes: 7

orbit
orbit

Reputation: 1296

the following code may help and you may see this link . and you can pixel value from window atrributes.Thank you.

var d = $('#div1');
d.scrollTop(d.prop("scrollHeight"));

Upvotes: 1

Related Questions