Murat Aşık Murat Aşık - 3 months ago 7
CSS Question

changing content with # mark

I have seen many web sites that has the system i am curious about.
System is like: There is only one page. If you click any link in menu the page slides to that area using # mark.

The url is usually like : example.com/#content1

I couldn't find any current example but i can summarize like this:

---- menu (usually fixed) -----

First content




Second Content




And so on.

If i click any link in menu. The page will slide to that area.

How can i do that?

Answer

You give ids to the elements that you want to target with the menu, and make those ids match the hash fragment (the #xyz).

E.g., this link:

<a href="#first">First</a>

when clicked will take the user to this element:

<div id="first">...</div>

You've said "sliding." By default, the page jumps there, rather than sliding. Sliding is accomplished by overriding the default behavior with an animation. Recommending a specific plugin is not on-topic for SO, but for instance here's a simple example with jQuery (which you tagged in the question):

// Handle clicks on our navigation anchors
$(".nav a").on("click", function(e) {
  // Get the href attribute, which will be #first or similar, and get the element using that
  // as a CSS selector
  var hash = this.getAttribute("href");
  var target = $(hash);
  // Tell jQuery to animate us to that location. Note that some
  // browsers animate body, others `html`, so we 
  // do both
  $('body, html').animate({
    scrollTop: target.position().top
  }, 800);
  
  // Prevent the usual jump
  e.preventDefault();
  
  // Set the hash *without* causing the jump (for bookmarks and such)
  if (history && history.replaceState) {
    history.replaceState(null, null, hash);
  }
});
.fill {
  height: 5em;
}
<ul class="nav">
  <li><a href="#first">First</a></li>
  <li><a href="#second">Second</a></li>
  <li><a href="#third">Third</a></li>
  <li><a href="#fourth">Fourth</a></li>
</ul>
<div class="fill">
  Some content to fill space
</div>
<div id="first" class="fill">This is the first target</div>
<div id="second" class="fill">This is the second target</div>
<div id="third" class="fill">This is the third target</div>
<div id="fourth" class="fill">This is the fourth target</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<div class="fill">More filler</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments