I have a table of buttons and once it is populated, I am using
document.getElementById("btn0").click();
to click the first button. The button is doing what it should do, but the background color of the button is not changing the same way it does when I am clicking it manually.
As you can see when its running, the background-color of the div is changing, but the button is not set to active.
Code Snippet:
var myfunc = function(){ document.getElementById("test").style.backgroundColor="red"; }; document.getElementById("btn0").click();
.btn{ border: none; color: white; width: 100%; padding: 5px 5px 5px 5px; height: 50px; cursor: pointer; font-size: 12px; background-color: #343a40; } .btn:active .btn.active{ background-color:green; outline: none; } .btn:focus{ background-color:green; outline: none; } #test{ background-color: green; width: 600px; height: 400px; }
<button class="btn" onclick="myfunc()" id="btn0"> Cool button</button> <div id="test"> Hello </div>
Here is a link to a jsfiddle I created: https://jsfiddle.net/58hrwcgo/3/
There's a difference between click
and focus
.
click()
clicks on the element and then unfocuses, unlike a real mouse click, which clicks and then focuses.
I would recommend simulating a real click by doing both:
document.getElementById("btn0").click();
document.getElementById("btn0").focus();
const btn = document.getElementById("btn0")
var myfunc = function(){
document.getElementById("test").style.backgroundColor="red";
btn.focus();
};
btn.click();
...
.btn:active, .btn.active{
background-color:green;
outline: none;
}
...
When clicking manually a focus state ist triggered first. That's why the appearance changes according to your class .btn:focus
.
document.getElementById("btn0").focus();
document.getElementById("btn0").click();
will lead to the desired behavior.
Furthermore you're missing a colon in your CSS-Example within the :active
state:
.btn:active, .btn.active { ... }
You can try the HTML DOM focus() method.
document.getElementById("btn0").focus();
You can read more about this in here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.