Reputation: 5096
I am creating a page. I have the following HTML:
<ul id="nav">
<li><a href="#section1">Link</a></li>
<li><a href="#section2">Link</a></li>
<li><a href="#section3">Link</a></li>
<li><a href="#section4">Link</a></li>
<li><a href="#section5">Link</a></li>
<li><a href="#section6">Link</a></li>
</ul>
<div class="section">
<p>Content</p>
</div>
<div class="section" id="section1">
<p>Content</p>
</div>
<div class="section">
<p>Content</p>
</div>
<div class="section" id="section2">
<p>Content</p>
</div>
<div class="section">
<p>Content</p>
</div>
<div class="section" id="section3">
<p>Content</p>
</div>
<div class="section">
<p>Content</p>
</div>
<div class="section" id="section4">
<p>Content</p>
</div>
<div class="section">
<p>Content</p>
</div>
<div class="section" id="section5">
<p>Content</p>
</div>
<div class="section">
<p>Content</p>
</div>
<div class="section" id="section6">
<p>Content</p>
</div>
What I would like to achieve is when a link is clicked. Use jQuery to find a div with the same id as the links href and then scroll the page to that div. Can anyone point me in the right direction? The bit I am struggling with is how to match the id to the href.
Many thanks.
Upvotes: 0
Views: 6444
Reputation: 14766
You could achieve this by this way:
$('#nav li a').click(function(){
//Scroll to targetID offsetTop.. or using the scrollTo plugin, scrolling to $($(this).attr('href'))
})
Upvotes: 1
Reputation: 36111
Add a click event to each of the anchor tags. The use the attr function to get the href of the selected element.
I've then used the animate function to scroll to this element.
$(function(){
$('#nav li a').click(function(){
var divID = $(this).attr('href');
$('html,body').animate({
scrollTop: $(divID).offset().top
}, {
duration: 'slow',
easing: 'swing'
});
});
});
Upvotes: 3
Reputation: 25312
Try something like this :
$('#nav a').click(function(){
$($(this).attr('href')).whatyouwant();
});
Upvotes: 1