Reputation: 4368
So my HTML looks like this :
<section id="nav-wrapper">
<div class="container">
<ul id="ul-main_wrapper">
<li class="item_1""></li>
<li class="item_2"></li>
<li class="item_3"></li>
<li class="item_4"></li>
<li class="item_5"></li>
<li class="item_6"></li>
<li class="item_7"></li>
<li class="item_8"></li>
<li class="item_9"></li>
<li class="item_10"></li>
<li class="close_clear">Back</li>
</ul>
</div>
</section>
I have a list that sits all onto one line so the CSS looks like :
#nav-wrapper {
width: 100%!important;
height: auto!important;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
overflow-x: scroll;
bottom: 80px;
}
#ul-main_wrapper li {
height: 20px;
width: 20px;
margin: 2px;
display: inline-block;
}
onClick of the last item in the list that is back i'm trying to get the list to scroll back to the first item. But can't find anything that works.
EDIT :
Here's a JSFiddle : https://jsfiddle.net/svuh0mvj/1/
Upvotes: 0
Views: 11427
Reputation: 585
If you are not using jquery, or don't want to use it, you could try to use .scrollIntoView()
MSDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
"The Element.scrollIntoView() method scrolls the current element into the visible area of the browser window."
though this is not implemented the same way in all the different browsers we got these days.
document.getElementsByClassName('item_1')[0].scrollIntoView();
Or you could assign an id to the first item, or pass this id: 'ul-main_wrapper' and pass it to this example function
function scrollToAnchor(anchor) {
var scrollLocation = document.location.toString().split('#')[0];
document.location = scrollLocation + '#' + anchor;
}
which will do the scrolling for you.
If you do use jquery, use the solution by mmm
Upvotes: 0
Reputation: 73271
Just use scrollTop():
$('.close_clear').on('click', function() {
$(window).scrollTop($('.item_1').offset().top);
})
Or with animate:
$('.close_clear').on('click', function() {
var body = $("html, body");
body.stop().animate({scrollTop:$('.item_1').offset().top}, '500');
})
To scroll to the left within your #nav-header
div, use:
$('.close_clear').on('click', function() {
var nav = $("#nav-wrapper");
nav.animate({scrollLeft: $('.item_1').offset().left}, '500');
})
Upvotes: 3