Scroll the page to bring the div to the top position

Currently working on a web page that consists of divs with varying heights and text inside them. I would like to implement a feature where clicking on the text within a div automatically scrolls the page so that particular div is positioned at the top of the screen.

Most solutions I've come across involve using the fixed property, but I prefer not to alter the position property of the div itself. Ideally, I want the page to scroll automatically to bring the desired div to the top. Any suggestions on how I can achieve this?

Appreciate any guidance you can provide!

.container {
  width: 100vw;
  height: auto;
}
.element {
  padding: 50px;
}
#element-1 {
  background-color: beige;
  height: 500px;
}
#element-2 {
  background-color: darkSeaGreen;
  height: 200px;
}
#element-3 {
  background-color: coral;
  color:  white;
  height: 800px;
}
#element-4 {
  background-color: MidnightBlue;
  color: white;
  height: 300px;
}
<div class="container">
  <div class="element" id="element-1">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-2">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-3">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-4">
    <h1>Some text</h1>
  </div>
</div>

Answer №1

If I understand correctly, this solution should be beneficial for you.

let divs = document.querySelectorAll(".element");
divs.forEach(div => {
    div.addEventListener("click", event =>{
        let divTop = div.offsetTop;
        window.scrollTo(0, divTop);
        console.log(divTop + " --- " + window.scrollY);
    });
});
.container {
    width: 100vw;
    height: auto;
}
.element {
    padding: 50px;
}
#element-1 {
    background-color: beige;
    height: 500px;
}
#element-2 {
    background-color: darkSeaGreen;
    height: 200px;
}
#element-3 {
    background-color: coral;
    color:  white;
    height: 800px;
}
#element-4 {
    background-color: MidnightBlue;
    color: white;
    height: 300px;
}
<div class="container">
  <div class="element" id="element-1">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-2">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-3">
    <h1>Some text</h1>
  </div>
  <div class="element" id="element-4">
    <h1>Some text</h1>
  </div>
</div>

Answer №2

To achieve this task, you must create a custom function.

window.scrollTo(x, 0); 

Replace x with the specific position of the element you desire to scroll to. You can obtain this value by executing:

let x = element.getBoundingClientRect().top;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use Beautiful Soup to change the value of a dropdown button to match the selected dropdown

Is there a way to have my BS4 dropdown menu display the selected value in the dropdown toggle button, specifically .dropdown-toggle? A similar question was asked before here, but it pertains to an older version (BS3 Framework) and does not address using t ...

issue: [astro preview] adapter lacks preview entry point

Recently, I encountered an issue while working on a website using astro (). When running astro preview, I encountered an error. Here is the code from my astro.config.mjs file: import { defineConfig } from 'astro/config'; import vercel from ' ...

Is there a way to set an image as the background of my HTML screen?

{% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> < ...

Unable to load content: net::ERR_CONTENT_LENGTH_MISMATCH

Can someone help me understand what this error message means and how to fix it? This error is showing up in the console of Google Chrome version 33.0 on a Windows 7 machine. An error occurred while trying to load a resource: net::ERR_CONTENT_LENGTH_MISM ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Is there a way I can adjust the width of a DIV to automatically adjust to its content?

Is there a way to make a div adjust its width based on the width of its children, even if the children are too wide and collapse? Here is my CSS code: .outer{ width: 100%; background-color: green; } .inner{ width: auto ...

Incorporating images with text in the navigation bar

Just dipping my toes into the world of HTML and CSS, but I need some guidance. I'm trying to incorporate images and text (for the title) in my header using a navbar. However, when I resize the window, the text doesn't move along with the image. ...

Extract the content from a <Span> element without specifying its ID

Is there a way to make it so that when a user clicks on an HTML tag, the text is copied to their clipboard? I also need to ensure that this functionality does not apply to a specific tag ID/name as I am unable to add those to my span. Is there a way to aut ...

Is there a way to include a minimize button on a MaterialUi Table enclosed in a Paper component for easy table reduction?

I am trying to add a minimize button to either minimize my MaterialUi Table or the Paper component that wraps it. Here is the code I have so far: <TableContainer component={Paper} style={{maxHeight:'inherit', maxWidth:'inherit', boxS ...

Ways to determine if a website is being accessed from a mobile device or a computer without relying on TeraWurfl technology

After my search on the internet yielded no answers, I decided to post my question here. Is there a method available to detect whether a site is being accessed from a computer or mobile device without using TeraWurfl? I'm looking for a simple code snip ...

What is the simplest method for a beginner to transfer form data from HTML to an email?

Currently I am in the process of developing a compact website and looking to design an HTML form that can send values to my client's email address. The snippet of code for the form is as follows: <form id="contact-form" method=" ...

Difficulty toggling divs using the data-parent attribute in Bootstrap 4

Incorporating Bootstrap 4 features in this project. I am aiming for the functionality where clicking on one of the links in the navigation bar will toggle the content for that specific link while closing any other open ones. Currently, each section/div re ...

What is the most effective method for transferring resolved promise values to a subsequent "then" chain?

Currently, I am grappling with understanding promises by utilizing the Q module in node.js. However, I have encountered a minor setback. Consider this scenario: ModelA.create(/* params */) .then(function(modelA){ return ModelB.create(/* params */); } ...

Check input validation using jQuery

Looking for a jQuery function to validate the value of a textbox. Criteria: required field:true, minimum length: 8, maximum length: 16, only alphabets and numbers allowed. I have attempted to write a function: jQuery.validator.addMethod("nameRegex", f ...

Counting selected files can be done by following these steps

My form includes a simple input field like so: <input id="my_id" multiple="true" type="file" name="image_name[]" /> I need help with the following questions: What is the best way to calculate the number of selected files using jQuery or pure Java ...

Mistakes in nodebacks can be traced back to the promises they originate from

While transitioning my code from callbacks to promises, I stumbled upon an issue when trying to maintain the function's interface. Here is an example: function callMeWithCallback(args, next) { Promise.resolve() .then(()=> { return ...

Changing the Color of Tooltips in Bootstrap 4

Currently, I am attempting to customize a Bootstrap 4 tooltip by re-styling it, but the original method no longer seems to be effective. My current approach looks like this: .tooltip-inner { background: #7abcff; background: -webkit-linear-gradien ...

Developing a dynamic dropdown navigation bar using JSON information

I need help in displaying the data from different keys such as "conta", "zip, city, street_a, street_b", "count, number". I want to create a drop-down menu using the "contact" keys, but so far I haven't been successful. Can someone provide an explanat ...

Leveraging a single Axios request across various components

My current setup involves making a simple Axios call in this way: .get('https://myAPI.com/') .then(response => { this.info = response.data }) Subsequently, I utilize a v-for array loop on my components to display the retrieved data. ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...