Adam
Adam

Reputation: 29119

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?

Upvotes: 0

Views: 106

Answers (2)

Nutshell
Nutshell

Reputation: 8537

EDIT

The code on mousedown() and mouseup() as we said in the comments :

$('.bluebox').mousedown(function(){
    $(".greenbox").toggleClass('active');
}).mouseup(function(){
  $(".greenbox").toggleClass('active');
});

New fiddle


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

Upvotes: 1

Ivan Gajic
Ivan Gajic

Reputation: 486

You should try to set everything in your js. like this:

$('.bluebox').mousedown(function(){
    $(".greenbox").css("backgroundColor", "yellow");
    }).mouseup(function(){
        $(".greenbox").css("backgroundColor", "green");
    });
$('.greenbox').mousedown(function(){
    $(".greenbox").css("backgroundColor", "yellow");
}).mouseup(function(){
    $(".greenbox").css("backgroundColor", "green");
});

https://jsfiddle.net/1nxfy18v/

Upvotes: 1

Related Questions