Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bringing a div to :active state via jquery .trigger() method

I have assigned to a div an :active CSS pseudo class, to make it "responsive" on clicks and holds.

   .quarter:active{
      opacity: 0.5;
   }

What I want to achieve is to simulate a long click with JQuery. The .trigger("click") doesn't seem to do the trick since there is no visible discoloration. I have also tried with .trigger("focus") and .trigger("mousedown") but it seems I mess up somewhere.

    <div id="1" class="quarter green" ></div>
    <div id="2" class="quarter red" ></div>
    <div id="3" class="quarter yellow" ></div>
    <div id="4" class="quarter blue" ></div>

Is there a way to achieve that or do I have to use a toggleClass approach?

Edit: Thanks to nashcheez answer I solved my problem using the .trigger("focus") followed by a setTimeout(...{ .blur() }). Thank you all for the quick responses.

like image 763
Thodoris Avatar asked Mar 21 '17 12:03

Thodoris


2 Answers

You can do it without jQuery and in pure css. You can just provide it a focus state in css and a tabindex attribute in the html.

Refer code:

.quarter {
  height: 40px;
  width: 40px;
  display: inline-block;
  margin-right: 15px;
  cursor: pointer;
}

.quarter:focus {
  opacity: 0.5;
}

.green {
  background-color: green;
}

.red {
  background-color: red;
}

.yellow {
  background-color: yellow;
}

.blue {
  background-color: blue;
}
<div id="1" class="quarter green" tabindex="1"></div>
<div id="2" class="quarter red" tabindex="1"></div>
<div id="3" class="quarter yellow" tabindex="1"></div>
<div id="4" class="quarter blue" tabindex="1"></div>

This way your opacity persists on click of the div, and returns back to the normal value on clicking anywhere outside.

Read more about the tabindex attribute here.

like image 128
nashcheez Avatar answered Nov 15 '22 17:11

nashcheez


Generally, :active can be applied to <a> or <button> elements (as they are clickable), to make a div :active first you need to click on div it, then will be in :active state, also in the same case you can use :focus on this element to show as active. Second option you can use active class and add it on particular div.

See the below snippet with its working.

$('.quarter.green').trigger('focus');
.quarter:active,
.quarter:focus,
.quarter.active {
  opacity: 0.5;
  color: red;
}

.quarter:active {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="1" class="quarter green" contenteditable="true">1 Using contenteditable property</div>
<div id="2" class="quarter red active">2 Using active class</div>
<div id="3" class="quarter yellow">3</div>
<div id="4" class="quarter blue">4</div>
like image 33
Rohan Kumar Avatar answered Nov 15 '22 19:11

Rohan Kumar