What is the best method for choosing a div element using JavaScript and altering its background color?

On my website, I have a pop-up modal with a form that contains 5 divs, each with a picture and description. I came across this JS code on w3schools that allows me to style a selected div. However, when the modal is opened, one of the divs is already pre-selected, which is not what I want. I'm struggling to figure out how to modify the code so that initially no divs are selected.

      // When user clicks an div, add background
      var divs = document.getElementsByClassName("mood-state");
      for (var i = 0; i < divs.length; i++) {
        divs[i].addEventListener("click", function () {
          var current = document.getElementsByClassName("active");
          current[0].className = current[0].className.replace(" active", "");
          this.className += " active";
        });
      }

Below are some of the div elements in the modal:

            <div class="mood-state">
              <img src="neutral.svg" alt="" />
              <p>Neutral</p>
            </div>
            <div class="mood-state">
              <img src="smile.svg" alt="" />
              <p>Pleasant</p>
            </div>
            <div class="mood-state active">
              <img src="grin.svg" alt="" />
              <p>Very Pleasant</p>
            </div

Answer №1

Take out the active class from the HTML. Leaving it there causes it to be active by default.

<div class="mood-state active"> <-- The active class is present here
  <img src="grin.svg" alt="" />
  <p>Very Pleasant</p>
</div>

Change it to

<div class="mood-state"> <-- No 'active' class included here
  <img src="grin.svg" alt="" />
  <p>Very Pleasant</p>
</div>

You'll also have to update your JavaScript code to address a bug

// Whenever user clicks on a div, apply background styling
var divs = document.getElementsByClassName("mood-state");
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener("click", function() {
    [...document.getElementsByClassName("active")].forEach(ele => ele.classList.remove("active"));
    this.classList.add("active");
  });
}

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 trouble extracting data from JSON object with an AJAX request

I have written some code to fetch JSON data from a servlet using an Ajax call. When the success function is executed, I am able to see the response in the console as Object: [{"userId":"dfeterter"}]. However, I am facing difficulty in accessing the value ...

What is the best method for connecting my HTML to jQuery code?

Apologies for my lack of experience in coding, but I will try to keep this brief. To put it simply, when I insert my jQuery code directly into the HTML file below the content, it works perfectly - the element I want to animate 'hides' and then & ...

Issue with uploading files in Internet Explorer using Ajax not resolved

I've been encountering an issue while uploading images using Ajax and PHP. Surprisingly, everything runs smoothly on Firefox but fails to work on Internet Explorer (I.E). Take a look at my HTML code below: <!doctype html> <head> <titl ...

Creating a persistent toolbar in Vuetify: Tips and tricks

Within my Vuetify app, I've implemented a toolbar: <v-toolbar dark color="primary"> <v-toolbar-side-icon @click.stop="drawer.drawer = !drawer.drawer"></v-toolbar-side-icon> <v-toolbar-title>{{drawer.title}}</v-toolb ...

Submit Form using Ajax - Update text in HTML element upon click

As I am working on developing a message system, I encountered an issue where the message content is not opening correctly in my template when clicking the "See" button. My intention is to implement an Ajax call that will replace the content with jQuery .te ...

Utilizing npm/buffer package within a TypeScript module

I'm interested in implementing this NPM package: https://www.npmjs.com/package/buffer I'm unsure about how to convert this line of code into typescript: var Buffer = require('buffer/').Buffer Could you provide me with the correct code ...

New feature: Material UI Chip Input with floating input label

I installed material-ui-chip-input to implement tags in an input field. I wanted a label alongside it, so I utilized the default Material UI label for consistency with other inputs. However, the input doesn't shrink as expected when clicked on by the ...

The function .val() is not a recognized method

hello everyone here is the section of my HTML code: <div class="radio"> <input type="radio" name="certain" id="oui" value="oui"/> <label for="oui"> oui </label> <br /> <input type="radio" name="certain" id=" ...

I am looking to transform CSV data into XLSX file format, upload it to AWS, and obtain the corresponding URL

I am currently in the process of converting a JSON file to CSV. My next step is to convert this CSV file to XLSX data and upload it to AWS to retrieve the link. Convert CSV to XLSX const xlsxFilePath = 'path/to/transaction_data.xlsx'; await csvto ...

Tips for properly aligning numbered lists in text documents

My issue involves designing an order list paragraph where I also need a paragraph in the middle of the ordered list numbers. The first paragraph is displaying correctly, but the second and third paragraphs are only appearing as single lines, so I adjuste ...

Why am I unable to access the array once the loop has finished?

While utilizing the Google Maps API and AngularJS (1.5.8), I encountered an issue where I couldn't access markers that were created in a loop. The code snippet below is located inside the initMap function: var markers = []; for(var i=0; i<10; i++ ...

Changes made to code within the node_modules directory do not appear in the browser

I encountered a bug in the vuejs-datepicker project on Github, prompting me to fork the repository. However, despite making changes to the forked project, these alterations are not reflected in my main project that relies on this dependency. Here's a ...

Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet: .run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $loca ...

Instructions for selecting a checkbox using boolean values

According to the HTML specification, you should use the checked attribute in the <input type="checkbox"> tag to indicate that it is checked. However, I only have a boolean value of either true or false. Unfortunately, I am unable to manipulate the b ...

Applying CSS to inherit styles

I have a group of divs with a similar style, but each one has different padding and margin settings. Here is an example: <div class="mainStyle" id="cc">CC</div> <div class="mainStyle" id="bb">BB</div> <div class="mainStyle" id=" ...

The error message InvalidCharacterError is displayed when the attempt to create a new element using the 'createElement' method on the 'Document' object fails. This is due to the tag name provided ('/static/media/tab1.fab25bc3.png') not being a valid name

Hey everyone! I'm new to using React and I decided to try cloning Netflix by following a tutorial on YouTube. However, I've encountered an issue with rendering an image in a functional component. The error message I'm receiving is as follow ...

Performing an AJAX request to send data containing special characters

What is the best way to send a large string with special characters like '%' and '&' to my PHP page using AJAX POST? In simple terms, how can I encode these characters in JavaScript and then decode them in PHP? ...

Create a Boostrap navbar with a form and links aligned to the right using the navbar

I'm trying to use navbar-right on a navbar-form and a navbar-nav, but the form ends up on one row and the nav links on another row on the right. How can I make the navbar display the brand on the left and have a search field followed by nav links on t ...

Perform a jQuery function and SQL query when a selection is made in a dropdown menu

Struggling to execute a SQL query on drop-down menu selection. Here's my current code: <script> $('#templateid').change(function(DoUpdateOnSelect) { $.post('page.edit.php?page_id=(-->Need help in retrieving this id from the pa ...

Uncertainty surrounds the interaction of computed height and margins with CSS float right

What is the reason behind this HTML code: <html> <head> <style type="text/css"> .left { background-color: yellow; } .right { float: right; background-color: lightgray; width: 150px; } </sty ...