"Modifying the content:url() with JavaScript: A step-by-step guide

Hello, I am currently working on creating a traffic light using an array of images. My goal is to change the image path specified in the CSS when a button is clicked, to change the appearance of the traffic light. In this case, the 'content.url()' line in each class needs to be modified when the function is triggered by the button click. The approach I am using right now may not be correct, but it is a starting point for understanding the concept.


<style>
#rect{
    height:550px;
    width:180px;
    border:1px solid #000;
}
.black1 {
  position: relative;
  top: 10px;
  left: 10px;
  content.url('black.png')
}
.black2 {
  position: relative;
  top: 20px;
  left: 10px;
  content.url('black.png')
}
.black3 {
  position: relative;
  top: 30px;
  left: 10px;
  content.url('black.png')
}
</style>

<Body>
<div id="rect">
<img class="black1" />
<img class="black2" />
<img class="black3" />
</div>

<script>
var x = ["black.png", "red.png", "orange.png",'green.png'];
var i = -1;
function change(){
    i++;
    if (i == 0){
    document.getElementByClass('black1').src=x[1];
    document.getElementByClass('black2').src=x[0];
    document.getElementByClass('black3').src=x[0];
    }

}
</script>
<button onclick = "change()">Change light</button>
</div>
</Body>
</html>

Answer №1

If you organize your css classes into red, orange/yellow, and green categories, you can utilize the classList function more effectively. Below is a basic working example for you to enhance and modify according to your needs.

let i = -1;

function change() {
  const tl = document.querySelectorAll('.light');  
  i++;    
  
  if (i == 0) {
    tl[0].classList.add('red')
  }
  if (i == 1) {
    tl[1].classList.add('yellow')
  }
  if (i == 2) {
    tl[2].classList.add('green')
  }  
  if (i == 3) {
    tl[2].classList.remove('green');
    tl[1].classList.remove('yellow');
    tl[0].classList.remove('red');
    i = -1;
  }
}
#rect{
    height:350px;
    width:120px;
    border:1px solid #000;  
}
img {
  height: 100px;
}

.light {
  position: relative;
  top: 10px;
  left: 10px;
  content: url(https://via.placeholder.com/150/000000);  
}

.red {
  content: url(https://via.placeholder.com/150/FF0000);  
}

.yellow {
  content: url(https://via.placeholder.com/150/FFFF00);
}

.green {
  content: url(https://via.placeholder.com/150/008000);  
}
<Body>
  
<div id="rect">
<img class="light" />
<img class="light" />
<img class="light" />
</div>

<script>

</script>
<button onclick = "change()">Change light</button>
</div>
</Body>
</html>

Answer №2

If you want to ensure your program functions correctly, consider implementing the following changes:

  1. Remove content.url('black.png') from the CSS
  2. Assign default URLs to your img tags, such as "black.png"
  3. Refine your code as follows:
const urls = ["black.png", "red.png", "orange.png", 'green.png'];
let index = -1;
const imgs = ["black1", "black1", "black1"].map(className => document.getElementByClass(className));

function change(){
  index++;
  const currentLight = index % 3;
  imgs.forEach((image, i) => {
    if (i === currentLight) {
      image.src = urls[currentLight + 1];
    }
    else {
      image.src = urls[0];
    }
  });
}

change(); // Ensure the red light is initially on. If this function is not called, all lights will be off

I trust this aligns with the functionality you desired for your program.

However, it is worth noting that I mentioned the need to eliminate the use of content: url, whereas your query involves modifying it. Essentially, JavaScript cannot directly alter classes (unless you generate them dynamically with JS, though this approach is not recommended). If you insist on utilizing content: url (although it may not be advisable), you must create three classes - .red, .orange, and .green - each with their respective URLs. You can then toggle these classes using JS, similar to how you would toggle src attributes.

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 incorporating async/await within a promise

I am looking to incorporate async/await within the promise.allSettled function in order to convert currency by fetching data from an API or database where the currency rates are stored. Specifically, I want to use await as shown here, but I am unsure abou ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

Display the size of the data array in VueJS once the data has been retrieved from the API

Using Vue JS, I have been attempting to retrieve data from an API. My goal is to determine the length of the array and then log it to the console using a method. However, every time I try to do this, the value logged is always "0" instead of the actual le ...

Creating a dynamic state management system for multiple Collapse components can be achieved by utilizing

I am trying to create a Collapse menu from array data, Currently, when I click on any menu all sub menus expand I believe my issue lies in not being able to set a unique "open" state for each Main menu I want to avoid assigning a "state" to accommodate ...

Tips for transferring custom data on a form without relying on input fields are an effective way

Is there a way to submit a form with both name and quantity without having an input field for the second variable? I want the quantity get variable to be passed when the form is submitted, but I also need to pass the name quantity that is already displayed ...

There seems to be a glitch with the Flask flash messaging feature, as

My Flask application includes login and register routes where I aim to display flash messages when username passwords are not matched. Specifically, this issue arises in my index and login routes: @app.route('/') @login_required def index(): ...

When utilizing the getIntersectionList function, IE 9 may experience a malfunction and cease functioning

I am currently working with SVG code and JavaScript, trying to achieve a specific intersection result. <svg id="svgSurface" width="500" height="500"> <defs> <marker id="Triangle" viewBox="0 0 20 20" refX="0" refY="0" markerUnits ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

Resolving the Smooth Scrolling Problem

Here is a simplified version of what I am currently working on: Although I have managed to get the scrolling functionality to work, there seems to be an issue with transitioning from one section to another. For example, when clicking on NUMBER 3, it s ...

Converting Excel values to Exponential format using Python

I'm struggling to find a solution for extracting the Invoice Number in Python from an Excel sheet without turning it into exponential form. Expected Value: 8000030910 Result: 8.00002e+09 Python Result Excel sheet d1.append(sheet.cell_value(j,0)) ...

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

A guide on calling a function from a different component in vuejs2

I am facing a situation where I need to trigger an event whenever my sidebar opens. This event should be called every time the sidebar is opened. For example, when I click on an element, it triggers the opening of my sidebar which then calls a function th ...

Implement a scrolling feature to the tooltip when using "data-toggle"

I'm struggling with a piece of code that showcases a tooltip when the user hovers over the question circle icon. The tooltip's content can't exceed 1000 characters, but I need to figure out how to make the overflow scroll by adjusting the to ...

Drop-down functionality in Bootstrap Form becomes unresponsive after screen width is decreased

I recently encountered a strange issue with my simple Bootstrap form. When I resize my browser width to mobile size or view it on a mobile device, the form stops functioning properly. Unfortunately, I am unable to provide any specific code examples at this ...

Is it possible to retrieve several columns using the pluck method in Underscore.js following the input from the where method, similar to LINQ

var persons = [ {name : "Alice", location : "paris", amount : 5}, {name : "Bob", location : "tokyo", amount : 3}, {name : "Eve", location : "london", amount : 10} ]; var filteredResults=_.pluck(_.where(persons, {location : "paris"}), 'nam ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

Steps for Adding an H1 Tag Using GWT

Forgive me for what may be a silly question, but I'm truly struggling to understand how to dynamically add an HTML heading tag to my page using the Google Web Toolkit. My motivation is not related to styling purposes, as any label can be styled. Inst ...

Looking for a straightforward way to incorporate a "Read more" and "Show Less" functionality into a Wordpress site using Javascript?

As a last resort, I am seeking a quick and simple fix. I have been experimenting with Javascript to implement a 'Read more...' & '... Read Less' feature on six different sections of a single page. The goal is to display only the fi ...

The versions of my npm and node are not compatible, despite using nvm

I have recently started working with node and npm. I need to run a program repository for my job, which requires compatibility with node version 10.13.0 or even 8.11. I attempted to install nvm, but now every time I try to execute any npm command (includ ...