Executing AjaxStart in a JavaScript file for a specific page selection

Seeking advice on how to restrict access to an ajaxStart function in a JavaScript file to only certain pages.

The code snippet below shows the current implementation:

$(document).ready(function()
{
    $(document).ajaxStart(function()
    {
        $("#overlay").css
        ({
        "display"           : "block",
        "background-color"  : "rgba(255, 255, 255, 0.4)",
        "width"             : $(document).width(), 
        "height"            : $(document).height(),
        "position"          : "absolute",
        "z-index"           : 99999 
        })
    });
    $(document).ajaxComplete(function()
    {
        $("#overlay").css("display", "none");
    });
});

This HTML snippet below displays a loading gif inside a div upon button click events that are triggered from various HTML pages:

<div id="overlay" style="display:none">
    <img src='loading.gif'/>
</div>

Answer №1

It is a bit unclear to me whether you want the overlay to be triggered on button click in addition to the onload functionality, or if you want it to replace it altogether.

Either way, here is how you can trigger the overlay via a Button:

HTML:

<button onclick="showOverlay()">Click for Overlay</button>

JS:

function showOverlay(){
    $(document).ajaxStart(function()
    {
        $("#overlay").css
        ({
        "display"           : "block",
        "background-color"  : "rgba(255, 255, 255, 0.4)",
        "width"             : $(document).width(), 
        "height"            : $(document).height(),
        "position"          : "absolute", 
        "z-index"           : 99999 
        })
    });
    $(document).ajaxComplete(function()
    {
        $("#overlay").css("display", "none");
    });
}

Answer №2

It's best practice to keep this code separate from your general script, such as 'common.java'. Create a new file like 'ajaxstart.java' and include this code only on the specific pages where you need it.

Keep in mind that using the ajaxStart event will apply to all ajax calls on all pages, even ones where you may not want to display the CSS. I suggest manually adding the CSS to each ajax call like this:

$('.button').click(function() {
    // Triggering an ajax function on button click
    $("#overlay").css({
        "display": "block",
        "background-color": "rgba(255, 255, 255, 0.4)",
        "width": $(document).width(),
        "height": $(document).height(),
        "position": "absolute",
        "z-index": 99999
    });

    $.post('script.php', {
        variable: variable,
        char: char,
    }, function(result) {
        alert(result);
        // Handling completion of ajax call
        $("#overlay").css("display", "none");
    });
});

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

ESLint encountered an error while attempting to load the configuration "next/babel" for extension

Every time I try to generate a build of my Next.js app by running "npm run build," I keep encountering this error. Check out the error I'm getting while running npm run build here. Also, take a look at my .eslintrc.json file here and my .babelrc file ...

JQuery event failed to trigger on the sorted row extraction using datatable.js

Utilizing DataTable.js to display data, I have <select> options in each <tr>. By default, DataTable only shows the first 10 rows with default parameters, and there's a JQ change event that is triggered for these initial rows. However, if t ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Issues with the count up functionality in jQuery

I'm currently working on a project involving countups. My aim is to have multiple countups displayed on a single page. While having one countup using interval() function poses no issues, I encounter trouble when trying to display two or more countups ...

What causes the vertical scroll bar to shift on its own?

I'm puzzled by the behavior of the vertical scroll bar when clicking on "Line 9" - it automatically moves to the top position and subsequent clicks don't affect it. Can someone shed light on why this happens and how to resolve it? I am using Fire ...

Why would one utilize window.location?.search?.split?

Could someone explain the purpose of using window.location?.search?.split('=')[1] and why the value of id is set to window.location?.search?.split('=')[1]? Code: function EndScreen() { const [score, setScore] = React.useContext(Score ...

displaying data once "other" is chosen from a dynamic chart

I am having an issue with a dynamic table where I have a dropdown list with the option "other", and I want to display additional input when "other" is selected. Currently, the function I have only hides the input that is always visible and does not show ...

Personalize Angular material mattooltip and style information for display in tooltip

I need assistance displaying data in a tooltip in JSON format similar to the image provided. Although I can load the data in the tooltip, it does not appear formatted like the attached picture. <ng-container matColumnDef="Alert"> &l ...

Show a dynamic Swiper carousel upon selecting a thumbnail in an image gallery

I am in the process of creating a thumbnail gallery that includes a slider feature using Swiper. The default setup has the slider hidden, and once an image is clicked, the slider should appear with the selected image. To close the slider and return to the ...

When a user hovers over an li element, jQuery will dynamically adjust the width of the element based

<ul class="level0"> <li class="level1" id="cat2441"></li> <li class="level1" id="cat2450"></li> <li class="level1" id="cat2455"></li> </ul> <div class="alles-zwei" id="new-cat2441"></div> <div ...

Tips for showcasing Markdown files within subdirectories in Next.JS

In my Next.JS project, I am managing numerous Markdown files that are organized into various category folders. For example, I have folders named 'CategoryOne' and 'CategoryTwo' located at the root level of the project alongside node_mod ...

JavaScript popup cannot be shown at this time

I'm encountering an issue with displaying popups using JavaScript. Currently, only the div with class "popup" is being shown. When a user takes action, both popup and popup2 should be displayed but for some reason, it's not working as expected. ...

Discovering the following element containing an ID attribute with jQuery

Upon clicking a link, my goal is to locate the subsequent <section> with an ID attribute and retrieve its ID. In the provided code snippet and JavaScript function, the expected outcome upon clicking the link is for "section_3" to be logged in the co ...

Create a library with CSS files added, excluding any test files

As I develop a React library, I've encountered an issue where the CSS files are being ignored during the build process. In an attempt to resolve this, I included the --copy-files flag in the build script, which successful copied the CSS files but also ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

Create a composition of several debounce promises in JavaScript

I am looking for a way to efficiently manage multiple costly server calls by continuously invoking a function that accepts a key and returns a promise containing an object. This object is guaranteed to have the requested key along with additional values, i ...

Safari experiencing issues with Brightcove's chromeless video player controls

There seems to be an issue with BrightCove's Chromeless player. When hovering over the controls (pause, play, and move to a specific time in the video), they appear but clicking on them causes them to just disappear instead of pausing/playing or movi ...

Exploring the world of logging in Nestjs to capture response data objects

I'm eager to implement logging for incoming requests and outgoing responses in NestJs. I gathered insights from various sources including a post on StackOverflow and a document on NestJs Aspect Interception. I'd love to achieve this without rely ...

NodeJs: Dealing with package vulnerabilities stemming from dependent npm packages - Tips for resolving the issue

Is there a way to address npm vulnerabilities that are dependent on another package? For instance, I'm encountering an error where the undici package relies on the prismix package. Things I have attempted: Executed npm audit fix Ensured Prismix is u ...