Open url with section targeting with jQuery and HTML 5

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

Let's 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 your page has multiple URLs. For example, you have a homepage with 3 alias below.
  • www.domain.com/homepage
  • www.domain.com/home
  • www.domain.com/homeindex

the three URLs above actually refer to one section on the homepage. So whenever visitors accesses the homepage with either one URL above, the browser will point to the correct section on the homepage. Someone will question how is it possible one page can have multiple URL? Yes, it is true, some websites already implement it.
Refer to this article about push state 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


Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example