Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to div after click on About or Contact in my menu?

How to scroll to div (e.g: #about, #contact) after click on About or Contact in my menu?

<div class="masthead">
    <ul class="nav nav-pills pull-right">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
    <h3 class="muted">Name site</h3>
</div>
like image 390
vavelde Avatar asked Jan 25 '13 14:01

vavelde


People also ask

How do I make Div scroll automatically?

Set the overflow-x:hidden; and overflow-y:auto; that will automatically hide the horizontal scroll bar and present only vertical scrollbar. Here the scroll div will be vertically scrollable. Example 1: html.

How do I scroll to a particular div on button click?

The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.

How do I scroll to a specific section in HTML?

By using an href attribute inside an anchor tag you can scroll the page to a specific element using a # in front of the elements id name.

How do you auto scroll to a specific point on a page react?

To scroll to an element on click in React:Set a ref prop on the element you want to scroll to. Set the onClick prop on the other element. Every time the element is clicked, call the scrollIntoView() method on the ref object.


2 Answers

Your html:

<div class="masthead">
    <ul class="nav nav-pills pull-right">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="#contact">Contact</a></li>
    </ul>
    <h3 class="muted">Name site</h3>
</div>
<div id="about">about</div>
<div id="contact">contact</div>

Your javascript:

$('ul.nav').find('a').click(function(){
    var $href = $(this).attr('href');
    var $anchor = $('#'+$href).offset();
    window.scrollTo($anchor.left,$anchor.top);
    return false;
});

If you want to use animate, replace

window.scrollTo($anchor.left,$anchor.top);

by

$('body').animate({ scrollTop: $anchor.top });
like image 68
JohnJohnGa Avatar answered Oct 09 '22 08:10

JohnJohnGa


It is easier than you think.

  <div class="masthead">
    <ul class="nav nav-pills pull-right">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#About">About</a></li>
      <li><a href="#Contact">Contact</a></li>
    </ul>
    <h3 class="muted">Name site</h3>
  </div>


<div id="About">Here's my about</div>

...

<div id="Contact">Here's my contact</div>

By using the hash, it'll auto scroll to an element with that id (or an anchor with that name attribute). If you want it to scroll smoothly you can enhance the scroll effect with a javascript library, like jquery. See this question: How to scroll HTML page to given anchor using jQuery or Javascript?

like image 30
Eli Gassert Avatar answered Oct 09 '22 10:10

Eli Gassert