3
\$\begingroup\$

Intention: Automatically scroll the window to the top of a DOM element when the document is loaded.


via JavaScript:

window.onload = function(){
    document.getElementById('foo').scrollIntoView(true);
};

Questions and Concerns:

  • Is there a more compact and/or smarter technique?
  • Does this technique pose issues or potential conflicts?
  • With the above said, should it matter where on the document it's loaded? If so, what's the best location? I've already studied this question and its references closely and I'm led to believe it's best to have this kind of script located toward the bottom the document.
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Three concerns:

  1. Error if there is not element called 'foo'

  2. I have no idea what that boolean in the function is for. Passing booleans at parameters is very bad. I have no idea what happens if I were to pass it false or any other value. Not scroll into view? I know that it is for topAlign but why not leave it out.

  3. you can't use the onload event again without messing it up.

\$\endgroup\$
12
  • 1
    \$\begingroup\$ "If true, the scrolled element is aligned with the top of the scroll area. If false, it is aligned with the bottom." source \$\endgroup\$ Commented Mar 9, 2012 at 0:31
  • \$\begingroup\$ Obviously, the element won't be called 'foo' in production. Where would the second onload event be placed and why is it an improvement? \$\endgroup\$ Commented Mar 9, 2012 at 0:32
  • \$\begingroup\$ 'foo' by any other name.. is still 'foo'... you are chaining behavior when it could break your code. I am recommending doing a bit of checking like: ` if (el = document.getElementById('foo')) el.scrollIntoView(); \$\endgroup\$ Commented Mar 9, 2012 at 1:03
  • \$\begingroup\$ @gmeben it is topAligned by default... that is my point. \$\endgroup\$ Commented Mar 9, 2012 at 1:08
  • 1
    \$\begingroup\$ I feel adding a conditional to test for a single element that's known to exist is a bit overkill. Compactness is one of my goals. My concerns for potential conflict comes down to whether or not scrollIntoView or the way I'm initializing the script is known to cause behavior issues, and if so, is there an alternative method? \$\endgroup\$ Commented Mar 9, 2012 at 2:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.