Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected.

The reason for using the background: url() property is to ensure that the banner image resizes smoothly when the browser window is resized. I am uncertain if this is the most effective approach to solve my issue.

EDIT - Although my current code successfully swaps the images in the banner, it does not implement the desired fadeIn() effect. There are no errors reported in the console.

CSS:

header div#banner {
    background: url(../image/banner/00.jpg) no-repeat center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    height: 300px;
}

JavaScript:

var bannerImages = new Array();
var bannerCounter = 0;

function run() {
    loadBannerImages();
    runBannerTimer();
}

function loadBannerImages() {
    var filePath = "image/banner/";
    bannerImages[0] = filePath + "00.jpg";
    bannerImages[1] = filePath + "01.jpg";
    bannerImages[2] = filePath + "02.jpg";
    bannerImages[3] = filePath + "03.jpg";
    bannerImages[4] = filePath + "04.jpg";
}

function runBannerTimer() {
    var t=setTimeout("swapBannerImage()",2000);
}

function swapBannerImage() {
    $('#banner').fadeIn(1000, function() {
        $('#banner').css('background', 'url(' + bannerImages[bannerCounter] + ') no-repeat center');
    });
    bannerCounter++;

    if (bannerCounter >= bannerImages.length) {
        bannerCounter = 0;
    }

    runBannerTimer();
}

Answer №1

Looks like your setTimeout function needs a little tweaking; give this code a try instead:

function startBannerTimer() {
    var timer=setTimeout(function(){
        changeBannerImage()
    },2000);
}

UPDATE

Check out the revised Banner Rotation function below:

function changeBannerImage() {
    $('#banner').fadeOut('slow', function(){
        $('#banner').css('background', 'url(' + bannerImages[bannerCounter] + ') no-repeat center').fadeIn('slow');
    });

    bannerCounter++;

    if (bannerCounter >= bannerImages.length) {
        bannerCounter = 0;
    }

    startBannerTimer();
}

Demo with Updates Here

Answer №2

If you want to achieve a fading effect for multiple images, consider using separate divs for each image and transitioning them in and out. These divs can still utilize the css background property as desired, but they must be positioned absolutely to overlap one another. In order to ensure that the absolute divs resize proportionally with the parent container and maintain a "pleasant" resizing effect, you should structure the css in the following manner:

header div#banner {
    ... /* include your background styling here */
    position: absolute;
    left: 0;
    right: 0;
    height: 300px;
}

Be sure to specify both left and right properties to occupy the full width of the parent container. Additionally, confirm that the parent container has a value of position:relative.

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

Is the ID selector the quickest method in jQuery and CSS?

Which is the optimal choice in jQuery/javascript for speed? $('#myID .myClass') or $('.myClass') What is the preferred option to utilize in CSS? #myID .myClass{} or .myClass{} In hindsight, I realize my explanation was insuffici ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Tips for ensuring sequential execution of $.post requests without ajax alternative

Can I make synchronous requests with $.post in this code snippet? function loadTest() { var questionIDs = []; var count = 0; console.log("getting test"); $.post("db.php", function(data) { obj = jQuery.parseJSON(data); var questionCount = obj.l ...

With Crypto-JS, a fresh hash is always generated

I'm looking to integrate crypto-js into my Angular 8 application. Here is a snippet of my code: import {Injectable} from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Injectable() export class HprotoService { public ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

Troubleshooting: Issue with saving data from Backbone.js model. Information did not transmit

Exploring the world of Backbone.js, I am faced with a challenge in saving a model instance while utilizing Django as my server. Here is the client-side code snippet: var Song = Backbone.Model.extend({ defaults: { name: 'New Song' ...

Replace existing styled-component CSS properties with custom ones

One of my components includes a CheckBox and Label element. I want to adjust the spacing around the label when it's used inside the CheckBox. Can this be achieved with styled()? Debugging Info The issue seems to be that the className prop is not b ...

Could you display the picture prior to the function commencing?

This is the image that needs to be loaded before the loop begins. <div id="attendenceGridDivLoader" style="display:none"> <img src="<?php echo base_url() . 'images/loader.gif'; ?>" /> </div> <select onchange=checkAll ...

"Ensure only one checkbox is selected at a time by unchecking the previous

Hi, I'm facing two issues with the code below. The first problem is that when I select checkbox number 3, it automatically selects number 2 as well. I only want this to happen if I manually check it (similar to checkbox number 2). The second issue i ...

Text encoded in UTF-8 emerges from the surrounding frame

As someone who is relatively new to frontend development, I recently created a blog using a template that utilizes Next.js, Tailwind, and React. However, when I input UTF-8 text in Korean, the text overflows outside of the parent frame on mobile devices. ...

retrieve the value of a specific key from an array

How can I extract key-value pairs from an array in JavaScript where the data is structured like this? jsonData = [ {"dimensions":[5.9,3.9,4.4,3.1,4.8],"icon":0,"curves": [false,false,false,false,false],"id":"p1","color":"0x000000"}, {"dimensio ...

How to efficiently handle a queue of JSON calls and callbacks using jQuery

This Question May Have Been Asked Before: Sequencing ajax requests I am faced with the task of retrieving songs by various artists through an array of artist names using Ajax calls to a remote webservice. My main concern is ensuring that all the ajax ...

Using CSS to leverage the power of both Grid and Flex simultaneously

Help Needed: CSS Challenge! I'm not a fan of CSS and can't seem to crack this code conundrum. Here's what I want the end result to look like: Current Situation: #newOrderControl { border-style: solid; border-color: black; b ...

An error occurred while trying to initialize the ui.bootstrap.demo module in AngularJS

Currently, I am in the process of learning angularjs and have encountered a roadblock. An error keeps popping up: ncaught Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap.demo due to: Error: [$injector:nomod] Module 'ui.bootstr ...

Is there a way to synchronize the autohide duration for both the LinearProgress MUI and SnackBar components?

Can someone help me align my SnackBar with the LinearProgress so that they both have an auto-hide duration of 4 seconds? I've been struggling to figure it out for hours and haven't found a solution yet. Could the issue be in the useEffect part of ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Unlock the power of JavaScript and jQuery by utilizing inner functions

Here's some JavaScript and jQuery code with an ajax request included. Can you solve the mystery of why success1() can be called, but not this.success2()? Any ideas on how to fix this issue? function myFunction() { this.url = "www.example.com/ajax ...

403 Forbidden - CSRF Token Not Recognized

I am encountering an issue with Node Express and CSurf - 403 (Forbidden) Invalid csrf token. After reviewing other solutions and attempting all available options, I am still unable to resolve this. The API functions perfectly when tested in Postman. Howe ...

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...

Troubleshooting CSS Animation Failure in Internet Explorer 11

My mouse over / mouse out animation works perfectly in Firefox and Chrome, but it's not functioning in IE. Can anyone suggest why this might be happening when it was working fine before? var actual = 1; var over = 0; var over2 = 0; function scrol ...