Adding :active pseudo state using JS/JQuery

Adding :active pseudo state using JS/JQuery
0

#1

I want to add :active pseudo state/class when I click an element.

<p>Hello</p>
<script>
$('p').click(
    function(){
      // Here i want to add the active effect manually.
     $("div").active();
}
);
</script>

#2

Maybe you meant $("div").focus()?


#3

@randelldawson
$(“div”).focus() didn’t work


this is the project i’m working on


#4

Ok, so explain exactly what you want to happen when a p element is clicked.


#5

@randelldawson
When i click a div it active so its background color change when it gets active. Now i want to add the same effect when i press a key on the keyboard.


#6

That’s not how pseudo classes work. Use .addClass(“active”); on div. In said class add styling you wish …


#7

@codename11
.addClass(‘active’) can’t solve my problem.
It can change background-color on first time only;


#8

.removeClass('active'). The active pseudo classes is not for adding/removing via JS


#9

@DanCouper
Anyother way to add :active class;


#10

Edit: I edited instead of replying and just wiped this reply out.

You can’t really manipulate pseudo classes using JS, that’s not the.point of them.


#11

Then you should useJquery toggle.


#12

@DanCouper
Ok. Any way to change background-color for 1s when clicked or a button is pressed;


#13

For that use setTimeout() with callback.


#14

Add/remove an actual class if you want to use JS or use CSS animation on the :active pseudo class. In this case it sounds like it’s putrely styling so use CSS animation, you shouldn’t need JS for that at all


#15

You’re forgetting the point " i want to active an element (div) when a button is press"


#16

Then yes, you need to use JS. There are ways to do it with CSS but they’re hacky, it’s very simple to with JS: listen for click then either change class on the div or literally change the background color


#17

Now you’re understanding my situation. But not completely I need to active that element for just 1s


#18

I first recommend simplifying your $(“body”).keypress to the following:

  $("body").keypress(event => {
    let ch = String.fromCharCode(event.charCode).toUpperCase();
    $('#' + ch).click();
  });

You notice instead of executing the run function, I simply “click” the applicable div.

Next, you can change your pseudo-class selector to a normal class named drum-pad-active

.drum-pad-active{
   animation-name: chCol;
  animation-duration: 0.1s;
  position: relative; top: 3px;
}

An then inside your run function, use setTimeout like:

  function run(a, x) {
    $(box[x]).addClass('drum-pad-active')
    setTimeout(() => $(box[x]).removeClass('drum-pad-active'), 100);
    $("#beats").text(str[x]);
    a.play();
  }

Note the 100ms delay so that your animation finishes properly.


#19

No, I understood, 10sec, or 500ms, or 10min it’s exactly the same, do something for time, just what @randelldawson said