Scroll to specific div using a variable from the URL on page load


/ Published in: JavaScript
Save to your folder(s)

This code assumes a page is populated with divs with ids div_1, div_2, div_3 etc etc etc...

Some quick php to create 200 divs numbered as above:



Copy this code and paste it in your HTML
  1. <script languate="javascript" type="text/javascript">
  2.  
  3. //Get the values from the url variable id
  4. //(getUrlVars Code URL: http://snipplr.com/view/19838/get-url-parameters/)
  5. function getUrlVars()
  6. {
  7. var vars = {};
  8. var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
  9. vars[key] = value;});
  10. return vars;
  11. }
  12.  
  13. //scroll to the specific div, assuming each div is named "div_(number)"
  14. function scrollToID()
  15. {
  16. document.getElementById("div_" + id).scrollIntoView();
  17. }
  18.  
  19. var id = getUrlVars()["id"];
  20. window.onload=scrollToID(id);
  21.  
  22. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.