Reputation: 513
Might be a duplicate but I cant seem to find the right answer.
I have a button, and when I press it, I want it to scroll to the li item that has an ID of '#li-1', and also have it hovered. I know my code is wrong but not really sure how to fix it (new to jquery). So how do I achieve the desired results?
Here's a jsfiddle link - https://jsfiddle.net/orb1vw28/7/
Thanks in advance
$(document).ready(function(){
$('.button').click(function(){
$('body').scrollTo('#li-1', 200);
$("#li-1").toggleClass("hov");
});
})
Upvotes: 2
Views: 96
Reputation: 7225
You can calculate the correct target position – the one which you scroll to – with the getScrollTargetPosition()
function in this gist (heavily commented, so no need to explain it here).
Based on that and the jQuery.scrollable plugin – which solves cross-browser issues as well as a bunch of scroll-related usability problems –, you'd end up with this code:
$( document ).ready( function () {
$( ".button" ).click( function ( event ) {
var $window = $( window ),
$scrollContainer = $( "#event-list" ),
$target = $( "#li-1" ),
targetPosition = getScrollTargetPosition ( $target, $window );
event.preventDefault();
$scrollContainer.scrollTo( targetPosition, {
complete: function () {
$target.toggleClass( "hov" );
}
} );
} );
} );
To see it in action, check it out in JSBin (result, source).
Upvotes: 1
Reputation: 2446
Ok, you have some problems in your code, but i made some minor changes and managed it to work.
JSfiddle wans't working for me, so i made you a pen.
http://codepen.io/filipemerker/pen/jbvxyY
The thing is that you need to pass a numeric value to "scrollTo", not a selector. I just calculated the difference between the parent scrolltop minus the LI element scrolltop. I also added an animation for you. Check it out.
$('#event-list').stop().animate({scrollTop:location}, '200', 'linear');
Upvotes: 1