Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change a css background onclick

Please check this JSFiddle, Here there are two div named step-wrapper and inside these step-wrapper div there are three div named step-box. Its written in such a way that while clicking on a step-box div its background color changes to yellow.

I have added a reset button. What I needed is on clicking the reset button, the color of last clicked step-box div should changes to white. But in this code, when I click the reset button all the step-box background color changes to white.

like image 676
nitroman Avatar asked Jun 08 '15 16:06

nitroman


2 Answers

I believe this is what you're looking for: https://jsfiddle.net/richardgirges/8m9qstg3/11/

We're saving a reference to the lastClicked div, and targeting it specifically when reset is hit. Like so:

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;
    }
});

EDIT: Improved the code. Using explicit var instantiation to keep it within scope.

like image 77
richardgirges Avatar answered Sep 21 '22 11:09

richardgirges


It looks kind of weird when you have only one reset button at the very end but only want to reset only one wrapper. How about if we add a reset button inside the wrapper div and resets only that wrapper when we click each reset? See if you like it.

HTML:

<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>

Javascript:

$('.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', '' );
});
like image 26
Ming Huang Avatar answered Sep 21 '22 11:09

Ming Huang