Adding :active pseudo state using JS/JQuery

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

      // Here i want to add the active effect manually.
1 Like

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

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

this is the project i’m working on

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

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.

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

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

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

Anyother way to add :active class;

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.

Then you should useJquery toggle.

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

For that use setTimeout() with callback.

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

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

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

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

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

   animation-name: chCol;
  animation-duration: 0.1s;
  position: relative; top: 3px;

An then inside your run function, use setTimeout like:

  function run(a, x) {
    setTimeout(() => $(box[x]).removeClass('drum-pad-active'), 100);

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


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

keydown / keyup…
My Similar code that you can be inspired by…

  $(document).bind('keydown', function(e) {
	$(this).bind('keydown', function(e) {

		if(e.keyCode == 13)

		 key = e.keyCode;			
         value = String.fromCharCode((96 <= key && key <= 105)? key-48 : key)
		if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) 
            // 0-9 only