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>
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.
The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.
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.
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.
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 });
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With