0
votes

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 with id="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...

1
Does this answer your question? JavaScript scroll to div with animation - IT goldman
It is invalid to have two elements with the same id. Just put the id in the onclick attribute. I.e., onclick="reply_click('div1')". Make sure you update your jQuery so it works though: $("#" + clicked_id).offset().top... - Heretic Monkey
Heretic Monkey, thank you! it looks like it solve my problem - Agapini

1 Answers

0
votes

As you said, you can use hashes. And why do you need to use JS? If it's not required, you shouldn't use it unnecessarily.

EDIT: Or do you not want to display it in the URL? ("...#div1")

<a href="#div1">button1</a>
<a href="#div2">button2</a>

<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>

EDIT (JS):

function reply_click(id) {
   document.querySelector(`#${id}`).scrollIntoView();
}