Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery Scroll to class name

I have the Html code like below,

<div data-stored="storenow" data-save="save" class="saveIcon" data-unique="game">Save</div>

And I write the jquery to scroll to the gameNo 456 like below.

var container = $("html,body");
var scrollTo = $(this).find('.saveIcon').attr('data-unique', 456);

 container.animate({
    scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});

I am using jQuery version 1.9. I am getting error in console:

Cannot read property 'top' of undefined

Is that not possible to scroll to class name instead of id?

But it is working fine in Firefox. But not in chrome or IE.

I try to find the solutions from stackoverflow. But all other solutions are different than my case.

like image 814
alagu Avatar asked Jun 24 '14 15:06

alagu


People also ask

How do I scroll to a specific div?

The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser.

How do I add a class to my scroll?

addClass('newClass'); } else { $('#dynamic'). removeClass('newClass'); } }); This allows you to add and/or remove classes after the user has scrolled down a certain amount in a page. In this case, fill background with orange after scrolling 50px down.

Why is scrollTop not working?

If your CSS html element has the following overflow markup, scrollTop will not function. To allow scrollTop to scroll, modify your markup remove overflow markup from the html element and append to a body element.


2 Answers

You are not targeting a DOM object, you are targeting a string.

scrollTo = $(this).find('.saveIcon').attr('data-unique', 456); -> this is wrong

So, while you are trying to target an element, you are actually setting the 'data-unique' to the '.saveIcon' element.

Try this:

scrollTo = $('.saveIcon');

Working code:

var $container = $("html,body");
var $scrollTo = $('.saveIcon');

$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop(), scrollLeft: 0},300); 
like image 142
RazvanDH Avatar answered Sep 18 '22 16:09

RazvanDH


have you looked at scroll to view function?

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

element.scrollIntoView(true);
like image 23
vico Avatar answered Sep 21 '22 16:09

vico