I want to trigger a button with keyboard and with mouse. It works, but the :active does not show if I trigger it with keyboard.
HTML
<button id="btn1" onclick="btn1()"> click </button>
CSS
#btn1:active{
transform:scale(1.1);
}
Javascript
document.addEventListener("keydown", function(event) {
if (event.key === '1') {
document.getElementById("btn1").click();
}
});
CodePudding user response:
You'll need to use Javascript add/remove class for this use case.
In the keydown
eventListner add the active class. Add another eventListner for keyup
and then remove that active class.
document.addEventListener("keydown", function(event) {
var btn = document.getElementById("btn1");
btn.click();
btn.classList.add('active');
});
document.addEventListener("keyup", function(event) {
var btn = document.getElementById("btn1");
btn.classList.remove('active');
});
function btn1(){
}
#btn1:active{
transform:scale(1.1);
}
.active{
transform:scale(1.1);
}
<button id="btn1" onclick="btn1()"> click </button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use selector.style
and use setTimeout() to transfrom to default scale
Example :
document.addEventListener("keydown", function(event) {
if(event.key == "1"){
clicked(document.getElementById("btn1"));
document.getElementById("btn1").click();
}
});
function clicked(el){
el.style.transform = "scale(1.1)";
setTimeout(()=>{ el.removeAttribute('style'); }, 100);
}
#btn1:active{
transform:scale(1.1);
}
<button id="btn1" onclick="//btn1()"> click </button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>