Javascript scroll to div id
54,323
Solution 1
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function scrollTo() {
$('html, body').animate({ scrollTop: $('#div_id').offset().top }, 'slow');
return false;
}
</script>
<style type="text/css">
.uno {
height: 1000px;
background: #808080;
}
.due {
margin-top: 300px;
height: 500px;
background: #ff00ff;
}
</style>
</head>
<body>
<div class="uno" onclick="scrollTo()">
Clicca
</div>
<div class="due" id="div_id"></div>
</body>
</html>
Try this:
Solution 2
Change your script to:
$('.uno').on('click', function(){
$('html, body').animate({scrollTop: $("#div_id").offset().top}, 'slow');
});
and remove onclick
from the first div.
A demo is in this jsFiddle.
Solution 3
see my jsfiddle:
you should add jquery to your codes, and this is my way:
and in this jsfiddle if you click on each div you will scroll to other div DEMO
Javascript
$("#firstDiv").click(function(){
$('html, body').animate({ scrollTop: $('#div_id').offset().top }, 'slow');
})
HTML
<div class="uno" id="firstDiv">
Clicca
</div>
<div class="due" id="div_id"></div>
Author by
ProtoTyPus
Updated on January 09, 2020Comments
-
ProtoTyPus over 4 years
I've searched on google the solution to my problem, and I can't understand why the code I've written work for everyone, but not for me.
I've written this:
<head> <meta charset="utf-8" /> <title></title> <script type="text/javascript"> function scrollTo() { $('html, body').animate({ scrollTop: $('#div_id').offset().top }, 'slow'); return false; } </script> <style type="text/css"> .uno { height: 1000px; background: #808080; } .due { margin-top: 300px; height: 500px; background: #ff00ff; } </style> </head> <body> <div class="uno" onclick="scrollTo()"> Clicca </div> <div class="due" id="div_id"></div> </body>
-
Rohit Batham almost 10 yearsPlease try this is working after including jquery library in above code
-
ProtoTyPus almost 10 yearsYes, I'm a complete idiot... i tryed to make work a jquery script without include jquery. omg...
-
Rohit Batham almost 10 years@Daniele hahahha, Some time occurs this
-
Pugazh almost 10 years@DanieleNekoLuciani: If the suggested solution solves your issue, accept this as answer. This may help others as well.
-
Rohit Batham almost 10 years@SyncCircles Thanks Sync
-
ProtoTyPus almost 10 yearsOfcourse, but I've to w8 some minutes. It's for this I'm here still.
-
Hemant Kumar about 5 yearsThis is not Javascript, can you also update how to do this in javascript only, I am working on chrome extension.