Executing a jQuery event after a div's background-image has finished rendering

Greetings and thank you for sparing a moment.

I'm curious to know if there exists a method through jQuery to execute a function immediately after a background image in a div has completed downloading and rendering.

Imagine you have the following div element:

<div id="img1" class="img1"> </div>

with the img1 class styled as follows:

.img1 {
    background-image: some_big_image.png;
    background-position:center;
    background-repeat:no-repeat;
    background-size:cover;  
    display: none;
}

taking into account this JavaScript function:

function showDiv() {
  $("#img1").fadeIn(1000);
}

Is it possible to invoke the above function right after the image has been rendered? By rendering, I mean resized to fit neatly within its div and ready to be displayed.

I've come across plenty of information on triggering functions after page loading or image downloading but nothing related to post-rendering.

Your assistance is greatly appreciated. Thank you in advance.

Answer №1

Attempt

let picture = new Image();
picture.src = "/large_picture.png";
picture.onload = function( ) {
    $("#pic1").css("background-image", "url('" + picture.src + "')" ).fadeIn(1000);
}

Fiddle here

Answer №2

Although you've already accepted an answer, there's a simpler way to achieve this using the jQuery magic function.

$(function() {
    $("#img1").fadeIn(1000);
}

You mentioned earlier that the onload event wasn't working for you. The $(function() { //code here } ); triggers when the DOM is fully loaded (not all browsers do this automatically for the onload event), which may be why you were experiencing issues. It's also convenient because you can use it in multiple places on your page and they will all be combined (unlike directly setting onload, which can be overridden if set elsewhere).

Check out this Fiddle: http://jsfiddle.net/5cR4G/8/

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

Activate video playback when scrolling, but ensure it only occurs one time

I've encountered an issue with my script that is meant to play a video when it reaches a certain position on scroll. The problem is, if the video is paused and scrolling continues, it starts playing again. I attempted to use just one scroll function b ...

Ways to retrieve the user's IP address and provide the information in JSON format

Although I am not an expert in PHP, I specialize in developing Android apps. One of the challenges I face is extracting the user's IP address from a specific URL . This URL provides various information when accessed, but my main requirement is to retr ...

Confirming if the value is an array using jQuery

Currently, I have a list of elements with various types associated with them. My goal is to identify specific text within these types and hide only those types that do not contain the desired text, leaving the rest unaffected. The structure looks like thi ...

Twitter typeahead with a dynamic array of strings

Currently, I am making an ajax call to retrieve a list of objects. Once this array of objects is filled, a separate string[] is created with the names of these objects. My goal is to pass this data to Twitter Typeahead using a Bloodhound source. However, ...

A guide to displaying API response data in a React JS application

As a beginner in react JS, I've encountered a persistent issue. Here is the code: import React from 'react'; class SearchForm extends React.Component { async handleSubmit(event){ event.preventDefault(); try{ const url ='/jobs/ ...

Another option instead of using jQuery to retrieve the active element in the

My goal was to determine when the user is interacting with an INPUT or TEXTAREA element and set a flag variable to true during this engagement. Once the user clicks out of these elements, the flag should be set back to false. To achieve this, I utilized j ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

Steps to enable navigation to external pages from a ReactJS app

I am working on a simple ReactJS application: [Demo] [Source] I am trying to implement navigation within the app from external sources without refreshing the web page. This functionality should be similar to using this.props.history.push(...). /public/i ...

Tips on retrieving a result from mongoose's findOne() function

I created a custom function using the findOne() method in Mongoose and now I need to use the result for another function. How can this be achieved? Thank you! module.exports.retrieveDeal = function(dealRequest){ Deal.findOne({name:dealRequest},functi ...

What could be the reason for the absence of definition for 'res'?

As I work on coding a bot using discord.js, I am facing an issue while trying to set up a system where the bot can send a message as long as it is not blacklisted. However, every time I attempt to run the function, I encounter this error message: Reference ...

Traversing an array and connecting each element to a separate array in AngularJS

In my programming task, I am working with an object and an array that are defined as follows: $scope.multipleTransferGotten = []; $scope.newParameters = { UserId: "", Udid:"", TransType: "", SourceAccNumber: "" ...

Text field suddenly loses focus upon entering a single character

In my current code, I have functions that determine whether to display a TextField or a Select component based on a JSON value being Text or Select. However, I am facing an issue where I can only enter one letter into the TextField before losing focus. Sub ...

When the mouse drags across the empty space, the force graph continually jumps

I have some questions. I utilized a force graph and added zoom functionality to it. However, when I drag the mouse over the blank area, the force graph keeps jumping erratically. like this Is there a way to prevent the graph from jumping? Thank you. ( ...

Stubbornly Persistent Server Error (Django and Ajax)

I've been using Ajax to send my data over to views.py, but despite terminating all the urls and configuring the form action for my url, I'm still encountering an internal server error. I'm struggling to pinpoint the issue, so any assistance ...

Retrieve the value from an input tag that is only displayed based on a condition using *ngIf

In my HTML form, I have implemented conditional visibility of input fields based on the radio button selection using *ngIf. <table> <tr> <td><label>name</label></td> <td><input #name />&l ...

Divide a string into separate array items where a specific character is found

Within my sentence are several characters (~). I want to split the text before each ~ into an array item, and then add a <br /> tag at the end of each item. I attempted using the replace method but it only worked for the first ~ and disregarded the ...

When working with ES6 modules, the value of `this` and $(this) can be undefined

I attempted to integrate the toggleImage functionality into a gallery and referenced this thread along with the code provided in one of the responses. However, upon doing so, I encountered the error message Uncaught TypeError: Cannot read property 'at ...

``In a jade view, navigating through JavaScript object properties leads to the addition of quotation marks around strings

Utilizing the npm module traverse to filter data from mongodb / mongoose has been quite helpful for me. Here is an example of the kind of data I might receive: [ { rating: 5, title: { da: 'Web udvikling', en: 'Web Development' } } ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...