Using JavaScript to set a constant variable for dynamically changing the background image URL

I am trying to implement a feature where clicking a button will change the background of my HTML file, and then revert back to the original background when clicked again.

To achieve this, I have set up a map containing key/value pairs. The first pair consists of the original background as the key and the new background as the value, while the second pair reverses this relationship.

Here is the code snippet:

const nextBackgroundImageUrl = {
    "url('../images/pexels_bg.jpeg')" : url('/images/bbyshrk.jpg'),
    "url('../images/bbyshrk.jpg')" : url('/images/pexels_bg.jpeg')
}

function changeImg() {
    const currentBackgroundUrl = elem.style['background-url'];
    elem.style['background-url'] = nextBackgroundImageUrl[currentBackgroundUrl];
}

While it seems like this should work, I encounter an error in the console:

index.html:197 Uncaught ReferenceError: url is not defined

This error specifically points to the value of the second key/value pair, `url('/images/pexels_bg.jpeg')`.

The file mentioned definitely exists. Could it be that URL cannot be used as a value for a key, or is there something else I am overlooking?

Any guidance or advice on this issue would be greatly appreciated. Thank you.

Answer №1

Make the value of the URL variable a string instead of considering it as a variable

const nextBackgroundImageUrl = {
  "url('../images/pexels_bg.jpeg')": "url('/images/bbyshrk.jpg')",
  "url('../images/bbyshrk.jpg')": "url('/images/pexels_bg.jpeg')"
}

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

Tips for removing the default hover and click effects from a Material-UI CardActionArea

Check out the card sample with a lizard photo on https://material-ui.com/components/cards. When you hover over the cardActionArea, it will get darker or lighter based on the theme. Clicking on the card will make the picture change its brightness relative ...

Using React to easily rearrange images by dragging and dropping them

Currently, I am working on incorporating drag-and-drop functionality using React JS along with the react-dropzone library to display thumbnails. The code implementation is provided below: import React from "react"; import ReactDOM from "react-dom"; impor ...

Changing Location of Carousel in Bootstrap

Recently, I have been working with Bootstrap and have encountered a problem with the carousel. I have placed carousel images below my navbar, but there seems to be a gap between the navbar and the carousel image. I want the image to be right below the navb ...

The excessive number of hidden newline elements in tables created with TinyMCE causes formatting issues

After successfully saving a table created inside TinyMCE to the database, I encountered an issue when trying to fetch the content using PHP. The retrieved data had an excessive amount of <br> tags appearing before the table. Although removing the nl2 ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

Styling not being applied in Angular directive

Seeking assistance with styling AngularJS directives, specifically a Bootstrap directive for progress bars within my project. Utilizing it within a custom div class. <div class="diagnostics-widget-modal"> <div class="modal-header"> ...

Using a try catch within a try catch block along with the Mongoose library and Express

Looking for the most efficient solution here. Can I achieve the desired outcome with just one try catch block, or do I need to nest try catch within try catch? I'm currently working with express and mongoose for mongodb. try { const savedR ...

Python code using Beautiful Soup to crawl web pages and extract JSON data

Currently exploring the world of beautifulsoup in Python and attempting to extract specific details from a website, particularly the deeplink and title. Utilizing beautifulsoup to gather json data has produced a variable named `soup` of type beautifulsoup ...

Creating a border around a clipped box using CSS

I have a uniquely shaped box with a diagonal line at the end. I want to add a border around it, but the border also follows the shape of the box. Is there a way to apply a border to the clipped area using only CSS and HTML? So that the white part has a bl ...

Tips for deleting all content below a specific key in a JSON object

My JSON data (located within req.body) is structured like this: {body : { Cust : {...} }, { Input : {...} }, { Reciept : {image: [Array] } } } I am trying to remove the entire Reciept key so that the updated JSON looks like this... {body : ...

Steps for generating tab panels and their respective content using a v-for loop

I am currently utilizing Vue 3 in combination with Bootstrap 5. My objective is to incorporate multiple Tabpanels within a v-for. Each of these Tabs should feature distinct content. To achieve this, I attempted placing my Tabs and their respective Conten ...

Unused expressions in React should not be allowed

Just dipping my toes into React and giving this code a test drive var animateButton = function(e) { e.preventDefault; //reset animation e.target.classList.remove('animate'); e.target.classList.add ...

Mobile browser not resizing window width in fluid layout on WordPress site

Currently, I am working on developing a basic web layout that can adapt to mobile view. I have made some progress which you can check out here. The layout successfully adjusts when the window is resized in Firefox or Chrome. However, when I tried to acce ...

Manipulating images separately using the canvas

Currently, I am utilizing an HTML5 canvas to generate a collection of trees alongside their corresponding shadows. My objective is to ensure that each shadow corresponds with the position of a designated light source. While I have successfully drawn each t ...

The request returned a 404 (Not Found) error message when trying to navigate using AngularJS

Currently, I am working on building a straightforward application using Ionic and Angular. To test my progress locally, I have set up a simple server by running Ionics ionic serve command. Below is the snippet of my playlist.html code, where I intend to s ...

Add a sound file to the server and configure the images based on the server's response

I am a newcomer to JavaScript and AJAX, and I am facing an issue while trying to upload an audio file to the server and display the image from the server response. When attempting to pass the audio file from the input tag to an AJAX call, I encounter an il ...

establish headers when sending form data

When making an ajax call for form submission, it is possible to set headers before sending the request to the server. But what if you are using a specific action "URL" to send data to the server? How can you set any header for that request? Case 1: <f ...

Modifying the value of a local variable results in a corresponding adjustment to the original global variable's value

Within my Node.js program, I have set up an array named "list" in the routes section. This array is populated with values from a function defined in the model. The code for this route looks like: var express = require('express'); var router = ex ...

Extending a Typescript class from another file

I have a total of three classes spread across three separate .ts files - ClassA, ClassB, and ClassC. Firstly, in the initial file (file a.ts), I have: //file a.ts class ClassA { } The second file contains: //file b.ts export class ClassB extends Class ...

Utilize the Feefo JSON data and convert it to a JavaScript array for rendering as an HTML

Currently diving into the world of Javascript and JSON, but feeling a bit overwhelmed by it all. Attempting to pull data from a JSON array, I've managed to reach this stage $(function(){ var $reviews = $('#reviews'); $.ajax({ ...