Display the background image with a smooth fadeIn transition

My goal is to display a div background using the fadein() effect once it has finished loading.

After some research, I found a helpful topic on Stack Overflow which works well with an <img> tag.

I want to achieve the same effect with the CSS background property of a div. Here is the code I have been trying to implement:

HTML

<div id="some_target"></div>

CSS

#some_target {
  position: absolute;
  width: 100%; height: 100% ;      
}

jQuery

$(document).ready(function() {
var newImage = "url(http://vanusasousa.com.br/sicom/img/background2.jpg)"; //Image name

  $("#some_target").hide() //Hide it
    .one('load', function() { //Set something to run when it finishes loading
      $(this).fadeIn(); //Fade it in when loaded
    })
    .css('background', newImage) //Set the background image
    .each(function() {
      //Cache fix for browsers that don't trigger .load()
      if(this.complete) $(this).trigger('load');
    });   
});

Although the code seems correct, it's not working as expected. You can view the issue on jsFiddle where I've been testing it out.

If anyone knows what I might be doing wrong, any help would be appreciated.

Thank you to everyone.

Answer №1

.load and .complete aren't meant for divs, but you can achieve the desired effect by creating an <img> element and utilizing its triggers to update the div correctly.

var newImage = "http://vanusasousa.com.br/sicom/img/background2.jpg";
$("#some_target").hide().css('background', 'url(' + newImage + ')');
var $img = $("<img>").attr('src', newImage).one('load', function () {
    $("#some_target").fadeIn();
});
if ($img.get(0).complete) {
    $("#some_target").fadeIn();
}   

http://jsfiddle.net/DfFhp/2/

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

Content is the main driver for CSS Flexbox dynamic aspect-ratio code

When creating a grid layout for a webpage, I opted to use Flexbox. My goal was to incorporate some automatic functionality so that additional grid boxes could be included without the need to manually add classes or styles in the HTML code. One particular f ...

What is the best method to extract the country_code from JSON data using jQuery or JavaScript?

{ "status": "success", "description": "Data successfully received.", "data": { "geo": { "host": "2405:204:3213:5500:b012:b9d5:e4db:47b6", "ip": "2405:204:3213:5500:b012:b9d5:e4db:47b6", "rdns": "2405:204:3213:5500:b012:b9d5:e4db ...

How can I stop iOS mobile browsers from automatically opening apps when I click on links?

Recently, I discovered an issue with my website when accessed on mobile (iOS). The links to external websites, such as Amazon product links, are causing the Amazon app to open instead of simply opening a new tab in the browser. The HTML code for these lin ...

Tips for sending multiple JSON objects using the ajax() method

As of now, I have successfully implemented a $.getJSON() call to fetch a JSON string from a specific URL. Here is the simplified code that is currently functioning well: $.getJSON("myURL",function(data){ var receivedJSON = data; }); The retrieved JSO ...

Using AJAX and JQUERY to display a value in HTML

JavaScript <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#but").click(function(){ $.ajax({ ...

Using the jQuery library for asynchronous AJAX requests can lead to variables being replaced when loading data

I am facing an issue with my code that loads details about user payments one month in advance. The current function works fine when loading data for each month individually, but it fails when multiple ajax requests are made simultaneously. It seems like du ...

Utilizing media queries and JQuery to display a variety of menus based on screen

I have created a hamburger menu specifically for smaller screens, and it is functioning properly on small screens. However, I am facing an issue where if the menu is not open before resizing the screen to a larger size, the menu does not show at all. When ...

Tips for utilizing if statements in ng-repeat to display a unique combination of arrays while excluding duplicates in ng-options

I am faced with the challenge of working with multiple arrays in my AngularJS project. One array, owner_users, contains information about user ownership, while another array, admin_users, stores data on admin users. A third array, test_users, holds infor ...

What is the process for transforming a URL into an image?

I have the following code that currently detects if a URL is pasted into a contenteditable div. If a URL is pasted, it will automatically be converted into a link (surrounded by a tags). How can I modify this so that when a user pastes an image URL, it wi ...

Encasing a jQuery plugin within an AngularJS directive

In my pursuit to wrap a jQuery plugin (addtocalendar) in an angular directive, I encountered a challenge. Following advice from answers found here, the plugin worked fine initially, but once I navigated away from the state and back again, the addtocalendar ...

Can you provide me with advice on how to make a materialize table responsive?

Here is the script I am using: <table class="responsive-table"> <thead> <tr> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thr</th> <th>Fri& ...

employing JavaScript to present an image

Here is the image code I have: <img id="imgId" src="img/cart.png" style="display: none"/> After clicking a button, it triggers a JavaScript function to show the image document.getElementById("imgId").style.display = "inline" The image display ...

The deletion was not successfully carried out in the ajax request

Can anyone help with an issue I'm having while trying to remove a row from a table using the closest function? The function works fine outside of the $.post request, but it doesn't work properly when used within the post request. Here is my code: ...

When taking a vertical picture on my iPhone, my Vue component does not function properly

Having trouble with displaying recently uploaded images on a form. If the image is taken from a phone, it may have an exif property that browsers do not handle correctly, causing the picture to appear flipped or sideways. Upside down photo To fix this is ...

Saving the created PDF documents on the server

Utilizing the jsPDF plugin, I am currently generating a .pdf file upon clicking a button to initiate a download. Rather than downloading the file, I would like it to be saved onto my server when the button is clicked. Specifically, I want the file to be sa ...

Impact of Optgroup on dropdown menu width

I have never encountered this issue before, although I do have working examples. It could be related to how the content has been framed. .section-wrapper { width: 100%; margin-left: auto; margin-right: auto; margin-top: 10 ...

What is the best way to eliminate the white border from my website's code?

If you'd like to see the code in action, check out my JSFiddle html, body { height: 100%; } #background { height: 100%; background: url(http://phosproject.com/wp-content/themes/phos_theme/images/7.jpg); no-repeat center cente ...

jQuery Mobile experiencing issues with certain links getting stuck on loading

For some reason, when using jQuery Mobile, certain links are getting stuck on the loading spinner and not opening the next page. Here is the code snippet: <div data-role="page"> <div data-role="content"> <ul data-role="listview" ...

Where can I locate documentation on the source code of Node Red Editor in order to customize the CSS and JS for the client?

I am seeking assistance in modifying the following files: red.min.js located at: ~ npm\node_modules\node-red\node_modules@node-red\editor-client\public\red style.min.css located at: ~ npm\node_modules\node-red\ ...

Automatically reset the form after submission in CakePHP 1.3

I've encountered an issue with my report form that is linked multiple times on a page to a jQuery dialog box. To prevent cross-posting, I added a random string to the submission process. After successfully submitting the form on a single page access, ...