Have a quite simple code:
<button id="div1" onClick="reply_click(this.id)">button1</button>
<button id="div2" onClick="reply_click(this.id)">button2</button>
<div id="div1" style="height: 1000px; width: 100px">
Text for div 1
</div>
<br/>
<div id="div2" style="height: 1000px; width: 100px">
Text for div 2
</div>
<script type="text/javascript">
function reply_click(clicked_id) {
$('html, body').animate({
scrollTop: $(clicked_id).offset().top
}, 2000);
}
</script>
Need to scroll after button click to specific div with same id like have button:
- If clicked button with
id="div2"so scroll to div with same id (id="div2") - If we click button
id="div1"it scrolls to div withid="div1"
My code doesn't work. Seems like scrollTop: doesn't see div ID it needs to scroll.
But JavaScript function see variable clicked_id (could make simple alert(clicked_id);) and it works.
Also if I define manually div ID to scroll scrollTop: $('#div1').offset().top it works and scrolling to div1, so it means, that function works.
I know, that there is much more simple ways to make it but I need to:
- Start scrolling by button click, not just by link (mean not
<a href="#div1">click<a>) - Scroll to div with same ID lake have button
- Work it by JavaScript
I am not so clever in JavaScript...
onclickattribute. I.e.,onclick="reply_click('div1')". Make sure you update your jQuery so it works though:$("#" + clicked_id).offset().top... - Heretic Monkey