Update the background image to be smoother, with no text overlay

I am working on a website where I need to smoothly change between background images. Here is the JavaScript code I currently have:

var bg=[
        'images/best.jpg',
        'images/61182.jpg',
        'images/bg.jpg'
       ];

   $('._container-1').css('background-image','url('+bg[2]+')');


window.setInterval(
    function(){
        img=bg.shift();bg.push(img);
        document.getElementsByClassName('_container-1')[0].style.backgroundImage='url('+img+')';
    },
    10000
);

However, I would like to make the image transitions slower and have attempted using jQuery's fadeIn/fadeOut methods like this:

window.setInterval(
        function(){
            img=bg.shift();
            bg.push(img);

        $('._container-1').fadeOut(600, function() {
            $('._container-1').css('background-image','url('+img+')');
            $('._container-1').fadeIn(600);
        });

    },
    17000
);

The challenge I am facing is that there are buttons and text within the container that also change with the images. I want the text and buttons to remain in the front at all times while only the background fades in/out. I hope my explanation makes sense.

If anyone can provide assistance, it would be greatly appreciated.

nina_berlini

Answer №1

To create the desired effect, I utilized 2 elements as background. You can also view the demo here.

HTML:

<div class="container">
  <div class="background"></div>
  <div class="background"></div>
  <button>
    Test button
  </button>
</div>

CSS:

.container { position: relative; line-height: 100px; }
  .container > .background,
  .container > .background { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-size: contain; z-index: 0; }

  .container > *:not(.background) { position: relative; z-index: 1; }

Javascript:

var bg=[
          'images/best.jpg',
          'images/61182.jpg',
          'images/bg.jpg'
       ];
var Transition = 1000;

$('.background').css('background-image','url('+bg[bg.length - 1]+')');
window.setInterval(
  function() {
    img=bg.shift();
    bg.push(img);

    var $Backgrounds = $('.background');
        $Backgrounds.eq(1).hide(0).css({
        'background-image': 'url('+img+')'
    }).fadeIn(Transition * .9);

    $Backgrounds.eq(0).show(0).fadeOut(Transition, function(){
        $(this).show(0).css({
        'background-image': 'url('+img+')'
      });
      $Backgrounds.eq(1).hide(0);
    });
  }, 2000
);

Answer №2

Create a wrapper element that contains both the background and button elements with absolute positioning and specific CSS styles. This allows you to independently control and animate the background and buttons.

var bg = [
  'https://placehold.it/1001x201',
  'https://placehold.it/1002x202',
  'https://placehold.it/1003x203'
];

$('._container-1').css('background-image', 'url(' + bg[2] + ')');

window.setInterval(
  function() {
    img = bg.shift();
    bg.push(img);
    document.getElementsByClassName('_container-1')[0].style.backgroundImage = 'url(' + img + ')';
  },
  10000
);

window.setInterval(
  function() {
    img = bg.shift();
    bg.push(img);

    $('._container-1').fadeOut(600, function() {
      $('._container-1').css('background-image', 'url(' + img + ')');
      $('._container-1').fadeIn(600);
    });

  },
  17000
);
.wrapper {
  position: relative;
  width: 100%;
  height: 200px;
}
._container-1 {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-size: cover;
  background-position: top center;
}
.buttons {
  position: absolute;
  width: 100%;
  text-align: center;
  bottom: 0;
  left: 0;
}
button {
  background: red;
  padding: 5px 10px;
  border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="_container-1"></div>
  <div class="buttons">
    <button type="button">
      Button A
    </button>
    <button type="button">
      Button B
    </button>
  </div>
</div>

Answer №3

I want to express my gratitude for your excellent solution. As someone who doesn't have extensive knowledge of jQuery, I have a question regarding the code you provided:

$Backgrounds.eq(1).hide(0).css({
    'background-image': 'url('+img+')'
}).fadeIn(Transition * .9);

Does this mean that the second "background-div" is initially hidden, then receives a new background image, and finally fades in? And does hide(0) indicate an immediate hiding action?

nina_berlini

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

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

What is the best way to refresh the script located within the head tag of an index.html file in an Angular

I've been looking for solutions, but I can't seem to find one. In my index.html file, I've placed some script within the head tag (even above the </body> tag) and included a $(document).ready function. The issue I'm facing is th ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

When a table row is selected, set the OnClick attribute of an input to the value of the TD cell in that row based on

I'm really struggling with this. So, here's the issue - I have a table where rows get assigned a class (selected) when clicked on. Now, there's an input inside a form that needs to redirect to another page when clicked, and it also needs t ...

Tips for utilizing the onclick method to modify an ejs variable

, I am currently in the process of developing a web application utilizing Node, Express, and ejs. Specifically, I have created a page that features a series of buttons (displayed in the first table) alongside an associated set of hidden divs (shown in the ...

A guide on rendering a JSON array received from a URL using AJAX in AngularJS

Upon receiving a JSON array from the following URL: , it appears like this:https://i.stack.imgur.com/1Xrf4.png Within my AngularJS controller, I have the following code: $('#example-1').DataTable({ "ajax" : 'http://blahblahbla ...

What steps can be taken to retrieve data from a database table using JavaScript?

I am encountering a very peculiar issue. The values that I need are visible when I receive them as a message from the server-web console. However, when I try to retrieve them using a for loop, I encounter an error 05-22 18:58:23.203: I/Web Console(29392): ...

CSS3 flip effect on hover and click causing issues

I have successfully implemented a card flip effect using CSS3. The card is flipped using jQuery and CSS CSS .flipped { -webkit-transform: rotateY( 180deg ); -moz-transform: rotateY( 180deg ); -o-transform: rotateY( 180deg ); transfor ...

Is it possible to transform an array into a JSON file and securely store/upload it in an AWS S3 bucket?

Recently, I started exploring aws and its capabilities. Currently, my focus is on developing a web application that allows users to input text in two separate fields. Subsequently, this text will be converted into a Json file and stored in the S3 bucket. ...

"Prevent further button clicks by disabling it after the initial click with ActionRowBuilder in Discord.Js

Encountering a puzzling issue where I am unable to disable a button after it has been clicked. The option to disable the button does not seem to appear. When attempting to deactivate the button, I utilize the following function: const row = new ActionRowBu ...

Problem with spacing in Bootstrap horizontal layouts

My project is currently empty except for a code snippet I copied from Bootstrap's horizontal gutters page. Unfortunately, I am not seeing any horizontal gaps as expected. Why could this be? It seems that only vertical gutters are working... Click her ...

How can I ensure that a bigger sprite image fits inside a smaller div?

I have a unique situation where I am working with a large image sprite that is 1030px by 510px and contains two smaller images, each being 515px by 515px. My goal is to extract the two small images from the sprite and set them as backgrounds for two <im ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Differences in weekend start and end days vary across cultures

Looking for a solution to determine the weekend days per culture code in Typescript/Javascript? While most countries have weekends on Sat-Sun, there are exceptions like Mexico (only Sunday) and some middle-eastern countries (Fri-Sat). It would be helpful ...

Using arrays to pass parameters in JavaScript

I have multiple sliders that require the same set of parameters to be passed to each one. My understanding is that I need to use an array for this purpose. However, as a JavaScript novice, I am unsure of the correct way to implement it. The parameters lo ...

The navigation bar buttons in my IONIC 2 app are unresponsive on both the

In Ionic 2 for Android, I encountered an issue with the title placement. To resolve this, I applied some CSS to center the title and added left and right buttons to the nav bar. However, when I tried to implement onclick functionality for these buttons, no ...

Sequelize.Model not being recognized for imported model

I am encountering an issue while trying to implement a sequelize N:M relation through another table. The error message I keep receiving is as follows: throw new Error(${this.name}.belongsToMany called with something that's not a subclass of Sequelize ...

Preserve the HTML file with all its source code intact

Looking to access a specific parameter on this webpage: . For instance, if I need to retrieve the "Topological Polar Surface Area" value. If I manually save the page using Internet Explorer, I can locate the value with these commands: cat file.html | gr ...

A regular expression in JavaScript for matching unpredictable numbers without any specific words preceding them

For instance, I am looking to extract the numbers that do not have 'the', 'abc', or 'he' before them; the89 (no match) thisis90 (match 90) iknow89999 (match 89999) getthe984754 (no match) abc58934(no match ...

The command "npm run build" is not running successfully, likely due to npm not being able to interpret ES6 syntax

I am currently developing a web application using Vue.js and Flask. While I can successfully compile the Vue app on my laptop by running npm run build and integrating the static files into my Flask app, I encounter an issue when attempting to do this on a ...