Automatically scroll to the top of a pop-up div that is scrollable with the help of jQuery

One of the first things to note is that there is a popup div containing a form.

Below is the structure of the div:

<div class="addnewrule" id="add_message_0">
       <form method="post" action="" id="frmadd">
        <input type="hidden" name="filter" value="1">
        <input name="rule_id" type="hidden" value="0">
        <table class="table-responsive" width="100%" border="0" cellspacing="0" cellpadding="10" id="" style="text-align:center; margin-top:0px;">
      <!-- Rest of the code here -->
    </table>
    </form>
</div>

The jQuery AJAX function provided below performs validation checks and displays error messages in a message div:

function submitRule(frmId, rule_id)
{
    var data=$('#'+frmId).serializeArray();
    $.ajax({
        type: 'POST',
        url: 'ajax/rule_update_process.php',
        data: data,
        dataType: 'json',
        success: function(jData)
        {
            if (jData.status == 1)
            {
                $("#display_msg_"+rule_id).html(jData.error);
                $("#display_msg_"+rule_id).addClass('error');
                var child_div = $("#display_msg_"+rule_id);
                var parent_div = $("#add_message_"+rule_id);
                parent_div.scrollTop(parent_div.scrollTop() + child_div.position().top);
            }
            else
            {
                window.location.href = 'settings_rules.php';
            }
        }
      });
}

Since the popup div is scrollable, it is necessary to scroll within the div to display the error message.

If you face issues with scrolling to the top of the popup div to show the error message div, check the following code snippet:

An attempt was made using this code snippet to achieve the scroll effect:

However, it seems like there might be an issue. Troubleshoot and adjust as needed.

$("#display_msg_"+rule_id).html(jData.error);
$("#display_msg_"+rule_id).addClass('error');
var child_div = $("#display_msg_"+rule_id);
var parent_div = $("#add_message_"+rule_id);
parent_div.scrollTop(parent_div.scrollTop() + child_div.position().top);

Answer №1

update the final line of your code by using this parent_div.scrollPosition(0,0);

Answer №2

Here is a straightforward method that I recommend:

$("#apply_button").click(function () { 
  var error_display = $("#your_error_message").css("display");

  if (error_display != "none") {
    $("#add_message_0").scrollTop(0);
  }; 
});

The code explains itself.

Best Regards

Answer №3

If you want to style your form using only CSS, you can easily achieve that. Take a look at this example:

<div>
<form class="has-error">
<p>error</p>
<input name="" value="">
</form>
<div>

By adding the class .has-error, you can customize the appearance of your form when an error message is displayed.

div { overflow-y: scroll; }
div .has-error { height: 400px; }

The specified height will ensure that your section containing error messages has enough space.

You can see a demo similar to this on this fiddle demo.

If the error message is not visible after clicking a button, consider adding the following code snippet to your click function:

$( '#add_message_1' ).delay( 200 ).animate({scrollTop: 0 }, 300);}

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

Discover the second character in the sequence and substitute it with a different numeral

I need to manipulate a string where I want to replace the second digit with a random number. The challenge lies in identifying the second digit and performing the replacement. How can I accomplish this task? 1. "data[KPI][0][rows][0][name]" 2. "data[KPI][ ...

Having trouble with injecting string HTML into the head section in NextJS?

We have incorporated a NextJS page with a headless CMS platform. Within this content management system, I have included an option for the administrator to save custom code snippets to be inserted either in the head section or at the end of the body. In m ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

Sending a message to a specific client using socket.io

Currently delving into socket.io + node.js, I have mastered sending messages locally and broadcasting using the socket.broadcast.emit() function - where all connected clients receive the message. My next challenge is figuring out how to send a private mes ...

Toggling a div overlay through various user interactions such as clicking, pressing a button, or hitting the escape

I've created a simple div overlay that appears when a user clicks inside an input box: HTML <html> <body> <input id="search" type="text" placeholder="Search..."> </body> </html> CSS #overlay { position: fixed; ...

Extract information from an external HTML table and store it in an array

I am looking for a way to extract data from an HTML table on an external site and save it as a JSON file for further manipulation. Is there a method to retrieve table data from an external HTML site that differs from the code example provided? Additional ...

Persist modified text to button when toggling Elements using localStorage in JavaScript

I'm working on creating a button for my web app that can toggle elements, and I want the text on the button to change based on the action it should perform! Here's the code: $(".hideLink").on("click", function(){ if($(this).text()=="Hide ...

Verify the Existence of Date and Time Range in SQL SERVER

I am dealing with the following set of data ID empID FromDate ToDate FromTime ToTime 1 00001 09/11/2018 09/11/2018 10:00 AM 11:00 AM 2 00001 09/11/2018 09/11/2018 08:00 AM 09:00 AM 3 00001 09/11/2018 09/11/ ...

Express middleware for handling errors with Node.js router

My application structure is laid out as follows: - app.js - routes ---- index.js The ExpressJS app sets up error handlers for both development and production environments. Here's a snippet from the app.js file: app.use('/', routes); // ro ...

Unable to convert START_ARRAY token into an instance of CUSTOM_CLASS

I am currently attempting to send an array of objects to a Spring controller using jQuery AJAX. Below is the javascript code that I have written: var data = new Array(); $.each(products, function (i) { var temp = {}; temp.o ...

How can I fetch and show an image from a directory in Asp.Net Core 3.1 using a razor view?

What is the best way to retrieve an image from a directory and display it on a web page? "I've searched for solutions but haven't found one that works" I attempted this method, but it didn't yield the desired results Controller ...

Is there a way to post an array of MongoDB documents embedded in req.body?

How can I send the data from req.body to this MongoDB model using a POST request to '/add'? const QuestionSchema = new mongoose.Schema({ description: String, alternatives: [{ text: { type: String, ...

A step-by-step guide on accessing and displaying local Storage JSON data in the index.html file of an Angular project, showcasing it on the

I am facing an issue with reading JSON data from localStorage in my Angular index.html file and displaying it when viewing the page source. Below is the code I have attempted: Please note that when checking the View page source, only plain HTML is being ...

Ensuring grid columns are equal for varying text sizes

I am looking to achieve equal width and spacing for columns without using the width, min-width, max-width properties. Can anyone help me accomplish this using flex or any other method? https://i.sstatic.net/xo56M.png .d-flex { display: flex; } .d-fl ...

JavaScript code that moves the active link to the top of the navigation when the window width is less than or equal to 800px

I'm working on a responsive navigation that is fixed at the top and switches from horizontal to vertical when the screen size is less than or equal to 800 pixels wide. However, I'm facing an issue with moving the active link to the top of the na ...

Exploring the possibilities of incorporating Bootstrap 4 or ng-bootstrap elements into Angular 4 development

We are considering the use of Bootstrap 4 within an Angular 4 application by either importing their styles and JavaScript directly, or utilizing ng-bootstrap Angular components for improved performance and compatibility with the Angular app. We would lov ...

Matching a string literal with a hyphen in Express Router using Regex - How do I do it?

My dilemma involves two routes. When attempting to access the route test, it also matches with example-test due to the presence of a hyphen. Even after trying to escape it using \-, the issue persists. Is there a way to accurately match the exact rout ...

Creating distinct droppable regions within a single HTML5 canvas

Is it possible to create multiple droppable areas within one canvas? An example of what I'm looking for can be seen at this link . My goal is to drag and drop images onto various sections of a single canvas. If anyone has insight on how this was achi ...

When iterating over each document in a Firestore collection in Node.js, utilize an if function statement

Struggling to implement an if statement for the 'one' and 'two' functions. Currently, the statement is working fine individually for each document, but I can't figure out how to make it run for each document in a collection. I trie ...