Encountering a problem with scrolling the modal to the top

I am currently working on a code snippet that involves scrolling the modal to the top position. The purpose of this is to display form validation messages within the modal popup.

Below are the jQuery code snippets that I have attempted:

//Click event to scroll to top
 
$(".signIn-btn").click(function() {
    $("#largeModal").scrollTop(0);
});
.modal-body {
    height: 250px;
    overflow-y: auto;  
}

.modal-body-inner {
  height: 100%;  
}
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b6a9b6b6a3b4e8acb586f7e8f7f0e8f6">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<div class="container">
<h1 class="display-4 text-center mb-4">Bootstrap Modal</h1>  
<div class="row mb-4">
<div class="col text-center">
  <h3>The Large Modal</h3>
  <a href="#" class="btn btn-lg btn-primary" data-toggle="modal" data-target="#largeModal">Click to open Modal</a>
</div>
</div>
</div>

<!-- large modal -->
<div class="modal fade" id="largeModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Sign In</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      
      <div class="modal-body">        
        <div class="modal-body-inner">
            <p>Modal Message At Top</p>
            <div class="form-row">
              <div class="form-group col-md-6">
                <label for="inputEmail4">Email</label>
                <input type="email" class="form-control" id="inputEmail4" placeholder="Email">
              </div>
              <div class="form-group col-md-6">
                <label for="inputPassword4">Password</label>
                <input type="password" class="form-control" id="inputPassword4" placeholder="Password">
              </div>
            </div>
            <div class="form-group">
              <label for="inputAddress">Address</label>
              <input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
            </div>
            <div class="form-group">
              <label for="inputAddress2">Address 2</label>
              <input type="text" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">
            </div>
            <div class="form-row">
              <div class="form-group col-md-6">
                <label for="inputCity">City</label>
                <input type="text" class="form-control" id="inputCity">
              </div>
              <div class="form-group col-md-4">
                <label for="inputState">State</label>
                <select id="inputState" class="form-control">
                  <option selected="">Choose...</option>
                  <option>...</option>
                </select>
              </div>
              <div class="form-group col-md-2">
                <label for="inputZip">Zip</label>
                <input type="text" class="form-control" id="inputZip">
              </div>
            </div>
            <div class="form-group">
              <div class="form-check">
                <input class="form-check-input" type="checkbox" id="gridCheck">
                <label class="form-check-label" for="gridCheck">
                  Check me out
                </label>
              </div>
            </div>
            <button type="submit" class="btn btn-primary signIn-btn">Sign in</button>
        </div>    
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>            
      </div>
    </div>
  </div>
</div>

Answer №1

To achieve the desired effect, you need to define the element containing the scroll bar, which is .modal-body. Implement it like this:

$(".signIn-btn").click(function() {
    $("#largeModal .modal-body").scrollTop(0);
});

Answer №2

Don't bother writing custom CSS to create a scrollbar when Bootstrap4 already has a predefined class modal-dialog-scrollable for making the modal-body section scrollable. Also, utilize

$('#largeModal .modal-body').animate({scrollTop: 0}, 500);
to scroll the modal-body to the top.

Doc: https://getbootstrap.com/docs/4.4/components/modal/#scrolling-long-content Note: Please view this snippet in Full page mode.

$(document).on('submit', '#formID', function(){
  $('#largeModal .modal-body').animate({
    scrollTop: 0
  },500);

  return false;
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="container">
  <h1 class="display-4 text-center mb-4">Bootstrap Modal</h1>  
  <div class="row mb-4">
    <div class="col text-center">
      <h3>The Large Modal</h3>
      <a href="#" class="btn btn-lg btn-primary" data-toggle="modal" data-target="#largeModal">Click to open Modal</a>
    </div>
  </div>
</div>

<div class="modal fade" id="largeModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form action="#" method="post" class="modal-content" id="formID">
      <div class="modal-header bg-light">
        <h4 class="modal-title" id="myModalLabel">Sign In</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>      
      <div class="modal-body">        
        <div class="modal-body-inner">
          <div class="alert alert-danger" role="alert">
            <strong>Modal Message At Top</strong>
            A simple danger alert—check it out!
          </div>

          <div class="form-row">
            <div class="form-group col-md-6">
              <label for="inputEmail4">Email</label>
              <input type="email" class="form-control" id="inputEmail4" placeholder="Email">
            </div>
            <div class="form-group col-md-6">
              <label for="inputPassword4">Password</label>
              <input type="password" class="form-control" id="inputPassword4" placeholder="Password">
            </div>
          </div>
          <div class="form-group">
            <label for="inputAddress">Address</label>
            <input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
          </div>
          <div class="form-group">
            <label for="inputAddress2">Address 2</label>
            <input type="text" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">
          </div>
          <div class="form-row">
            <div class="form-group col-md-6">
              <label for="inputCity">City</label>
              <input type="text" class="form-control" id="inputCity">
            </div>
            <div class="form-group col-md-4">
              <label for="inputState">State</label>
              <select id="inputState" class="form-control">
                <option selected="">Choose...</option>
                <option>...</option>
              </select>
            </div>
            <div class="form-group col-md-2">
              <label for="inputZip">Zip</label>
              <input type="text" class="form-control" id="inputZip">
            </div>
          </div>          
          <div class="form-group">
            Insert your long form content here.
          </div>
          <div class="form-group">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="gridCheck">
              <label class="form-check-label" for="gridCheck">
                Check me out
              </label>
            </div>
          </div>
        </div>    
      </div>
      <div class="modal-footer justify-content-start w-100">
        <button type="submit" class="btn btn-primary px-4 signIn-btn">Sign in</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>   
      </div>
    </form>
  </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

Methods for extracting the date value from a Material UI datepicker?

As a newcomer to React, I am currently working on creating a form that includes a Date picker for scheduling appointments. Since booking appointments in the past is not allowed, I need to disable the days before today in the calendar for the date picker. ...

Is there a way to deactivate the previous button for today's date?

I need assistance with disabling the previous button on today's date in my calendar. It is crucial that users are only able to select the start date from today onwards. I am currently utilizing moment.js for my Datepicker. Any help would be greatly ap ...

Tips for preserving both existing data and new data within React's useState hook in React Native or ReactJS?

As I dive into learning reactjs, one question that has been on my mind is how to store both previous and upcoming data in useState. Is there a special trick for achieving this? For example: Imagine I enter "A" and then follow it with "B". My goal is to ha ...

Looking to add the Ajax response data into a dropdown selection?

Looking to add select options dynamically, but unsure how to retrieve response values. I am able to fetch all the values in the response, but I struggle with appending them correctly in the select option. I believe the syntax is incorrect. success: funct ...

Improving the performance when toggling visibility of multiple div elements

Having implemented a show/hide effect on a lengthy list of titles and definitions, I've found the speed at which it occurs to be quite sluggish. The code used was sourced from elsewhere, so I can't take full credit for it. One potential reason fo ...

What is causing the onclick event to not function properly when called from an external .js file?

I've created a .js file that contains code for a photo album application. The file includes functions for changing images when buttons are clicked. However, when I interact with the buttons, the images do not change as expected. The code in the .js f ...

Position 2 identical classes side by side on the horizontal axis

Currently enrolled in the MIMO HTML course and facing a challenge where I am unable to align both elements with the class="column" attribute horizontally using display: inline-block; I have attempted using float:right and other CSS properties to achieve a ...

Arrangement using the display property of inline-block not following a linear direction

I'm experiencing some issues with the arrangement of elements on this page: When the viewport width is around 800px, the layout appears misaligned. Some lines have only a few bottles even though there is space for more. Is there a solution to this pr ...

Tracking the progress of jQuery ajax requests

I'm currently using jQuery $.ajax to send files over the internet. Is there a way for me to receive updates on the progress of the file transfer, and then adjust the settings accordingly? Below is my current implementation of $.ajax : $.ajax({ ...

Using Firebase onDisconnect with React Native

I am currently working on a React Native app and I am facing an issue where I need to update the user status to 'offline' in Firebase when the user closes the app. Here is what I have tried: import React, { Component } from 'react' ...

Is the onmouseover / onmouseout transition failing to function properly?

Is there a way to make the ease-in-out effect work without modifying the HTML code? http://jsfiddle.net/68ojLg6p/ <img class="transition-img" onmouseover="this.src='http://1.bp.blogspot.com/-ISjKMLTnaTQ/Ty-USX-J1uI/AAAAAAAAC_0/YB6MUMflRmg/s400/fe ...

I keep encountering an Uncaught TypeError when trying to read the property 'options' of null, despite having the element ID properly defined

I am a newcomer to the world of Javascript and HTML. Despite having the element defined in HTML, I am encountering an exception. Could someone please offer assistance? My goal is to create a shape (initially a circle) based on user input such as shape type ...

Scrolling does not function properly on Android devices when utilizing skrollr.js in conjunction with multiple div elements containing the id "skrollr-body."

Having trouble with the scroll functionality in my skrollr.js animations. Everything works fine on desktop, but when I checked the rendered HTML in the browser console, I noticed that there are two divs with the same id "skrollr-body". One is empty and the ...

Hover image displacement

Can anyone help me identify the feature used in this price list where the mouseover changes and a big image appears underneath? I'm trying to achieve something similar but can't figure out how. Any guidance would be appreciated. ...

What is the process for incorporating an external script into a Vue component?

Seeking assistance urgently... I am encountering an issue with a Vue component and an endpoint that provides a script containing a small menu with actions. However, once the script is loaded, the actions do not seem to function on the page and I cannot det ...

Implementing a Scalable Application with React Redux, Thunk, and Saga

What sets Redux-Saga apart from Redux-Thunk? Can you explain the primary use of redux saga? What exactly is the objective of redux thunk? ...

What could be the reason that the close() method is not successfully closing the window that I have generated?

Although there are no error messages, I am encountering an issue where the function windowClose() does not execute when I click on the 'close window' button. Why could this be happening? Take a look at my code below: HTML <!DOCTYPE html> ...

What is the process for inheriting HTML templates?

I am currently utilizing KnockoutJS along with its default template engine. My goal is to establish a master template that can serve as a foundation for other templates to build upon, similar to a UserControl in .NET but within an HTML context. For instan ...

Ways to eliminate an item from an array when the value of the object is not present

I am facing an issue with removing objects from an array that do not contain the data object. I have attempted to use the filter method but have not been successful. results.filter(obj => obj.data === undefined) results = [ {id: 1, location: 'a&a ...

Performing two API calls using Jquery to fetch distinct dynamic elements within two nested $.each loops

There's an API link that contains crucial data about phone brands. From this initial data, I have to create a second API call for each brand to gather more detailed information. For example, the first JSON file (urlphonebrands) lists 3 phone brands - ...