Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollTop & scrollLeft do not work on display:none elements

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/

like image 412
Kivylius Avatar asked Jun 11 '13 15:06

Kivylius


People also ask

What is scrollTop?

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 .

Is scrollTop deprecated?

scrollTop is deprecated in strict mode.

How do I get scrollTop value?

You can use element. scrollTop and element. scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.

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.


3 Answers

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.

like image 121
dezman Avatar answered Oct 24 '22 00:10

dezman


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:

  • Get a reference to the element you want to reset.
  • Get a reference to the element's parent.
  • Remove the element from the parent.
  • Append the element back to the parent.

scrollTop and scrollLeft will now be set back to 0 even though they are invisible.

like image 35
prashn64 Avatar answered Oct 23 '22 23:10

prashn64


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"))
like image 2
Terren Avatar answered Oct 23 '22 22:10

Terren