Steps to Implement CSS Background Change on Click Event

Take a look at this JSFiddle link. In the code, you will find two divs called step-wrapper, each containing three divs named step-box. When you click on a step-box, its background color changes to yellow.

I have included a reset button. What I want is for the last clicked step-box div to change back to white when the reset button is clicked. However, in the current code, clicking the reset button changes all the step-box background colors to white.

Answer №1

Here is the solution you are seeking: https://jsfiddle.net/richardgirges/8m9qstg3/11/

We are storing a reference to the lastClicked div and specifically targeting it when reset is triggered. Here's how:

var $lastClicked = null;

$('.step_wrapper').on('click','.step_box',function () {
    $(this).parent().find('.step_box').css('background-color', '');
    $(this).css('background-color', '#fff000');
    $lastClicked = $(this);
});


$('.reset').on('click',function(){
    if ( $lastClicked ) {
        $lastClicked.css( 'background-color', '#fff' );
        $lastClicked = null;
    }
});

UPDATE: The code has been optimized. Used explicit var declaration for better scoping.

Answer №2

Consider this alternative approach: instead of having a single reset button at the end that resets all wrappers, why not place a reset button inside each wrapper div to individually reset that specific wrapper when clicked? Give it a try and let me know your thoughts.

Here's the updated HTML structure:

<div class="step_wrapper">
<div class="step_box" onclick="show('Page1');"> <span>Content of page 1</span>

    </p>
</div>
<div class="step_box" onclick="show('Page2');"> <span>Content of page 2</span>

    </p>
</div>
<div class="step_box" onclick="show('Page3');"> <span>Content of page 3</span>

    </p>
</div>
<div class="reset"> Reset </div>
</div>
<br>
<br>Second Wrapper
    <br>
        <br>
 <div class="step_wrapper">
 <div class="step_box" onclick="show('Page1');"> <span>Content of page 1</span>

    </p>
</div>
<div class="step_box" onclick="show('Page2');"> <span>Content of page 2</span>

    </p>
</div>
<div class="step_box" onclick="show('Page3');"> <span>Content of page 3</span>

    </p>
</div>
<div class="reset"> Reset </div>
</div>

And the corresponding Javascript functionality:

$('.step_wrapper').on('click','.step_box',function () {
$(this).parent().find('.step_box').css('background-color', '');
$(this).css('background-color', '#eeffaa');
});


$('.reset').on('click',function(){
$( this ).parent().find(".step_box").css( 'background-color', '' );
});

Answer №3

Clicking on a step box will add the class "last" to it and remove it from the previously clicked element.

$('.step_wrapper').on('click','.step_box',function () {
    $(this).parent().find('.step_box').css('background-color', '');
    $(this).css('background-color', '#fff000');
    $('.last').removeClass('last');
    $(this).addClass('last');
});


$('.reset').on('click',function(){
    $( ".step_box.last" ).css( 'background-color', '' );
});

http://jsfiddle.net/8m9qstg3/7/

Answer №4

Take a look at this interactive demo

In my solution, I added an ID attribute to the step_box class and utilized this ID to set a hidden field value when a step_box is clicked. Then, in the reset onClick function, I retrieved the ID from the hidden field and reset the background color based on that ID.

Here's the updated code:

JavaScript

$('.step_wrapper').on('click','.step_box',function () {
    $(this).parent().find('.step_box').css('background-color', '');
    $(this).css('background-color', '#fff000');
    document.getElementById('test').value=this.id;
});


$('.reset').on('click',function(){
    var a= document.getElementById('test').value;
    $( "#" + a ).css( 'background-color', '' );

});

HTML

<div class="step_wrapper">
    <div class="step_box" onclick="show('Page1');" id="1"> <span>Content of page 1</span>

        </p>
    </div>
    <div class="step_box" onclick="show('Page2');" id="2"> <span>Content of page 2</span>

        </p>
    </div>
    <div class="step_box" onclick="show('Page3');" id="3"> <span>Content of page 3</span>

        </p>
    </div>
</div>
<br>
<br>Second Wrapper
<br>
<br>
<div class="step_wrapper">
    <div class="step_box" onclick="show('Page1');" id="4"> <span>Content of page 1</span>

        </p>
    </div>
    <div class="step_box" onclick="show('Page2');" id="5"> <span>Content of page 2</span>

        </p>
    </div>
    <div class="step_box" onclick="show('Page3');" id="6"> <span>Content of page 3</span>

        </p>
    </div>
</div>
<input type="hidden" id="test" />
<div class="reset">Reset</div>

Answer №5

http://jsfiddle.net/8m9qstg3/6/

In my solution, I have utilized a variable called 'last' to store the clicked object. This ensures that when the reset button is clicked, it will refer back to the last element that was clicked. For handling multiple elements, an array can be used along with the ".push()" method to keep track of all previously selected elements. However, for your specific query, this approach should suffice.

var last;

$('.step_wrapper').on('click','.step_box',function () {
$(this).parent().find('.step_box').css('background-color', '');
$(this).css('background-color', '#fff000');
last = this;
});


$('.reset').on('click',function(){
$(last).css("background-color", "white");
});`

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

How can I implement a redirect function for Carousel image clicks in a React project?

I am working on a React project that includes Carousel from the 'react-responsive-carousel' npm package. I am looking to implement a functionality where clicking on the images in the Carousel will redirect to another component. How can this be ac ...

Encountering a 500 Internal Server Error while attempting to redirect to the callback URL during the use of Google OAuth2 with Passportjs

The application's credentials check out. However, when the redirected URL retrieves the profile object, it returns a 500 Internal Server Error. As a result, any code within the get callback route is not functioning correctly. Any assistance on this ma ...

How can I change the nested Material UI component style from its parent component?

I am currently incorporating a component from an external library into my project. However, I am facing limitations in customizing its style, especially when it comes to a button that is using material ui styles. Upon inspecting the element, I can see that ...

Identifying the similarities between strings and array elements in JavaScript

I am facing an issue where I have a list of values stored in a comma-separated string and I need to compare them against an array to see if any match. The goal is to return true or false, but I keep getting an undefined error. const reqRights = ["189002 ...

Displaying divs depending on dropdown selection - Troubleshooting script issue

When I try to display certain divs based on dropdown selection using the script below, it works fine on a simple page. However, when I implement it on my current development page, it completely messes up the layout, turning everything black and adding stra ...

Analyzing JSON parsing efficiency

I am currently working on a client application using jquery and html5 For my project, I have a data file that is 70 MB in size The file named data.json contains the following: var myData = [ { "id":"000000001", "title":"title1", "c ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

Converting PHP arrays into JavaScript arrays with the help of json_encode()

Is there a way to pass an array from PHP to the JavaScript function console.log()? I'm currently simulating a database and need help with this specific task. Despite not having an array declared in my code, I attempted to use the .getJSON() function w ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

What steps should I take to transition from a table-based layout to a more semantic HTML structure with a CSS-based layout?

Looking at the image presented, a significant portion of the HTML code has been structured semantically, with CSS being utilized for overall aesthetics. However, despite concerted efforts, resorting to a table was necessary to ensure that the segment on th ...

What is the answer to this issue where the entity name is required to directly come after the "&" in the entity reference?

Whenever I insert the code into my Blogger platform, an error pops up stating: The entity name must directly follow the '&' in the entity reference Here is the code: <script> if (typeof bc_blocks == "undefined" && wind ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

The ViewChild instance is currently undefined

Within my component, I have the following setup: @ViewChild('PaginatedTableComponent') userTable: PaginatedTableComponent; Here is the corresponding HTML code inside the component: <pag-paginated-table #userTable [(shouldUpdate)]="sh ...

Button hover in Chrome causing problems with Leaflet map

Since yesterday, I have been experiencing issues with the buttons on my page. chrome : Version 61.0.3163.100 (Build officiel) (64 bits) I do not encounter any problems with Firefox. The problem arises when I select text on my overlay; the overlay beco ...

The intersection of JavaScript, node.js, and cybersecurity

I recently set up a user registration form on my website where the data (username, password, email) is currently being sent to the server in plain text using socket.io. I am aware that this method is not secure at all. Can anyone recommend a better solut ...

Adding a margin space to the right of the header using Bootstrap

As I embark on creating my very first Bootstrap website, I have encountered what seems like a simple issue that is causing me quite the headache. There appears to be an unexplained 20px margin on the right-hand side of the page, persisting across all brows ...

What is the method for applying reduce to an array of objects in order to calculate the total value based on a specific property within each object?

I'm attempting to calculate the total population of males and females for each county. For example, if "Bomi" has both male and female populations, they should be combined. However, I'm struggling to get it to work properly. let population = [{ ...

Dynamic Content with Angular Bootstrap Tooltip

Currently, I am developing a cart application in Angular and utilizing Angular Bootstrap. The main requirement is to display a tooltip when hovering over the cart icon, with the content of the tooltip changing based on whether the item is already in the c ...

Leverage React Native elements within a Meteor React-based website

Currently, we are in the process of developing a Meteor React web application that will be displayed within a web view on a react native app. While this arrangement may seem unconventional, it is due to time constraints and the fact that the react native a ...

Can you help me extract a number from an NSString that contains html tags?

Seeking assistance with extracting a telephone number from an NSString containing HTML tags. The specific telephone number needed is isolated within the string. <div><a href="tel:12345" x-apple-data-detectors="true" x-apple-data-detectors-type="t ...