Is there a way to ensure that a div modal always resets to the top when it's opened?

I created a modal using only HTML, CSS, and JavaScript. When I click a button on the main page, the modal pops up.

However, if I scroll down in the modal and then close it, when I reopen it, it still shows the scrolled-down view. How can I make it always display the content at the top whenever I open the modal?

Here is the code I used:

<div class="button" id="btn"></div>

<div class="modal" id="mymdl">
    <div class="modal-content" id="mdl-con">
        <div class="modalwidth">
            <img class="image-title" id="img-ttl" src="./img/banner.png">
            <span class="close" aria-hidden="true">&times;</span>
        </div>
        <div class="paragraph">
            Here is the main content.
        </div>
    </div>
</div>
document.getElementById('btn').addEventListener('click', function(e) {
    modal.style.display = "block";
});

var closeX = document.getElementsByClassName("close")[0];
closeX.onclick = function() {
    modal.style.display = "none";
}

I attempted to use the window.scroll method suggested in a solution for this issue, but it did not resolve my problem.

As a beginner in HTML, CSS, and JavaScript, any advice on how to fix this would be greatly appreciated! Thank you in advance.

Answer №1

Instead of scrolling to the top, a more efficient method is to bring the modal to the top.

document.getElementById('btn').addEventListener('click', function(e) {
  modal.style.display = "block";
  modal.style.top = window.pageYOffset + 10 + "px";
});

const modal = document.querySelector('.modal')
const btns = document.querySelectorAll('.btn');

for (let x = 0; x < btns.length; x++) {
  btns[x].addEventListener('click', function(e) {
    modal.style.display = "block";
    modal.style.top = window.pageYOffset + 10 + "px";
    console.log(window.pageYOffset, modal.style.top);
  });
}
.container {
  height: 1000px;
}

.btn {
  display: inline-block;
  margin-top: 400px;
}

.modal {
  padding: 20px;
  position: absolute;
  width: 200px;
  background: rgba(0, 0, 0, .5);
  color: #fff;
}
<div class='container'>
  <div class='modal'>Modal</div>

  <button class='btn'>click</button>
  <hr>
  <button class='btn'>click</button>
</div>

Answer №2

To scroll an element to the top, you can utilize the code element.scrollTop = 0.

For instance, if you want to scroll a `.paragraph` element, you could implement something like this:

const modal = document.getElementById("mymdl");

document.getElementById('btn').addEventListener('click', function(e) {
    modal.style.display = "block";
});

var closeX = document.getElementsByClassName("close")[0];
closeX.onclick = function() {
    modal.querySelector(".paragraph").scrollTop = 0; //scroll to the top
    modal.style.display = "none";
}
.modal
{
  position: fixed;
}

.modal-content
{
  border: 1px solid black;
}

.paragraph
{
  overflow: auto;
  height: 50vh;
  white-space: pre;
  text-align: center
}

.paragraph > div
{
  height: 120%;
}

.paragraph > span
{
  position: relative;
  bottom: 0;
}

.button,
.close
{
  cursor: pointer;
}
<div class="button" id="btn">open modal</div>

<div class="modal" id="mymdl">
    <div class="modal-content" id="mdl-con">
        <div class="modalwidth">
            <img class="image-title" id="img-ttl" src="./img/banner.png">
            <span class="close" aria-hidden="true">&times;</span>
        </div>
        <div class="paragraph">
        <div>Here is the main content.
scroll down</div><span>bottom</span>
        </div>
    </div>
</div>

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

What is the best way to retrieve the name of all input tags, obtain their respective IDs, and append additional text to each

Is there a way to extract all input tag names, retrieve their corresponding ids, and then append text to each input tag? Consider the following inputs: var inputs, index; inputs = document.getElementsByTagName('input'); for (index = 0; index ...

Setting up a simple configuration for WebGl and Javascript

I am currently using OSX 10.9.5 (Mavericks) and following a WebGL tutorial script provided on . I copied and pasted the code from the tutorial into TextEdit and saved it as HTML with the following file structure: webgl | +--index.html | ...

Deleting a CSS class from buttons inside of two button arrays by utilizing two separate functions

Uncertain if the issue lies within the scope, but essentially... I have a collection of 4 div buttons stored in an array called main_btns. When these buttons are clicked, they toggle between 2 classes to display different background colors. Similarly, I ...

Incorporate issues into the VeeValidate error collection using the parent component, then monitor them from the child components

Is there a way to implement data transfer from a parent component to a child component for error handling? Specifically, how can I add data to the errors bag from the parent component and then listen to a specific error in the child component to display so ...

Guide to making the top margin of Chinese characters consistent on all web browsers

Currently, I am working on a website that features flashcards for Chinese character learning. The issue I am facing is that Internet Explorer displays fonts slightly higher on the line compared to other browsers I have tested. Although this may seem insign ...

CSS does not alter the properties of a link's "background-color" or "border-color"

I have successfully changed the text color of visited links, but I am struggling to change the "background-color" and "border-color" properties. The initial part of my internal style sheet includes a CSS reset. a:visited { color: red; background-col ...

Hidden Span Element Appears Invisible

I have the following span element in my HTML: <span style="float: right;color: red; display: inline-block;" id="antcl_error"></span> However, when I checked its visibility it returned as not visible: $(document.body).find("#antcl_error").is( ...

JavaScript interprets code differently each time it runs

After returning to work this morning, I encountered some strange behavior that disappeared after restarting the server. Despite my efforts, I couldn't recreate it. So, consider this question "solved" and feel free to delete it if necessary. I'm n ...

Soft keyboard on mobile fails to update when arrows are used in Ajax-populated dropdown menus

I am working on a web form that includes two select fields: Country and City: <select id="country" onchange="getCity(this);"> <option value="">-- Please select your country --</option> <option value="1">Austria& ...

What are the different HTTP Methods supported by AJAX?

Considering that HTTP supports a variety of methods such as GET, PUT, POST, DELETE (and others like PATCH, HEAD, OPTIONS, etc.), I am pondering over which of these methods an AJAX request typically utilizes. Is there an option to specify which method we ...

Troubles with jQuery mobile functionality when utilizing hyperlink urls within a table

Currently, I am utilizing jQuery mobile to populate a table using ajax. One of the fields in the table is a hyperlink (href) that has a class assigned to it to trigger an alert on the screen. However, the alert does not appear when clicked: I have attempt ...

In CSS3, what is the significance of placing a comma between transition and transform?

Just getting started with CSS3 and have a couple of questions: 1) I know that using -XXX-transtion: opacity .4s tells Webkit and Firefox browsers to gradually change the opacity to zero over 400ms. However, what does the comma right after signify? opaci ...

Sending an array of strings from an ajax call to an MVC controller

I'm encountering an issue where I have an array that I build up when a row is selected in my bootstrap data table. The problem arises when I try to pass this array from my view to the controller, which is supposed to fire up a partial view. Strangely, ...

What is the method for obtaining the worldwide location of a vertex on a skinned mesh in Three.js?

In the realm of Three.js, we've recently acquired the ability to determine the global position of a vertex in a non-skinned mesh thanks to insights from this question. Now, the query arises - how can one ascertain the global position of a vertex in a ...

Tips for retrieving text from child tags that may only be displayed under certain conditions

I am trying to extract text from the child tag (html tag: a) that is only displayed when invalid data is entered. When valid data is entered, the child tag (html tag: a) will not be visible. Is there a way to write an xpath that can handle both scenarios ...

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

Tips for designing a unique CSS ellipse effect for text styling

Hey there! I have a list of titles in a drop-down menu as strings, for example: "Bharat Untitled offer #564", "Bharat Untitled offer #563" The titles are quite long, so we want to display the first eight characters, followed by '...' and then ...

Retrieve ALL information from a third-party API request with a limit of 1000 calls

Challenge: Implementation of a third-party API call using Node.JS. The API link restricts the number of users per call to 1000, with an option to retrieve the next set by passing parameters in the URL (?firstResult=1001&maxResults=1000&orderBy=NAME ...

What is the method for initiating a loop from index 1 rather than index 0 in an *ngFor loop within Angular?

Currently, I am retrieving data from a dummy API where the response starts from 1, but the index is starting from 0. Is there any way I can adjust the index loop to start from 1 instead of 0? Below is the HTML code for *ngFor: component.html < ...

The utilization of $(this) proves to be ineffective

I've been working on getting a script to add events to a specific DIV within a class using pep.js: $( ".drag" ).pep({ start: function() { $(".drag").addClass('color'); $('.drag').next(".text").fadeIn("slow"); ...