Having trouble with looping the CSS background using JavaScript in CodePen

Can someone help me with looping through CSS background images?

Why is the background not changing in this code example: http://codepen.io/anon/pen/dGKYaJ

const bg = $('.background').css('background-image');
let currentBackground = 0;
const backgrounds = [
    bg.replace('url(','').replace(')',''),
    'https://placehold.it/300x300&text=1',
    'https://placehold.it/300x300&text=2'
];

function changeBackground() {
    currentBackground++;
    if(currentBackground > 2) currentBackground = 0;

    $('.background').fadeOut(3000, () => {
        $('.background').css({
            'background-image': "url('" + backgrounds[currentBackground] + "')"
        });
        $('.background').fadeIn(3000);
    });

    setTimeout(changeBackground, 7000);
}

$(document).ready(() => {
    setTimeout(changeBackground, 7000);        
});

Any suggestions are welcome!

Thanks!

Answer №1

  1. An error message appears in the Console :

    Uncaught ReferenceError: $ is not defined
    

    The jQuery library was not included in the codpen settings. Please refer to this working codepen for a solution.

  2. Another issue to address in line 2 :

    bg =
    bg.replace('url(','').replace(')','');
    should be replaced by :

    bg = bg.replace('url(\"','').replace('\")','');
    

    Otherwise, the value of backgrounds[0] will have double quotes ""https://..."", resulting in a 404 error when attempting to load the image.

var bg = $('.background').css('background-image');
bg = bg.replace('url(\"','').replace('\")','');
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = String(bg);
backgrounds[1] = 'https://placehold.it/300x300&text=1';
backgrounds[2] = 'https://placehold.it/300x300&text=2';


function changeBackground() {
    currentBackground++;
    if(currentBackground > 2) currentBackground = 0;

    $('.background').fadeOut(3000,function() {

        $('.background').css({
            'background-image' : "url('" + backgrounds[currentBackground] + "')"
        });
        $('.background').fadeIn(3000);
    });


    setTimeout(changeBackground, 7000);
}

$(document).ready(function() {
    setTimeout(changeBackground, 7000);        
});
.background
{
  background-image:url("https://placehold.it/300x300&text=original");
  height:300px;
  width:300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="background"></div>

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

Find all elements with the same class and identify the first element among them using jQuery

In my dynamic data structure, I need to filter out all elements with the class name "My_data" and select the first one. In the code below, I am looking to retrieve the first element with the class "My_data". <div class="all_data"> <div class="lis ...

The page remains static even as the function is executed

Having trouble with creating a sliding form using jQuery. The issue is that instead of sliding to the desired page, it slides to a blank one. The website where this problem can be seen is www.entrilab.com. Upon inspecting the element, there are no errors ...

Material-UI LeftNav with a sticky header

I attempted to create a fixed header, specifically a Toolbar, inside a LeftNav so that when the LeftNav is scrolled, the Toolbar remains in place. However, for some reason, setting position: 'fixed' on the Toolbar does not work within the LeftNav ...

Utilize HTML strings to serve static files in express.js

While I primarily focus on frontend development, I often face challenges when working on the server side. Currently, I have a server.js file that includes: const express = require('express'); const http = require('http'); const path = ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...

tips for dynamically highlighting search bar after choosing a different dropdown option - vuejs

I need to filter products in my application based on name and category. To achieve this, I have included a search text box and a dropdown select box. The dropdown select box offers two options: 1. Search products by name 2. Search products by category name ...

I am experiencing an issue with my jQuery loop code not functioning properly when using the .each method within the loop

I am struggling with the following code. <input type="text" name="1" class = "inp<?=$p?>"> <input type="text" name="2" class = "inp<?=$p?>"> <input type="text" name="3" class = "inp<?=$p?>"> <input type="text" na ...

What is the process for transmitting data in JSON format generated by Python to JavaScript?

Utilizing Python libraries cherrypy and Jinja, my web pages are being served by two Python files: Main.py (responsible for handling web pages) and search.py (containing server-side functions). I have implemented a dynamic dropdown list using JavaScript w ...

Trouble with $.getJSON while trying to obtain song tempo data with getSongBPM

Still learning the ropes, so bear with me. I am trying to retrieve the BPM of a song using the getSongBPM public API. However, I'm not seeing any data in the console. // Please note that the API key has been updated $.getJSON("https://api.getsongbp ...

adjust the dimensions of the clickable icon's background

Is there a way to expand the pressable area of a close icon without altering its size? For example, if the icon is 19X19 pixels, can the pressable area be increased to 39X39 pixels? The concern lies with the div element containing the close button and the ...

Issue with JQuery Event Listener on Canvas Subelement not functioning

I encountered an issue while trying to implement a custom crop rectangle on a canvas using JavaScript. I created a function that, when called, should add a child node to the existing canvas and use JQuery listeners to draw the rectangle. However, although ...

What is the purpose of using double % in Java or JSP?

Yesterday, while reviewing some code, I came across a line that seemed very peculiar to me. In a JavaScript function, there is a condition checking for a string passed as a parameter in the following manner: "%%unsubscribe%%". See the snippet below for re ...

Is the oscillator value remaining stagnant in Safari?

Is there a way to utilize the web audio API alongside NexusUI JS for dial/knobs? When I use Chrome, the dial changes the oscillator frequency, but in Safari, it seems to be playing the default 440hz. Can anyone guide me on what could be the issue or what ...

Problem with Pinia: nested array in an object

My unique store located within a vue3 application, contains an object called currentReservation with a property named pricings which is an array. Each pricing includes an id and quantity. When I add a new pricing, it is added to both the store and compone ...

Issue with handling promise rejection of type error in node.js

Whenever I try running node server.js in Node.js, an error message pops up saying 'Cannot read property 'length' of undefined'. Despite installing all the necessary libraries (such as request) and browsing through various related posts ...

Tips for implementing a linear gradient on a bar graph using Highcharts

I'm trying to create a bar chart using highcharts, and I want to apply a linear gradient for the bar fill color. However, I am not sure how to set this up. Can anyone provide some guidance or ideas? Here is an example of what I'm hoping to achie ...

Error: Unable to retrieve the "error" property as the data is not defined

Encountered a title error and struggling to fix it :(. Attempting to retrieve data from a signup page, here is the snippet of my JavaScript code: const SignupComponent = () => { const [values, setValues] = useState({ name: 'ryan', emai ...

You can only use the angularjs http function once

After browsing through similar forum posts, I was unable to find a solution to my issue. It could be due to my limited experience with JavaScript and Angular. Here's the problem: Desired Outcome: When I click a button, I want the data from the server ...