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

Tips for utilizing the onload attribute alongside the ng-controller directive to run a function that has been established within the controller

When trying to call the submit() function as soon as the page loads, I keep encountering a submit() method not found error. The positioning of ng-controller and onload is confusing to me. If there is an alternate method in Angular to achieve this, please ...

How can you change the width of <td> and <th> elements?

I am trying to keep a table header fixed at the top of a window, but for some reason, setting the widths of the <td> and <th> elements as shown below is not resulting in them having the same width (the column headers are misaligned with other c ...

Customize scaffolding.less for the body element

Recently, I've been putting together a webpage and decided to incorporate Bootstrap into the design. However, after adding Bootstrap, I noticed that it changed the background color of the body on my site. I have included a link to the fiddle below for ...

React Material UI issue: You cannot render objects as a React child. If you intended to display a group of children, make sure to use an array instead

I am encountering an issue with the code provided below and despite trying various fixes, I am unable to resolve it. componentDidMount() { axios.get('http://localhost:8080/home') .then((response) => { this.setState({ ...

Client.on facing issue with receiving data upon initial connection

Currently, I am utilizing the net module in order to establish a connection between my client and server. Below is the code snippet: const Net = require('net'); client = Net.connect(parseInt(port), host, function() { co ...

Tips for containing `overflow` within a flexbox container

I've organized my body space into three sections: header, content, and footer. To achieve a sticky footer effect at the bottom, I used the flex property in my layout. However, I'm struggling to add a scrollbar to my main container box. I've ...

Using Angular JS, apply multiple column filters within a table to refine the displayed data

I'm currently working on implementing a filter for multiple columns in a table that is being populated by the ng-repeat directive. <tr ng-repeat="descriptiveField in vm.descriptiveFieldList|filter:{name:vm.searchText}" ng-class-even="'even-bg ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...

Deactivating Bootstrap Modal in Angular

Looking for advice on managing a Bootstrap Modal in Angular 7 I have a Form inside a Bootstrap Modal that I need to reset when the modal is closed (by clicking outside of it). Despite searching on Google, I haven't been able to find a solution. Any ...

Guide to retrieving a .txt file from a separate domain using server-side JavaScript and transferring it to the client side

My goal is to retrieve a .txt file from a web server on a different domain that does not have CORS or web services enabled. I believe I will need to handle this task on the server side using Node.js and JQuery, but I am unsure of where to begin. Currently, ...

Developing a dynamic user interface using an Angular framework and populating it with

I am currently learning Angular (version 1) and facing an issue with my layout. I need to dynamically change the navigation based on the type of user that is logged in. To achieve this, I make an API request when the page loads to fetch the user object dat ...

`Using a Video in a JQuery Carousel`

Currently in the early stages of developing a JQuery Slider that will kick off with a video, transitioning into slideshow mode once the video concludes. My goal is to ensure compatibility with IE9 and lower, as well as iPhone devices, necessitating options ...

Changing the color of a single child object in Threejs

Hey there, I'm facing an issue with changing the color of a specific element in my 3D Model (imported using the GLTFLoader). I've included some images showcasing the model's structure. The element I'm trying to target is the one highli ...

There seems to be an issue with your SQL syntax that is preventing the data from being entered correctly into the database using Node.js, MySQL, and Express

After successfully displaying data from my database, I attempted to add data to it using the following code snippet: exports.tambahData = (req, res) => { var keyy = req.body.keyy; var valuee = req.body.valuee; var brand = req.body.brand; ...

What is the best way to widen each tab so they fill up the entire width of the content block?

As a newcomer to both programming and this website, I've been exploring various codes for creating vertical and horizontal tabs. I have a specific query about this particular example found at https://jsfiddle.net/eu81273/812ehkyf/: My goal is to adju ...

Tips for streamlining the JSON parse object prototype in JavaScript

I recently had a JavaScript object that was created without a prototype. let bar = Object.create(null); After reading and parsing a JSON file in Node.js, I reassigned the parsed data to bar. Here's how: fs.readFile('data.json', 'utf8 ...

Utilizing the optimal method for aligning text to either the right or left side

I am currently working on creating a container element with multiple child elements. I would like these elements to be aligned differently, some left-aligned and others right-aligned. This includes scenarios where the child elements themselves are containe ...

The validation process is still failing even though the correct credentials have been entered

I'm diving into the world of Javascript and DOM today, but I've hit a roadblock. Can you take a look at this code snippet and help me figure out what's causing me to always end up in the else block, no matter what I input in the text field? ...

ajax - send dropdown options as an array

On my webpage, I have a dropdown list that allows for multiple selections. Here is an example of how it looks: <select id="myId" > <option value="1">Value 1</option> <option value="2">Value 2</option> <option valu ...

Storing and Retrieving User Identifiers in Next.js

Currently, I am developing a project using Next.js and I have the requirement to securely store the userId once a user logs in. This unique identifier is crucial for accessing personalized user data and creating dynamic URLs for the user profile menu. The ...