Tips for updating the color of multiple div elements using the onclick event

Imagine I have 3 different spans on a page that, when clicked, reveal something. Now, I want to change the color of the selected div.

<div class="step_wrapper">
   <div id="step_box1"> <span>Content for page 1</span>
   </div>
   <div id="step_box2"> <span>Content for page 2</span>
   </div>
   <div id="step_box2"> <span>Content for page 3</span>
   </div>
</div>

I attempted to achieve this by:

 $("#step_box1").toggle(function() {
   $(this).css("background-color", "red");
     }, 
     function() {
   $(this).css("background-color", "");
  });

 For the second div:

$("#step_box2").toggle(function() {
   $(this).css("background-color", "red");
     }, 
     function() {
   $(this).css("background-color", "");
  });

And for the third one:

 $("#step_box3").toggle(function() {
   $(this).css("background-color", "red");
     }, 
     function() {
   $(this).css("background-color", "");
  });

However, what I actually need is to only select one at a time and have the selected one change color while the others revert back to normal.

Answer №1

Before changing one to "red", ensure all are at the default color as shown here:

$('.content_box>div').css("background-color", "")
$(this).css("background-color", "red")

Answer №2

To begin with, considering the signature of the toggle() method being used, it seems that an outdated version of jQuery (< 1.9) has been included as this pattern is now deprecated. It is advisable to update jQuery to a more recent version for your project.

Furthermore, you can achieve the desired outcome by implementing a shared event handler on all div elements, similar to the example below:

<div class="step_wrapper">
    <div id="step_box1">
        <span>Content of page 1</span>
    </div>
    <div id="step_box2">
        <span>Content of page 2</span>
    </div>
    <div id="step_box3">
        <span>Content of page 3</span>
    </div>
</div>
$(".step_wrapper div").click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

Refer to this fiddle for a working example

It is worth noting the use of addClass()/removeClass(); it is considered good practice to place styles in an external stylesheet and modify the class names of elements rather than directly altering their inline styles.

Answer №3

To achieve the desired effect, simply modify the background-color of the chosen step_box, and set all others to have transparent backgrounds:

<div class="step_wrapper">
   <div id="step_box1"> <span>Content of page 1</span>
   </div>
   <div id="step_box2"> <span>Content of page 2</span>
   </div>
   <div id="step_box2"> <span>Content of page 3</span>
   </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$('.step_wrapper > div').click(function() {
$this = $(this);
  
  $this.css('background-color', 'blue');
  $this.siblings().css('background-color', 'transparent');
})  
</script>

Answer №4

<head>
    <title>Sample Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

    <style>
        .red {
        background-color:red;
        }

    </style>
<script>

    $(document).ready(function () {

        $('.step_wrapper div').click(function () {
            $('.step_wrapper div.red').removeClass('red')
            $(this).addClass('red');
        });


    });


</script>
</head>
<body>
   <div class="step_wrapper">
   <div id="step_box1"> <span>Content of page 1</span>
   </div>
   <div id="step_box2"> <span>Content of page 2</span>
   </div>
   <div id="Div1"> <span>Content of page 3</span>
   </div>
</div>

</body>
</html>

Answer №5

Easy CSS Trick

All it takes is a few lines of CSS to achieve this effect. Remember to include the tabindex attribute in each DIV so that they can be focused on. No need for any javascript or external libraries with this solution.

Give it a try by running the snippet below and clicking on the lines of text to see the magic happen.

div:not(:focus) { background-color: none; color: black;}
div:focus { background-color: red; color: white;}
<div>
   <div tabindex=1> <span>Content of page 1</span></div>
   <div tabindex=2> <span>Content of page 2</span></div>
   <div tabindex=3> <span>Content of page 3</span></div>
</div>

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

Jquery's Ajax Promise fails to execute

I'm developing an app and encountering difficulties with firing a promise. I simplified the code to a basic example that is still not functioning, utilizing EasyPHP... ajaxDialog = function( target ) { // Promise to indicate completion return ...

Changing the close button icon in highslide popups

Utilizing highslide together with highcharts, I need to customize the functionality of the close button. Specifically, I want to trigger an additional function when a user clicks on the "X" button. Upon inspecting the "X" button, this is what appears in m ...

Unresolved Issue: jQuery AJAX Fails to Load PHP File in Internet Explorer

I have a piece of code that runs lastactivity.php every 10000 milliseconds on FireFox, Chrome, and Opera for Windows & Linux. However, it does not seem to work on Internet Explorer (tested on IE Version 11). There are no error messages displayed by the b ...

JavaScript - When converting a string to a number, it may result in adding extra 0s at

Recently, I've been struggling to convert a string in this format into a number: "20150910095820526" Despite trying different methods like unary operators, parseInt, and parseFloat, the outcome is always off, ending up like this: 1017219000 I&apos ...

Adjust the component's onClick property in Next.js

Looking for guidance on how to update a property value of a component in Next.js. I have been using the Material-UI library for styling. Encountering an issue when attempting to modify the 'open' property of a drawer component, as it constantly ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Updating an image source using JQuery when a button is clicked

One interesting feature I have implemented is a Jquery dialog that opens up when a link is clicked. Upon clicking the link, AJAX is used to populate the dialog with data. One specific requirement I have is to include an image in the dialog based on the ID ...

Newest preact and typescript packages causing issues with type validation

Despite my efforts to integrate preact with TypeScript, I have encountered a problem where incorrect types can be passed without any error being raised. I am in the process of transitioning our codebase from plain JavaScript to preact with type scripting. ...

Enhanced Bootstrap 4 button featuring custom design with text and image aligned on the right side, optimized for flexbox layout

I am looking to design a button-like div that features a flag image alongside the abbreviation of a country. Although I have some code in mind, it doesn't follow Bootstrap's guidelines and I am struggling to adapt it accordingly. <div cla ...

Using jQuery to create dynamic tabbed interfaces

I am using a menu tab in jQuery, but I have one specific tab that needs to be loaded only when the user accesses it. Currently, the jQuery tab is functioning normally. However, this particular tab that I mentioned earlier has a significant impact on the p ...

Images on the login page are not being displayed due to CSS urls not functioning properly

Struggling with an issue and in need of some quick assistance. I have an ASP.NET application that utilizes Forms authentication. On the Login.aspx page, I have implemented multiple background images for visual appeal. These image URLs are set using CSS st ...

The accuracy of dates in javascript may be unreliable

Currently, I am working on creating a calendar using React JS. Below is the code that generates the entire month: function generateWholeMonth(currentDate) { var result = []; var focusDate = new Date(currentDate); focusDate = new Date(focusDate. ...

Refreshing issue: Model change in child page not updating view correctly (Ionic & Angular)

I am currently working with Ionic 3.20 and Angular 5.2.9, encountering an issue with content refreshing after a model change. Despite being new to this, I sense that I might be overlooking something fundamental. Within my view, I have the following elemen ...

Obtaining precise information through clicks using Ionic and Firebase

Currently, I am diving into learning the Ionic framework and Firebase using AngularFire. My current project involves creating a contacts application with multiple user accounts, where each user's contacts are displayed in a list. When a contact is cli ...

Issue with NodeJS Express's reverse proxy due to an invalid TLS certificate alternative name

I have configured a reverse proxy on my endpoint as shown below: var express = require('express'); var app = express(); var httpProxy = require('http-proxy'); var apiProxy = httpProxy.createProxyServer(); var serverOne = 'https://i ...

I'm absolutely obsessed with it: Error - unable to switch to an abstract state

Hey there! Currently, I'm working on an app using the IONIC Framework and running into some issues with user validation errors. Below, you'll find a snippet of the logic I've implemented: app.js: angular.module('skulApp', [' ...

Update all field values in Redux-form version 6.0 and above

I am attempting to update several values in redux-form. They are stored in a single object, and I want to replace the current redux-form state values with those from my object. One method I have tried involves using this.props.reset() followed by multipl ...

Is the output of MongoDB's ISODate() function always distinct from that of the Date()

After reviewing the documentation, my understanding was that ISODate simply wrapped the Date constructor. However, I've encountered issues when working with dates very far in the past. For example: new Date(-8640000000000000); ...

Adjusting the alignment of Bootstrap navbar items upon clicking the toggle button

When I click the toggle button on a small screen, my navbar items appear below the search bar instead of aligning with the home and about elements. Below is an image depicting this issue: https://i.stack.imgur.com/4rabW.png Below is the HTML code structu ...

Is it possible to identify iOS Safari exclusively without including iOS Chrome, Firefox, and other browsers in the filter?

For those familiar with working on iOS web applications, it's known that Apple's policy causes Chrome and other mobile browsers on iOS to use an outdated javascript engine. Because of this, we need to disable certain rendering for Chrome and othe ...