Saturday, 3 October 2015

Open url with section targeting with jQuery and HTML 5

Leave a Comment
Recently I have some project that require to target certain section in my HTML 5 project. after do some testing and research on google how to do it, finally I think this snippet is the best that can work in most modern browser.

Lets see the code .

HTML sample 

  <section id="mainIntro" class="" target-url="<target url>">  
   :  
   :  
   :  
 </section>  




JQuery Code Snippet

 <script> $(window).load( function () {  
   setTimeout(function(){  
    var current = window.location.href;  
    current = current.substr(current.lastIndexOf('/') + 1);  
    $( "section" ).each(function() {  
      var targetURL = $(this).attr("target-url");    
      if(targetURL == current){  
      var mainContentH = $(this).offset().top + 1;     
      $('body,html').animate({  
      scrollTop: mainContentH  
      }, 150/*this is where you can control of page move to target*/ );  
      return false;   
    }  
    });  
   }, 100 /*set timeout before function execute. This is to handle some end user with slow internet*/);   
 });  </script>


NOTE : This method will work if you page have multiple URL. Example you have homepage.
www.domain.com/homepage
www.domain.com/home
www.domain.com/homeindex

the three url above actually refer to one page in your website. So whenever end user enter either one url above, browser will point to the correct section in your website. Someone will question how is it possible one page can have multiple url? Yes it is true, some website already implement it.
Refer this article about pushstate in HTML5

  1.  InfiniteScroll Push State.
  2.  https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
  3. https://blog.twitter.com/2012/implementing-pushstate-for-twittercom







By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.