Execute a function within the ajax success callback

I have crafted a code snippet that scans through all images within a specified div and assigns classes based on their sizes.

Currently, this functionality is set to run when the document loads, and it works flawlessly upon initial page load.

However, I am developing a content management system where users can edit text directly on the page, triggering an update via ajax.

The response from this call typically resembles:

success: function (response) {
    if (response.databaseSuccess) {
        $("#container #" +response.postid).load("#container #" +response.postContentID);
        $targetForm.find(".saveupdatebutton").qtip("hide");
    }
}

After this update, the images within the dynamically loaded div are not resizing as intended.

I've attempted placing the image manipulation code inside the success callback, but it hasn't been successful.

What would be the correct way to execute the code after receiving the response?

Below is the snippet in question:

$(document).ready(function () {
// Iterate through each image in the .blogtest divs to determine their width. If it's greater than X, make it full size; otherwise, keep it normal.
var box = $(".blogtest");
box.find("img.buildimage").on('load', function () {
    var img = $(this),
        width = img.width();
    if (width >= 650) {
        img.addClass("buildimage-large");
    } else if (width < 500 && width > 101) {
        img.addClass("buildimage-small");
    }
    // If the image is less than X, it's likely a smiley
    else if (width < 100) {
        img.addClass("buildimage-smiley");
    }
    }).filter(function () {
        // Manually trigger the event if the image is already loaded
        return this.complete;
    }).trigger('load');
});

Answer №1

Depending on the version of jQuery you are using, a simple change from .on to .live might do the trick:

box.find("img.buildimage").live('load', function () {

If that doesn't work, here's an alternative method:

Start by externalizing your function for image resizing:

$(document).ready(function () {
    // check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
    var box = $(".blogtest");
    box.find("img.buildimage").on('load', imageOnload)
        .filter(function () {
            //if the image is already loaded manually trigger the event
            return this.complete;
        })
        .trigger('load');
});

function imageOnload(evt){
    var img = $(evt.currentTarget),
        width = img.width();
    if (width >= 650) {
        img.addClass("buildimage-large");
    } else if (width < 500 && width > 101) {
        img.addClass("buildimage-small");
    }
    // if image is less than X, its most likely a smiley
    else if (width < 100) {
        img.addClass("buildimage-smiley");
    }
}

Then, simply include this statement in your success callback:

$("#container #" +response.postid).on("load", imageOnload);

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

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

A pair of div elements within one section

Can you explain why the following HTML code uses two divs, one with a class and the other with an ID, instead of just using one of them to assign properties? .header { background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/ ...

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

Boosting autocomplete speed by storing the JSON response in a cache for enhanced performance

Currently, I am utilizing the FCBautocomplete plugin for auto-complete functionality. However, I have noticed that with each character entered into the field, a request is sent to the server for results. With my large dataset, this raises concerns about po ...

The functionality of the Ajax call ceases to function properly on mobile devices after a period of time

I'm currently developing a mobile application using Cordova, AngularJS, and jQuery. My issue lies in trying to retrieve two files from the same directory. The first file retrieval is successful and occurs immediately after the page loads. However, t ...

How can I optimize the display of 4 million 2D squares on a web browser?

With a display resolution of 7680x4320 pixels, I aim to showcase up to 4 million distinct colored squares. My objective is to adjust the number of squares using a slider. Currently, I have two versions in mind to achieve this goal. The first version involv ...

Ways to generate multiple void components side by side using React

What is the most efficient method for creating multiple empty inline elements using React in a declarative manner? Suppose I need 8 empty divs, I tried the following approach but it didn't work. Is there a more effective way? render() { return ( ...

Using Python and Selenium to Scroll Down the Page (with Two Separate Scrollbars)

I need help scrolling down the conversation section on Facebook Messenger. There are 2 scroll bars on the page, and I specifically want to scroll down scroll bar number 1 (see image) Click this link to access the page (make sure you are logged in and hav ...

Ways to update the page content seamlessly without refreshing the page

Is there a way to dynamically change the content of a specific div (such as: <div id="MyDiv"></div>) on a webpage using PHP when clicking a link? Previously, I attempted the following approach: $(function(){ $("a").on("click", function () ...

Chaos in asynchronous Node.js execution orders

Here is a snippet from my code: async.forEachOfSeries(dates, function(mydate, m, eachDone) { eachDateParse(Name,Place,Strategy, eachDone) }, function(err) { if (err) throw err; console.log("All Done!"); callback(); } ); While async.f ...

What is the best way to conceal selected options in a MUI multiselect in the select field?

I'm currently working with a MUI multiselect feature to allow for the selection of multiple options from a dropdown menu. However, I am facing an issue where I do not want the selected options to be visible within the dropdown field. Is there a way to ...

Is there a way to display menu items in a list when hovering over the parent element using CSS?

Is it possible to make the code below run when hovering over (#cssmenu ul > li > ul > li ) with the mouse? #cssmenu ul > li > ul > li > ul { right: 1170px; } ...

Tips for Centering Text next to Logo on Mobile Display with Bootstrap 5

My website I've designed with Bootstrap 5 is facing responsiveness issues. While everything looks fine on desktop, the text and logo are misaligned in the mobile view. Here are screenshots demonstrating the problem: https://i.sstatic.net/jA5QTfFd.jp ...

The issue of jQuery file upload not functioning on every row of an ASP.NET repeater

Incorporating a jQuery file upload button in each repeater row has resulted in a display issue where only the selected files for the first row are shown. For subsequent rows, only the total count of selected files is displayed without the progress bar sh ...

Is there a way for senders to also view their own messages using socket.io?

Using socket.io, I am trying to send a message to a specific user based on their socket.id, and also ensure that the sender can see their own message. The code snippet I am using for this is: socket.to(msg.id).emit('chat message', msg.message);, ...

Enhancing a JQuery Element to Suit Your Needs

Is it recommended to enhance a JQuery element with custom methods? For example: var b = $("#uniqueID"); b.someMethod = function(){}; Additional Information Let me explain further, I am developing a JavaScript application that binds JSON data to local J ...

The custom checkbox feature is not appearing on Google Chrome browser

I need help creating a custom checkbox in HTML using CSS. It works fine in IE, but in Google Chrome, it's displaying the default checkbox instead of my custom one. What changes do I need to make for it to work in Chrome? HTML <link href="btn.css ...

Struggling to bind an array in React

I'm currently diving into React and I've encountered a challenge in handling data from a REST API within my React application. Specifically, I'm retrieving Pokemon cards data from a Pokemon TCG API in JSON format that includes various detail ...

Ways to create interaction between two web pages with JavaScript

I am attempting to design a webpage where one page can influence the content of another page. I have two HTML pages and a JavaScript file named "Controll.js" which contains a function that changes the content of "Indiv" in Index.html. This function is tr ...

Keep scrolling! There's no need to worry about reaching the end of the page and having to start over

I'm experiencing an issue where scrolling only works once when the page is initially loaded. I need it to be able to repeat from the beginning each time. <div class="content"> <div class="next-section blue">First Section</div> & ...