How can you use HTML, CSS, and JavaScript to group objects with one color and then change the color of one specific object?

I have a set of 6 labels that act as buttons. When one is clicked, it changes from white to blue. If another label is clicked, the previously blue label turns white and the newly clicked one turns blue.

Currently, the code below sets all labels to white but doesn't seem to change the background color of the newly clicked label to blue. However, if I comment out the line:

document.getElementsByTagName('label').style.backgroundColor = '#fff';

Then each clicked label turns blue, but remains blue when a new label is clicked. So what I'm trying to figure out is how to set the background color of all labels to white and then only turn the background of the most recently clicked label to blue.

The desired outcome is for only the most recently clicked label to have a blue background while the others remain white.

Thank you in advance

<script type="text/javascript">
    function toggle(label) {
        document.getElementById('one').style.display = 'block';
        
        var labels = document.getElementsByTagName('label');
        for (var i = 0; i < labels.length; i++) {
            labels[i].style.backgroundColor = '#fff';
        }
        
        document.getElementById(label).style.color = 'rgb(54, 95, 145)';
        document.getElementById(label).style.backgroundColor = 'rgb(193,203,225)';
    }

</script>

<label id='Label6' class='button' onmousedown = 'toggle("Label6")'>Personal Details</label>
<label id='Label1' class='button' onmousedown = 'toggle("Label1")'>Education</label>
<label id='Label2' class='button' onmousedown = 'toggle("Label2")'>Achievements</label>
<label id='Label3' class='button' onmousedown = 'toggle("Label3")'>Work Experience  </label>
<label id='Label5' class='button' onmousedown = 'toggle("Label5")'>IT Skills</label>
<label id='Label4' class='button' onmousedown = 'toggle("Label4")'>Languages</label>

Answer №1

The highlighted line you pointed out is actually incorrect. When you make this call:

document.getElementsByTagName('label');

You receive an array of elements, which does not contain the property style. To resolve this, you must iterate through the results like so:

var labels = document.getElementsByTagName('label');
for (var j=0; j<labels.length; j++) {
    labels[j].style.backgroundColor = '#fff';
}

Another option would be to use jQuery as recommended by Mahesh.

Answer №2

Using Jquery in this situation is highly beneficial. I strongly suggest incorporating it into your project

An example of how you could utilize it is shown below:

$("button").on('click', function() {
    $("button[id^=button]").css('background-color', 'white');
    $(this).css('background-color', 'blue');
});

Note: Please note that I have not yet tested the provided code

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

Using Jquery for a synchronous "Ajax" request doesn't seem to be functioning

As a newcomer to javascript, I am currently in the process of developing a react/flux app and utilizing jquery for synchronous "ajax" calls (sjax?) to the backend. However, I am encountering inconsistent behavior which seems to be caused by my ajax call no ...

setting a variable with data retrieved from an AJAX call using jQuery

Here's a snippet of jquery code that I'm working with: var example = "example"; $.ajax({ url: root + "/servletPath", type: "GET", success: function (response) { alert(response); // displays the correct value example ...

The PHP script is malfunctioning, specifically due to a condition within a loop

Can anyone provide some assistance? I'm trying to work on a coding task but seem to be stuck. A helpful hint pointing out where I've gone wrong would be greatly appreciated. The task at hand is quite challenging. Currently, I am attempting to ha ...

Presenting a data table in Angular

I'm new to using Angular and need help creating a table to organize my data, which is being fetched from a JSON file on the server. Here's the content of data.component.html: <div class="container"> <h1>Search history</h1> ...

Regular expressions or regex can be used to match the initial letter or letters of various words

Struggling with regex? After searching for an hour, the best solution found was this one. Still unable to crack it though... Here's what I need: Have a JS array that needs to be filtered. The array looks like: [ 'Gurken halbiert 2kg', &a ...

In Internet Explorer 8, angular's $window service may sometimes return undefined

I've developed a custom directive called slideshow with some scope variables that are two-way bound to ng-style. This directive functions as a responsive carousel that adjusts based on the window height retrieved using the $window service. During tes ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Adding a class to unhovered elements with jQuery/JS: a step-by-step guide

I have a variety of elements that are almost working how I want them to. There are four divs in total. Depending on the URL visited, I want a specific div to be fully transparent/active. The next div in line should animate in and out of transparency simul ...

Utilizing the ng-required directive with the model's value in AngularJS

I need to validate a form field for both null and its value. Can anyone suggest how I can achieve this without writing a function on the controller? <form name="frm"> <input type="text" ng-model="myModel" ng-required="myModel != '' || m ...

Delete the class when the user clicks anywhere on the page

I have 2 buttons that will toggle/remove a class when the user clicks on them. $('.social-toggle').on('click', function() { $('.social-networks').not($(this).next()).removeClass('open-menu') $(this).next().toggl ...

Enhancing User Experience in AngularJS UI-Router by Updating State without Refreshing the Template

I have noticed that every time I navigate to a different state, my templates and controllers are refreshing. This is not the behavior I want; I would like to retain the values entered into a form on contact.html when switching to home.html. Currently, I a ...

Automatically updating CSS file in progress

Is there a way to have CSS changes automatically update on my template without requiring me to manually refresh the page? I've noticed this question being asked multiple times, but none of the solutions provided seem to work for me. I attempted usin ...

Tips for triggering useEffect just once when various dependencies are updated simultaneously

Currently, I have implemented a useEffect hook with two dependencies in the following way: useEffect(() => { ..... }, [apiData, currentMeasurements]); It's important to note that the apiData is fetched using useLazyQuery from apollo/client. Upon ...

Different Ways to Make Custom Checkboxes Overlap with Labels in CSS

Hello everyone, I am currently diving into the world of CSS and HTML. My goal right now is to create a custom checkbox with a list of options. During my research, I stumbled upon an example on how to create custom checkboxes at this link. However, when imp ...

Utilize HTML/CSS for text that changes automatically

Is it possible to dynamically change text using HTML and CSS based on the page being viewed? For example, when on the home page, the text would automatically display "Home Page" without needing manual changes on each page. I want this process to be seamles ...

React Native Issue: The mysterious disappearance of the 'navigation.push' object

I am trying to navigate to List.js after clicking a button in the MainMenu.js file, but I keep encountering this error: TypeError: undefined is not an object (evaluating 'navigation.push') This snippet is from my App.js file import { StatusBar ...

Transitioning from a multipage application to Piral: A comprehensive guide

Our organization operates several ASP.NET Core applications that are traditional multipage applications. As we develop a new portal using Piral, we want to incorporate elements from our existing applications while also introducing new modules. How can we ...

Utilizing AJAX and PHP for dynamic changes based on listbox selection

Is there a way to make the query run whenever a selection is made from the listbox? if(isset($_POST['select'])){ $newselection=$_POST['select']; $query = "SELECT count(*) FROM listings where description=" . $newselection. ""; $r ...

Tips for formatting numerical output in EJS by rounding the value

I am displaying a value in EJS and I am looking to format it to show fewer decimal places. This is related to the EJS engine on the frontend. Value displayed: 4.333333333333333 I want it to be displayed like this: 4.3 The EJS code snippet used: <p cl ...