Gradually reveal the background image as the page loads

Is there a way to add a fadeIn effect to the random background image loading using jQuery? Currently, the script I am using displays a random background on refresh without the desired transition effect. How can I achieve the fadeIn effect when the image loads? Please note that I do not want the images to cycle.

$(document).ready(function() {
  var images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg', '06.jpg', '07.jpg', '08.jpg', '09.jpg', '10.jpg'];

  $('.about').css({'background-image': 'url(../img/bg/' + images[Math.floor(Math.random() * images.length)] + ')'});
  ('.about').fadeIn(1000);
});

Answer №1

$(document).ready(function() {
  var pictures = ['http://funmozar.com/wp-content/uploads/2014/09/Beautiful-Yellow-Birds-06.jpg', 'http://petblaster.com/images/Birdwall.jpg', 'http://www.nscblog.com/wp-content/uploads/2014/04/birds-314989.jpg'];

  var link = pictures[Math.floor(Math.random() * pictures.length)];
  var image = new Image();
  image.onload = function(){
    $('.about').css({'background-image': 'url('+link+')', 'background-size' : 'contain'});
    $('.about').fadeIn(1000);
  }
  image.src = link;
  
  
});
.about{
  width: 400px;
  height: 400px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="about"></div>

This code snippet preloads an image using the `new Image` method. It attaches an `onload` event which sets the background of the `.about` div with the chosen image and fades it in.

The URLs have been modified to show some actual results.

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

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...

ChartJS does not function properly when included in a .php file that is loaded using jQuery's .load() method (

I am facing an issue with this plugin not working when I use the jQuery ajax function .load(). Below is the snippet of my PHP code: <script src="../Chart.js"></script> <script type="text/javascript" src="../functions.js"></script> ...

Sending the format of the display value to an Angular component

Looking for a way to pass display value formatting to an Angular component. Here are a couple of examples: format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)' or format="'(tz, offset) location'" === &a ...

What other methods can be used to initiate an Ajax request?

I'm curious about the most efficient approach to making an AJAX call. My current code works perfectly fine: $.ajax({ url: "/rest/computer", type: "GET", dataType: "json", data: { assessmentId: "123", classroomId: " ...

How to eliminate gaps in CSS grid for optional areas

I've recently started experimenting with CSS grid and I have to say, it's pretty amazing! I'm currently working on a basic layout for mobile devices and using media queries to adjust the layout as the screen size increases. At the moment, m ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

Troubleshooting: Css navbar alignment

How can I center the navigation bar both horizontally and vertically? I've tried various methods but nothing seems to work. Here is my HTML: <section class="navigation" ng-controller="NavController"> <div class="nav-container"> ...

The Mystery of Blurriness: How CSS Transforms Can Cause Image Quality Loss

What causes an image to become blurry when rotated? I attempted to rotate an image 90 degrees, but the result is unexpectedly blurry. transform: rotate(90deg); This issue occurs in both Firefox and Chrome (other browsers have not been tested). For refe ...

Footer content spilling out of the wrapper div

My web page has a footer content that is overlapping the wrapper div due to some issues with my css and html. Even when I tried changing the height to auto, it didn't resolve the problem. Below is an example of the current state of the page I am worki ...

Exploring React: Opening a new page without rendering the SideBar component

I currently have an application with a sidebar that navigates to three different pages, all of which include a navigation bar and the sidebar. However, for the next page I want to exclude the sidebar but still include the navigation bar. How can I configur ...

Cease processing ajax requests on the server side

After conducting thorough research on the topic of canceling ajax requests, I have come across several threads discussing this matter. One particular thread caught my attention: Abort Ajax requests using jQuery The post explains how when you use the abor ...

What is the method for determining the angle between two planes?

My question is about calculating the angle between two planes. Is it also possible to calculate the angle between two Object3D points like we do with planes? If you need a visual example, check out this fiddle: https://jsfiddle.net/rsu842v8/1/ const ...

The CSS focus-within and hover properties are not functioning as expected

How can I make the search tags visible (the buttons above the text input field) when the search bar below them is clicked? I've tried using :hover, :focus, and :focus-within, but none of them seem to be working. Can someone help me figure out the issu ...

How can I send a value from a for loop to a URL within a modal using Django?

Currently, I am working on a project that involves using a for loop with buttons and their corresponding pk values. {% for obj in all_objects %} <button data-toggle="modal" data-id="{{ obj.pk }}" data-target="#myModal" class="open-my-modal"> {{ ob ...

Issue with CoffeeScript and three.js: scene not defined

I've been troubleshooting this issue for hours, but I can't seem to figure out the error... Here's the error message I'm getting: Cannot read property 'add' of undefined Below is my coffeescript code file (hopefully it&apos ...

Developing bi-directional binding for newly generated elements post initial compilation

I have developed a directive that dynamically generates a form based on a JSON received from the server. I am trying to include the ng-model attribute in the input elements so that I can access the input values once the user enters them and clicks submit. ...

Error parsing JSON data with jQuery.parseJSON

I'm having trouble converting the following string to a JSON object. An error keeps popping up, but I can't figure out why. var jsonData = "{'firstName': 'John','lastName': 'Smith', 'age': 25, &a ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

Exploring the option of eliminating the email field from the PHP redirect function and transforming it into a pop-up notification

I am currently utilizing the following code to send an email notification to my address whenever a new user signs up: <?php $errors = ''; $myemail = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0ded1ddd ...

Tips for Managing Disconnection Issues in Angular 7

My goal is to display the ConnectionLost Component if the network is unavailable and the user attempts to navigate to the next page. However, if there is no network and the user does not take any action (doesn't navigate to the next page), then the c ...