Using JavaScript's click simulation does not work for CSS pseudo-class :active
. After I tried some classList methods, it still doesn't work. I just wonder if there are some possible ways to realize that?
Run the snippet below and click the button to see the ripple effect. The ripple effect doesn't repeat automatically with the included setInterval
code that simulates a click. It only works with the real click of the button:
const btn = document.querySelector(`button`);
btn.addEventListener(`click`, (e) => {
console.clear();
// try to manually set pseudo-class `:active` ?
btn.classList.toggle('ripple', 'ripple:active');
console.log('classList =', e.target.className);
});
setInterval(() => {
// js simulator click doesn't work for css pseudo-class `:active`
btn.click();
}, 1000);
.ripple {
position: relative;
overflow: hidden;
}
.ripple:after {
content: "";
display: block;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
pointer-events: none;
background-image: radial-gradient(circle, #000 10%, transparent 10.01%);
background-repeat: no-repeat;
background-position: 50%;
transform: scale(10, 10);
opacity: 0;
transition: transform .5s, opacity 1s;
}
.ripple:active:after {
transform: scale(0, 0);
opacity: .2;
transition: 0s;
}
<button >ripple button</button>
References
https://developer.mozilla.org/en-US/docs/Web/CSS/:active
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
CodePudding user response:
It is impossible according to the API description so far.
The :active
CSS pseudo-class represents an element (such as a button) that is being activated
by the user.
When using a mouse
, "activation" typically starts when the user presses down the primary mouse button.
APIs
https://developer.mozilla.org/en-US/docs/Web/CSS/:active
https://drafts.csswg.org/selectors/#the-active-pseudo
https://html.spec.whatwg.org/multipage/semantics-other.html#concept-selector-active
CodePudding user response:
You can try to recreate "active" event using js and css
CSS :
.ripple {
background-color: red;
}
.ripple:active, .ripple.active {
background-color: green;
}
JS :
let btn = document.querySelector('.ripple');
btn.addEventListener('click', e => {
btn.classList.add('active');
setTimeout(() => {
btn.classList.remove('active');
}, 500);
});
setInterval(() => {
console.log('click');
btn.click();
}, 2000);