I'm trying to scroll an hidden element before I show it. This is the code i'm working with:
<div class="main">
<div class="bg">
</div>
</div>
.main {
display:none;
position:abolsute;
width:250px;height:250px;
overflow:scroll;
}
.bg {
background: blue url(http://defaulttester.com/img/bg-landing-mario.jpg);
width:1200px;
height:800px;
}
$(".main").scrollTop($(".bg").height()/2);
$(".main").scrollLeft($(".bg").width()/2);
IT works fine if its showing but if its display:hidden
it will simple not work. Is there anyway to avoid this and make it work?
JSFiddle: http://jsfiddle.net/dpjzJ/
An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .
scrollTop is deprecated in strict mode.
You can use element. scrollTop and element. scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.
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.
Use visibility: hidden;
or some class like this instead:
.hide {
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
}
Or this (from Boilerplate):
.visuallyhidden {
position: absolute;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px; width: 1px;
margin: -1px; padding: 0; border: 0;
}
Something with display: none;
has no location on the page, as you probably knew.
Check out this article on the subject.
If your goal is to just set scrollLeft and scrollTop to 0(since that was my goal), one very hacky solution is to follow these steps:
scrollTop and scrollLeft will now be set back to 0 even though they are invisible.
function resetScroll(element) {
element.parentElement.replaceChild(element,element)
}
This will set both scrollTop and scrollLeft to 0 even if display none.
Example use:
resetScroll(document.getElementById("my_scroll"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With