I have few div
s .posts
which have a attr data-id
which corresponds to the mysql DB id
.
<div class="posts" data-id="1"></div>
<div class="posts" data-id="2"></div>
Now if I want to scroll to a specific div
which I am only known to the data-id
.
How will I scroll to it?.
My JSFiddle is here.
Can anyone give an example along with a JSFiddle?
You use link anchors and JQuery.
Just give your link the class "scroll" and use the following code in the head:
jQuery(document).ready(function($) {
$(".scroll").click(function(event) {
event.preventDefault();
$('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
} );
} );
You also need to give your posts an ID and link to them as in:
<a href="#8" class="scroll">Go To Div 8</a>
<div class="post" id="8">
JSFIDDLE
You can use jQuery.ScrollTo plugin: https://github.com/flesler/jquery.scrollTo
In this link you can find demos http://demos.flesler.com/jquery/scrollTo/
$(function() {
$('body').scrollTo($('div[data-id=1]'), 1000); //scroll to div 1
});
HTML:
<div class="posts" data-id="1"></div>
You don't need javascript if you have an anchor with a name
.
<a href="#post8">Div to post 8</a>
scrolls to <a name="post8"></a>
I think this would help $(".element").attr("any-attribute-of-ur-elem");
In your case it would look like: $(".post").attr("data-id")
And you can scrollTo that posts.
try this:
$(document).ready(function (){
$("#button").click(function (){
$('html, body').animate({
scrollTop: $(".post[data-id="+yourID+"]").offset().top
}, 2000);
});
});