Home > Net >  How to make hover styling with javascript?
How to make hover styling with javascript?

Time:12-16

My website css has the sections of div1, img, ul, and ul li. I have it set up so that you see the country list and when you click it shows you the sub region and flag image. I want a hover over just the country, but it goes over all three. I am using the hover on the ul li right now, but I need to reference the country list api, like I was able to for the other two. How do I create that reference in javascript?Here's the jsfiddle

var xhttp = new XMLHttpRequest();
var respJSON = [];
    xhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200) {
            resp = this.responseText;
            respJSON = JSON.parse(resp);

            html = document.getElementById("list");
            html.innerHTML = "";

            for(var i=0; i< respJSON.length; i  ){
                html.innerHTML  = "<li id=" i " onClick='clickMe(" i ")'><u>"   respJSON[i].name   "</u></li>"

            }
        }
    }
    xhttp.open("GET", "https://restcountries.com/v2/all", true);
    xhttp.send();
   
function clickMe(index) {
  document.querySelectorAll('#list img').forEach(
    function(item) {
      item.remove();
  });
     document.querySelectorAll('#list div1').forEach(
    function(item) {
      item.remove();
  });
        li = document.getElementById(index);
        img = document.createElement("img")
        img.src = respJSON[index].flag;
        li.append(img);        
        let div = document.createElement("div1");
        div.innerText = respJSON[index].subregion;
        li.append(div);
} 

CodePudding user response:

if you wanna apply hover effect to a btn just copy btn's class/id

and code snippet for your ref

#hover:hover{
background : purple;
}
#hover{
background : black;
color : white

}
<button id="hover"> HOVER ME </button>

Tell me is it ok or not

CodePudding user response:

List:

#hover-eff li {
color : green;
}
#hover-eff li:hover {
color : purple;
}
<ul id="hover-eff">
<li> List - 1 </li>
<li> List - 2 </li>
<li> List - 3 </li>
<li> List - 4 </li>
<li> List - 5 </li>
</ul>

So its a code snippet list

CodePudding user response:

It's happening that way because the country flag image is also child in the li tag you referenced in the css.

So what you can do is to add a class to the u tag in the li e.g. 'country-name'. See below:

// ...
for(var i=0; i< respJSON.length; i  ){
    html.innerHTML  = "<li id=" i " onClick='clickMe(" i ")'><u class='country-name'>"   respJSON[i].name   "</u></li>"
}
// ...

Then in the css, change the ul li: to .country-name, see below

.country-name:hover{font-size: 3em}

Test here: jsfiddle

  • Related