1
I am creating elements and setting attributes dynamically via Javascript.
But I’m not getting the property set :hover
.
Follows code:
$(document).ready(function(){
let valores = ['0119621A0','7.6.62.211', '27.1.23.112'];
let cores = ["#0000ff","#00b300","#ff471a"];
if (valores.length != null){
let divPrincial = document.getElementById("kits");
for(var i = 0; i < valores.length; i++){
let div = document.createElement("div");
let lbl = document.createElement("label");
var style = document.createElement('style');
var css = i + ":hover { background-color: #00ff00 }";
style.styleSheet = css;
lbl.innerHTML = valores[i];
div.setAttribute("id",i);
div.setAttribute('onclick','active(this);');
div.setAttribute("style","background-color:" + cores[i] + ";" + "border: 2px solid " + cores[i] + ";");
div.classList.add("t1");
if(i == 0){
div.classList.add("active");
}
divPrincial.appendChild(div);
div.appendChild(lbl);
div.appendChild(style);
}
}
});
function teste(){
alert();
}
function active(temp){
var element = document.getElementById(temp.id);
var ativo = document.getElementsByClassName('active');
element.classList.add("active");
for(var i = 0; i < ativo.length; i++){
if(ativo[i].id != temp.id){
document.getElementById(ativo[i].id).classList.remove("active");
}
}
}
.vl {
border-left: 3px solid black;
height: 500px;
margin-left: 5vw;
}
#kits{
margin-left: 6.5vw;
margin-top: -24vw;
}
.t1 {
margin-left: -26px;
width: 4.7vw;
border-top-right-radius: 50px 50px;
border-bottom-right-radius: 50px 50px;
height: 2vw;
}
label {
margin-left: 0.2vw;
color: white;
margin-top: 0.4vw;
}
.active {
width: 5.7vw !important;
}
.active > label {
margin-left: 0.5vw;
}
<!DOCTYPE html>
<html lang="pt">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="vl"></div>
<div id ="kits">
</div>
</body>
</html>
This won’t work, you’d better use JS to add/remove classes, and treat the
:hover
in the CSS code.– bfavaretto
This way you spoke had already done, and it worked very well. I just wanted to be sure some possibilities with the JS.
– Igor Carreiro