Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  134] [ 4]  / answers: 1 / hits: 18860  / 4 Years ago, tue, october 20, 2020, 12:00:00

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/


More From » html

 Answers
14

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();

[#50593] Friday, October 2, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daryldeontaeh

Total Points: 46
Total Questions: 97
Total Answers: 105

Location: Maldives
Member since Sat, Jan 29, 2022
2 Years ago
;