0

I am building a single page web application where I don't the require the url changing when clicking on the anchor tag that is linked to div in same page. div id gets added to the url. Kindly help in how to navigate to the div without changing the url.

This is my code so far:

$(document).ready(function () {

 
 $('a').on("click",function(e){
  
  
  window.location="#link5"
  e.preventDefault();
  e.stopPropagation();
  console.log(window.location);
  
 });
})
#login {
  position: absolute;
  top: 50%;
  left: 50%;
}

a {
  text-decoration: none;
  display: inline-block;
  padding-right: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="#">Link1</a>
 <a href="#">Link2</a>
 <a href="#">Link3</a>
 <a href="#">Link4</a>
 <a href="#">Link5</a>

 <h4>Content of the above links</h4>
 <div id="link1">
  <h3>Contents of #link1</h3>
  <p>Sample contents placed in the div #link1</p>
  <p>Sample contents placed in the div #link1</p>
  <p>Sample contents placed in the div #link1</p>
   
 </div>
 <div id="link2">
  <h3>Contents of #link2</h3>
  <p>Sample contents placed in the div #link2</p>
  <p>Sample contents placed in the div #link2</p>
  <p>Sample contents placed in the div #link2</p>
 
 </div>
 <div id="link3">
  <h3>Contents of #link3</h3>
  <p>Sample contents placed in the div #link3</p>
  <p>Sample contents placed in the div #link3</p>
  <p>Sample contents placed in the div #link3</p>
 
 </div>
 <div id="link4">
  <h3>Contents of #link4</h3>
  <p>Sample contents placed in the div #link4</p>
  <p>Sample contents placed in the div #link4</p>
  <p>Sample contents placed in the div #link4</p>
  <p>Sample contents placed in the div #link4</p>
  
 </div>
 <div id="link5">
  <h3>Contents of #link5</h3>
  <p>Sample contents placed in the div #link5</p>
  <p>Sample contents placed in the div #link5</p>
  <p>Sample contents placed in the div #link5</p>
  <p>Sample contents placed in the div #link5</p>
  
 </div>

http://jsfiddle.net/vkarthikcse/3duv3ozz/3/

CodingIntrigue
  • 65,670
  • 26
  • 159
  • 166
Karthik
  • 235
  • 3
  • 11
  • 2
    Possible duplicate: http://stackoverflow.com/questions/6677035/jquery-scroll-to-element ? – icke May 04 '15 at 09:48

2 Answers2

1

$http://jsfiddle.net/xovd9c8t/2/

with animation, using modern data- elements

This will give you a smooth transition while navigating to that part of the page. User experience will be amazing.

0

This should work: http://jsfiddle.net/3duv3ozz/4/

Of course right now it's hard coded to only work with one link, but you should get the idea:

$(document).ready(function () {
    $('a').on("click",function(e){

        var posTop = $("#link5").offset().top; //Get the position of the element you want to scroll to
        e.preventDefault();
        e.stopPropagation();
        $('html, body').scrollTop(posTop); //Scroll to that position
        console.log(window.location);

    });
})
Jonas Grumann
  • 9,697
  • 2
  • 17
  • 35