Reputation: 61
I have a code which slides to a particular div on page load . I am trying to modify that code . I wish to slide it to particular div on click event of href. JS Fiddle Link
Javascript
$(document).ready(function () {
// Handler for .ready() called.
$('html, body').animate({
scrollTop: $('#what').offset().top
}, 'slow');
});
HTML
<div id="mydiv">DATA FOR SAMPLE 1</div>
<div id="what">SAMPLE DATA</div>
<ul>
<li><a href="#"> on click<a/></li>
</ul>
Upvotes: 0
Views: 6892
Reputation: 25392
There are two things to note here. If you give your <a>
a link to a blank anchor, href="#"
, it will automatically send you to the top of the page.
So in order to do this, you need to get rid of that.
<a>on click</a>
It will still work if you don't remove the href="#"
, but it will jump to the top of the page and back before it scrolls, which is unsightly.
The other thing you need to do is bind the event to the <a>
$(document).ready(function () {
// Handler for .ready() called.
$("a").click(function(){
$('html, body').animate({
scrollTop: $('#what').offset().top
}, 'slow');
});
});
Upvotes: 1
Reputation: 2523
Javascript
$(document).ready(function () {
$('#clicky').click(function() {
$('html, body').animate({
scrollTop: $('#what').offset().top
}, 'slow');
});
});
HTML
<div id="mydiv">DATA FOR SAMPLE 1</div>
<div id="what">SAMPLE DATA</div>
<ul>
<li><a id="clicky" href="#"> on click<a/></li>
</ul>
Upvotes: 1
Reputation: 1745
TRY this. Here I am add a new id for your tag ( recommended ) called on_click_a
or you can use $('a)
instead of $('#on_click_a')
<div id="mydiv">DATA FOR SAMPLE 1</div>
<div id="what">SAMPLE DATA</div>
<ul>
<li><a href="#" id='on_click_a'> on click<a/></li>
</ul>
$(document).ready(function () {
// Handler for .ready() called.
$("#on_click_a").click(function(){
$('html, body').animate({
scrollTop: $('#what').offset().top
}, 'slow');
});
});
Upvotes: 1