Reputation: 3559
Hello using Jquery
how can i scroll an element (with overflow
) to children element ?
<span id="gran">
<span id="parent">
<div class="a">
Casa
</div>
<div class="a">
Casa
</div>
<div class="a">
Casa
</div>
<div class="a">
Casa
</div>
<div class="a">
Casa
</div>
</span>
</span>
#gran {
overflow: auto;
}
I want to scroll #gran to third element with class a
so i tried this but doesn't work:
$("#gran").scrollTo('#parent > div:nth-child(3)');
I hope in your help :) Thanks a lot and sorry for my english
Upvotes: 1
Views: 1060
Reputation: 24001
This is how it can be done
You need to set max-height
with overflow : auto
to let the element scrollable without that it will keep extending without scrollbar .. if you need to use the document/body scrollbar use $('body , html')
Smooth scroll to div id jQuery
You need to use animate()
function with scrollTop
and offset()/position()
//$("#gran").scrollTo('#parent > div:nth-child(3)');
$(document).ready(function(){
$('#gran').animate({
scrollTop: - $('#gran').offset().top + $("#parent > div:nth-child(3)").offset().top
}, 2000);
});
#to_remove{
background : red;
height : 100px;
}
#gran {
overflow: auto;
max-height : 500px;
}
.a{
height : 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="to_remove"></div>
<div id="gran">
<div id="parent">
<div class="a">
Casa 1
</div>
<div class="a">
Casa 2
</div>
<div class="a">
Casa 3
</div>
<div class="a">
Casa 4
</div>
<div class="a">
Casa 5
</div>
</div>
</div>
Upvotes: 2