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

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

Launching ExpressJS and ReactJS on Heroku

Currently working on a project that combines express and react. When attempting to deploy it to Heroku via git push, I encountered an error upon checking the heroku logs. The specified webpage then shows a message indicating that it cannot locate a build ...

Showing off map positions on D3 using data from a JSON array

I have received a JSON response containing coordinates from PHP in the following format: {"All":[{"longitude":"36.8948669","name":" Manyanja Rd, Nairobi, Kenya","latitude":"-1.2890965","userID":"1"}, ...]} Next, I am processing it using JavaScript as sho ...

What is the best way to resume a paused animation using JavaScript?

My first game involves triggering an animation that transitions the game screen to greyscale when the character dies. Despite my efforts, I have been unable to successfully trigger this animation using document.getElementById("object").animationP ...

steps for transferring a shallow copy of an array to a function

How can I adjust this code so that when I press each button, the console.log displays a different slice of the array instead of always showing me the last 20 elements? for (var i = 0; i < array.length; i++) { var b; var NewArr = []; ...

Tips for positioning a React component above another component

I am currently facing a challenge while working on a table with an expand more option to display additional details for each specific row. I have implemented a slider to facilitate the expansion of the table. Presently, my ExpandToggle component is embedde ...

When the play button is clicked, the video slides over to the left

Whenever I attempt to click on the video link, it seems to shift over to the left side of the page. The link is positioned in the center and I would prefer for the video to open up at the same central location. However, it consistently opens up on the left ...

An issue has been encountered in the following module federation: `TypeError: g.useSyncExternalStore is not a function`

I encountered an error after deploying my next app with module federation: TypeError: g.useSyncExternalStore is not a function The same app works fine as a standalone application when run with yarn dev or yarn start, but it fails when using module federat ...

What is causing a single state update when setState is called twice in React?

It seems like I'm making a beginner mistake in React as I am trying to call the "addMessage" function twice within the "add2Messages" function, but it only registers once. I believe this issue might be related to how hooks work in React. How can I mod ...

ajax is providing identical data when called too frequently

Using my barcode scanner triggers the function below, but scanning multiple barcodes quickly results in duplicate data being processed. The issue seems to be related to the async setting - when it's false, the process slows down significantly. Is the ...

Exploring the World of Micro-Frontends with the Angular Framework

I am conducting research on the best methods for transitioning a large single-page application into a micro-frontend architecture. The concept: The page is made up of multiple components that function independently Each component is overseen by its own ...

Obtain the names of the cities that the Google Maps route passes through

Currently working on a website that integrates Google Map API v3. Is there a method to gather the names of the places or cities along the route from point A to B? The page utilizes JavaScript for functionality. ...

Filtering an array of JSONs in Vue.js using a separate array of JSONs

In my code, there are two arrays of JSONs: one named products and another called deletedProducts. The task is to filter out the products that are not present in the deletedProducts array. For instance: products = [ { id: 1, name: 'Box&apos ...

Enhancing the accessibility of Material UI Autocomplete through a Custom ListboxComponent

I have developed a custom ListboxComponent for the MUI Autocomplete component in MUI v4. How can I ensure that it meets the necessary accessibility requirements, such as navigating through options using the arrow keys? <Autocomplete ListboxComponent ...

Implement a background image in the navigation bar links using CSS

Strange as it may seem, the image refuses to show up in the navbar. Adding borders or other styling makes it visible, but not the image itself. If I manually include the image using the <img/> tag in the HTML, it appears, but then the hover effect do ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

From converting Javascript code to PHP and using the innerHTML function for deletion

I'm currently working on implementing a script and could use some assistance with two specific issues that I'm struggling to resolve. The main goal is to enable users to create a running route and then store the route in a database using coordina ...

The website's content is displayed as a mobile-friendly menu

I've been working on creating a responsive menu using HTML and CSS, and everything is functioning well so far. However, I'm facing an issue with the mobile view of the menu. When the menu opens up, it obstructs the text below it, making it diffic ...