Jquery unable to change the css property 'background-image'

I'm currently working on creating a photo viewer for my website by cycling through an array of pictures. The cycling aspect is functioning properly, but I am encountering difficulties when trying to transfer the message to the CSS. I'm not sure if there are syntax errors in my JavaScript code or if I'm overlooking a key concept. I have confirmed that the cycling itself works as intended based on the alert that triggers.

var changeIt = ""
var backgroundPic = new Array(4);

backgroundPic[0] = '("images/displayPic1.jpg")';
backgroundPic[1] = '("images/displayPic2.jpg")';
backgroundPic[2] = '("images/displayPic3.jpg")';
backgroundPic[3] = '("images/displayPic4.jpg")';
backgroundPic[4] = '("images/displayPic5.jpg")';

var picCounter = 0;
var numberOfPics = 5;
var picTimer;

function setPic(){
    alert("hi I want this pic: " + backgroundPic[picCounter]);
    $('slider').css('background-image', url + "backgroundPic[picCounter]");

    picCounter += 1;
        if(picCounter >= numberOfPics){
        picCounter = 0;
    }

}

$(document).ready(function(){

    $('.slider').css('background-image', backgroundPic[picCounter]);

    picTimer = setInterval(setPic, 2000);

});

Answer №1

The problem arises from the incorrect syntax being used in your CSS property value concatenation. You can rectify this by following these steps:

let backgroundImages = [ 'images/displayPic1.jpg', 'images/displayPic2.jpg', 'images/displayPic3.jpg', 'images/displayPic4.jpg', 'images/displayPic5.jpg' ];    
let imageCounter = 0;
let imageTimer;

function setImage() { 
    // pay close attention to the '.' in the jquery object below indicating a class selector
    $('.slider').css('background-image', 'url("' + backgroundImages[imageCounter % backgroundImages.length] + '")');
    imageCounter++;
}

$(document).ready(function() {
    imageTimer = setInterval(setImage, 2000);
    setImage();
});

Answer №2

To apply a background image, use the following code snippet:

$('.carousel').css('background-image', "url('" + images[counter] + "')");

Answer №3

The order of the quotation marks on the second line of setPic has been reversed.

Suggestion:

$('slider').css('background-image', 'url' + backgroundPic[picCounter]);

Answer №4

When looking at the setPic function, I noticed something interesting with this particular line of code:

$('slider').css('background-image', url + "backgroundPic[picCounter]");

It seems like there might be a missing dot in $('.slider'). What do you think?

Answer №5

Make sure to add quotation marks (") both before and after the imageUrl, as shown below:

$('slider').css('background-image', 'url("' + backgroundPic[picCounter] + '")');

By doing this, even if the image file contains spaces, it will still be recognized as a valid property.

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

The jquery scrolltop() function provides the value of the scroll position prior to the current

Using the jQuery function element.scrollTop(), I attempted to retrieve the current scroll position of the page with the following line of code: var currentScrollPosition = $('html').scrollTop() || $('body').scrollTop(); However, this ...

Is it possible to disable 'rtl' using {flip: false}?

I am attempting to replicate the behavior demonstrated in the MUI docs at this link. When switching from 'ltr' to 'rtl', the 'Affected' content flips sides while the 'Unaffected' remains unaffected. To illustrate th ...

Vue - Display components based on the parent data's state

I am currently working on a project where I need to dynamically render components based on the state of an array in the parent component (App.vue). As someone who is new to Vue and not very experienced with programming, I am uncertain if this is the most e ...

Tips for creating a vertical navigation submenu with hover using Bootstrap style

How can I create a vertical navigation with sub-menu/widgets using Bootstrap 4.2.1? Here is the requirement: https://i.sstatic.net/JaiLV.jpg My attempt so far: The menu only works onclick, not on mouse over (sub menu still shows when mouse moves out). ...

invoking a SOAP endpoint with Node.js

I've recently delved into the world of Node.js and I'm attempting to integrate a SOAP service using the node soap extension. Right now, I'm just experimenting with a sample service call but I'm encountering some issues getting it to wor ...

Using Javascript and jQuery to retrieve a subarray value with a randomly generated array key

I am dealing with the JSON data provided below: { "0": { "jQuery331045811028719032642": { "stepCount": 1, "captionSize": 0, "countdown": true, "countdownAlertLimit&q ...

Generating an HTML table using a JavaScript object dynamically

I am in the process of dynamically generating an HTML table using information from a MySQL database table. The data within the table is regularly changing, requiring the HTML table to be updated accordingly when alterations are made to the database table. ...

Guide to creating standalone Express middleware that can interact with the raw request body

Can anyone help me with writing an Express middleware that can access the raw request body without affecting other handlers or middlewares? I want to achieve something like this: const middleware = [ express.raw({ type: '*/*' }), (req, res, n ...

Angular 13 doesn't recognize ViewChild

I am encountering an issue where I am attempting to access the view child of a child component from the parent component, but I keep getting an 'undefined' error in the console. Please refer to the image and check out the stack blitz for more de ...

Explain the significance of the symbols $$ and $ in the context of webdriver, and provide instructions on integrating them into

According to the webdriver documentation, using the $ and $$ functions in WebdriverIO can provide shortcuts for moving deeper into the DOM tree without relying on complex xPath selectors. Currently, I am working on writing a cucumber test for my Reactjs a ...

Issue with nested menu links not functioning properly in Semantic UI dropdown

Having trouble implementing links in nested submenus? <div class="ui menu"> <div class="menu"> <div class="ui pointing dropdown link item"> <i class="dropdown icon"></i> <span class="text">Menu</spa ...

What is the process for creating an HTML text box with horizontal menu tabs at the top for selection?

Sorry if my question is a bit confusing. I am not sure what the specific name for this type of text box is :( I am interested in creating an HTML text box with various menus at the top, where each menu heading contains additional text that expands when cli ...

Adjust the position of an object in Three.js based on the scale of another object

Sharing a helpful solution for a recent problem I faced in case it can assist someone else. Imagine you have a House object with a Chair inside it positioned in a particular spot. If you scale the House's size by 2, the Chair will no longer be in the ...

React: Unable to set scrollTop on a Div under certain conditions

I've been grappling with this issue since this morning and I still can't pinpoint where I went wrong. My goal was to highlight text within a textarea input, even though I know it's not technically possible. However, I came across a clever wo ...

Modifying a document by ID in Mongoose without altering a specific field

In my code, I have successfully established a new connection using Mongoose and implemented a schema. Retrieving attributes from the collection is also working as intended. However, when attempting to update my collection, I am encountering difficulties. T ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

No search results found on Dropbox. PHP

I've utilized this code in various projects I have created, but for some reason it is not functioning correctly now. To me, everything seems fine and it should work, but I am hopeful that someone will be able to identify the mistake that I am overlook ...

Having trouble sending an array with res.send() in NodeJS

My User model contains a field that stores an array of course IDs like this: "courseId" : [ "5ac1fe64cfdda22c9c27f264", "5ac207d5794f2910a04cc9fa", "5ac207d5794f2910a04cc9fa" ] Here is how my routes are set up: router.get('/:userid/vendo ...

App for registering for an AngularJS course

Currently, I am developing an application that involves a JSON list containing information about various courses such as title, course ID, location, and type. One of the features in my app includes a modal window that appears when a user clicks on a speci ...

Running npm start in a React development environment on Linux without automatically opening a browser can be achieved by configuring

As I dive into learning React, I've noticed that I keep running npm start in the terminal multiple times. However, it can be quite frustrating how a new browser window opens each time. I'm currently attempting to prevent this from occurring on my ...