Adam Adam - 7 months ago 31
Javascript Question

jQuery .click() :active

Given the following code (jFiddle):

<style>
div.bluebox {
width: 200px;
height: 200px;
background-color: blue;
}

div.greenbox {
width: 200px;
height: 200px;
background-color: green;
}


div.greenbox:active{
background-color: yellow;
}
</style>
<script>
$('.bluebox').click(function(e){
e.preventDefault();
$('.greenbox').click();
});
</script>

<div class="bluebox">
</div>

<div class="greenbox">
</div>


If I click on the greenbox, then its background color changes to yellow. If I click on the bluebox, then the click event of the greenbox is triggered, but the background is still green. How can I tell jQuery to give greenbox the status active when click is executed indirectly?

Answer

You can't trigger :active CSS state with javascript. However, you can toggle a class instead to reproduce a similar behavior :

div.greenbox.active{
  background-color: yellow;
}

$('.bluebox').click(function(e){
      e.preventDefault();
    $('.greenbox').toggleClass('active');
});

Fiddle