Jpark9061
Jpark9061

Reputation: 1080

How to scroll to an element WITHIN a div, without scrolling entire page (no JQuery)?

I have a scrollable div with a bunch of h3 elements. I want to click a button to scroll a specific h3 element within that div. NOT scrolling the entire page. Is this behavior possible without using JQuery? My app is built in React, so npm library suggestions are welcome too! Thanks

Upvotes: 0

Views: 1376

Answers (3)

Paul-Louis Mas
Paul-Louis Mas

Reputation: 429

If you don't mind setting an id to the specific h3:

<div>
  <!-- The content of the div -->

  <h3 id="foo">
    Foo
  </h3>

  <h3 id="bar">
    Bar
  </h3>

  <!-- ... -->
</div>

you can then tell the browser to navigate to the h3 element using a link pointing to the id using the hash:

<a href="#foo">
  <button>
    Go to Foo
  </button>
</a>

else, you can use the Javascript .scrollIntoView() function while targeting the correct h3 element:

// Consider the h3 element is referenced by the 'h3' variable

h3.scrollIntoView();

as stated on MDN Web Docs

See example:

// Wait for window to load before adding listeners
window.addEventListener('load', function() {
  // The button that needs to trigger the scrolling event
  const button = document.querySelector('button.clickable');
  
  // The h3 element to scroll to
  const h3 = document.querySelector('h3');
  
  // Add the click listener
  button.addEventListener('click', function(event) {
    h3.scrollIntoView();
  });
});
h3 {
  /* Make the h3 elements really distanced from other elements to test the scrolling  */
  margin: 500px auto;
}
<div>
  <a href="#foo">
    <button>
      Goto <code>foo</code> using <code>id</code>
    </button>
  </a>
  
  <button class="clickable">
    Goto <code>foo</code> using <code>scrollIntoView</code>
  </button>
  
  <h3 id="foo">
    Foo
  </h3>
</div>

EDIT 1: switched button and a HTML components to make the a the parent container of the button

EDIT 2: added code snippet

Upvotes: 1

Aymen Albouchammaoui
Aymen Albouchammaoui

Reputation: 26

var hello = document.getElementById("hello");
var bye = document.getElementById("bye");
function goHello(){
  hello.scrollIntoView({block: "start"});
}
function goBye(){
  bye.scrollIntoView({block: "start"});
}
#divScroll{
  max-height:180px;
  overflow:auto;
  background : #FFCC00;
  padding:20px
}
<div id="divScroll">
<h3 id="hello">Hello</h3>
<br><br><br><br><br><br>
<h3 id="bye">Bye</h3>
<br><br><br><br><br><br><br><br><br>
<button onClick="goHello()">Go Hello</button> 
<button onClick="goBye()">Go Bye</button>
<div>

Upvotes: 1

S&#233;rgio Cruz
S&#233;rgio Cruz

Reputation: 1

Style each h3 with height and overflow-y: scroll;

Upvotes: -1

Related Questions