Posted By

chrisguiblin on 08/19/12


Tagged

javascriptdividparametersvariablesurl


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


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


 / Published in: JavaScript
 

This code assumes a page is populated with divs with ids div1, div2, div_3 etc etc etc...

Some quick php to create 200 divs numbered as above:

  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  

You need to login to post a comment.