Slow transition with a gradual appearance and disappearance for the background

I am currently implementing a fading background image effect on my web page, where the current image fades out as the next one fades in. Here is my code:

    var backgrounds = [];
    backgrounds[0] = './img/bg.jpg';
    backgrounds[1] = './img/bg2.jpg';
    backgrounds[2] = './img/bg3.jpg';



function changeBackground() {
    currentBackground++;
if(currentBackground > backgrounds.length-1) currentBackground = 0;

$('.bgContainer').fadeOut(1500,function() {
    $('.bgContainer').attr('src', backgrounds[currentBackground]);
    $('.bgContainer').fadeIn(3000);
});



    setTimeout(changeBackground, 5000);
}

The functionality is working well, but I have noticed that each time the image fades in, other elements on the page start dropping frames and become laggy. Is there a way to optimize this to reduce frame drops?

.bgContainer{
position:fixed;
z-index: -1;
width:100vw;
height:100%;
top:0;
}

<img class="bgContainer" src="./img/bg.jpg">

Answer №1

If you're unsure about using CSS transitions for cross-browser compatibility, experiment with this approach:

.backgroundContainer {
    transition: opacity 1500ms ease-in-out;
}

Also, consider implementing the following code snippet:

$('.backgroundContainer').css('opacity', 0);

setTimeout(function() {
    $('.backgroundContainer').attr('src', selectedBackground);
    $('.backgroundContainer').css('opacity', 1);
}, 1500);

By leveraging CSS3 to manipulate opacity levels, as opposed to relying solely on JavaScript for property adjustments, you can achieve smoother background fades. Do note that this method may have limited support and performance consistency across different browsers; primarily compatible with modern versions such as IE10 and above.

Answer №2

Opt for CSS transitions over jQuery, as they are more effective, especially on mobile devices.

Dynamically add a class using JavaScript or jQuery to apply the desired effects to that class.

For further information on CSS transitions, refer to this resource.

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

A guide on updating label text using JavaScript or jQuery following a click on an HTML form

Seeking a solution to modify the text underneath a name form element on a squarespace.com website. This platform aids in website creation, but direct manipulation of the source code is not allowed. However, injecting JavaScript is permitted. I have identi ...

Incorporate Nested JSON within JSON using JavaScript

I am currently dealing with a table that has been created using ng-repeat for rows and columns. ng-model="tableValues[row][column]" The values for row and column are obtained from ng-repeat. The data in the table consists of dropdowns, which I want to po ...

Testing an asynchronous generator function in Jest using unit tests

I need help writing a unit test for a generator function where I am struggling to properly mock a read stream object (ReadStream). Here is the function I'm trying to test: public async *readChunks(file: string, chunkSize: number): AsyncIterableIter ...

"Encountering issues with Instagram embeds.js library failing to load

I've been working on a JavaScript function that loads the HTML embed code for Instagram posts. When the post appears, the photo is replaced by a grey background and the Instagram logo. Even though the post contains other information like hashtags, tim ...

Transferring a large object to a child process in Node.js can lead to slow performance

My scenario involves making multiple REST API calls from my node server to various public APIs. The responses can vary in size, with some being large and others small. To handle this, I need to convert the response JSON into a string. However, I am aware t ...

A collection of dynamically created checkboxes is being gathered into an array to capture all of their values at

Here is my code snippet: Checkbox1 content: Generated dynamically from a JSON list tr.append($("<td />").html('<input type="checkbox" id="reqid" name="reqid[]" value='+item+'>')); Checkbox2 content: Also generated dynamic ...

Ways to troubleshoot an issue that arises when the `onChange` event is not utilized in a radio button component on a

When using this component for radio buttons without the Onchange function, I sometimes encounter the following error on the page related to onUpdate: TypeError: this.props.onUpdate is not a function onChange(e) { let value = e.target.value; this ...

How can I align multiple lines of text vertically?

Currently employing: #leftfoot {padding-left: 20px; vertical-align: middle;} Unfortunately, this code is not yielding the desired results. Despite searching through numerous explanations, I haven't been able to find a solution that works for me. Can ...

Create unique pages based on varying content types

Let's consider the structure I am working with: _components (directories) x1.html x2.html x3.html On my initial page, I gather information from the YAM section for each component. https://i.sstatic.net/en6mC.png Now, I want to include a link f ...

Building a service operation for an untyped custom data service provider entity without relying on entity framework

In my C# project, I have created a custom Untyped Data Service Provider using OData. All required providers and interfaces have been implemented. Entities are dynamically specified during metadata creation only. Neither EDMX nor Reflection providers ...

Selected radio button from the $_POST method

Can you determine the value of a clicked button? <input type="radio" name="radio">Yes<br> <input type="radio" name="radio">No A PHP example $option1 = $_POST['radio']; After echoing, it consistently displays "ON". ...

When you access the `selectedIndex` property in JavaScript, it will return an object of type `HTMLSelect

I am currently working on a piece of code that retrieves the value from dropdown list items and then displays it in the document. To proceed, please select a fruit and click the button: <select id="mySelect"> <option>Apple</option ...

Deliver real-time updates directly to clients using Django Channels and Websockets

Currently, I am working on a page that needs to display live-updating data to the client. The rest of the website is constructed using Django framework, so my approach involves utilizing Channels for this purpose. The data that needs to be showcased is st ...

Implementing CSS counter-increment with jQuery

Is there a way to use jQuery to set the CSS counter-increment attribute on ".demo:before" even though jQuery cannot access pseudo elements directly? I recall seeing a suggestion on Stack Overflow about using a data attribute and then referencing that value ...

Issue with response.split(",")[0] in Internet Explorer

Here is the code snippet I am struggling with: <script> $('#blah').on('click', function(){ $.ajax({ type: 'POST', url: 'ajax.php', data: {"xxx":"yyy", "zzz":"nnn ...

Issues with utilizing Jquery datepicker within a Vue.js component's v-for loop in Laravel

I am facing an issue with the Jquery date picker inside a v-for loop in my vue.js component. The date picker works fine outside of the loop, but inside the loop it does not behave as expected. Here is a snippet of code where the date picker is working cor ...

Ensuring WCAG Accessibility Compliance - mandate the inclusion of at least one input in a fieldset

I'm working on a form where users need to provide at least one contact method from a group of fields, such as home, work, or mobile phone number. How can I ensure this meets the latest WCAG 2.2 standards? <!-- Other fields above and below --> ...

CodeIgniter 4 Route Fails to Respond when a Different Value is Provided

I am currently engaged in self-studying Code Igniter 4. My focus is on inserting records irrespective of transactions. I have defined parameters such as Add, Edit and Delete. In the case of 'Add' being the passed value, a new record will be inser ...

What is the process for uploading a file in binary format using the ng-file upload library in AngularJS?

While trying to upload a file to Amazon S3 Bucket using a pre-signed URL from AngularJs, I encountered an issue where the zip file ended up getting corrupted. Interestingly, everything worked as expected when I uploaded the file from Postman in binary form ...

When the dropdown menu is displayed, apply a class to the parent <li> element's

Encountering a frustrating problem where I'm trying to assign a class to an li a when its submenu is visible. However, the class is being added to all li a elements, including those in the submenu. <ul id="nav"> <li><a href="#" tar ...