Skip to content Skip to sidebar Skip to footer

Css/js Solution: On Hover Of Child Element, Change Parent Div

I know CSS is 'cascading', but in this case I want the effect to ascend. I'm open for either a JS or CSS solution, but honestly I'd prefer the solution with the least amount of co

Solution 1:

The solution would probably be JS:

$(".letter").hover(function() {
    $(this).closest("#word").toggleClass("hovered")
});

Here is a fiddle: http://jsfiddle.net/zT9AS/2

Solution 2:

True;

#word#h:hover {
    background-color: rgba(0, 102, 0, .5); 
}

False;

#h:hover#word{
    background-color: rgba(0, 102, 0, .5);
}

Solution 3:

A without jquery solution:

onload = function()
{
  var links = document.getElementsByTagName('a');
  for (var i = 0; i < links.length; ++i)
  {
    if (links[i].className == 'letter')
    {
      links[i].onmouseover = function() {
        document.getElementById('word').style.backgroundColor="#0000FF";
      };
      links[i].onmouseout = function() {
        document.getElementById('word').style.backgroundColor="#FFFFFF";
      };
    }
  }
}

Solution 4:

It can be done in pure JS, no jQuery (I assume you don't want that since it wouldn't be that light in code), this is the best I could came out with:

var word = document.getElementsByClassName("letter");
for (i=0; i<word.length; i++) {
  word[i].addEventListener("mouseenter", function( event ) {
    parent = event.target.parentNode.parentNode;
    //whenever the mouse hovers over a letter this will be evaluated once 
    parent.style.backgroundColor = "green";
  });
  word[i].addEventListener("mouseout", function( event ) {
    parent = event.target.parentNode.parentNode;
    //whenever the mouse hovers over a letter this will be evaluated once 
    parent.style.backgroundColor = "";
  });
}

Try it in this fiddle:http://jsfiddle.net/SZ9ku/17/

Solution 5:

In POJS, add the following

CSS

.wordBg {
    background: rgba(0, 102, 0, .5) !important;
}

Javascript

var changeWordBg = (function (word) {
    returnfunction (evt) {
        if (evt.target.classList.contains("letter")) {
            switch (evt.type) {
                case"mouseover":
                    word.classList.add("wordBg");
                    break;
                case"mouseout":
                    word.classList.remove("wordBg");
                    break;
                default:
            }
        }
    };
}(document.getElementById("word")));

document.body.addEventListener("mouseover", changeWordBg, false);
document.body.addEventListener("mouseout", changeWordBg, false);

On jsfiddle

Post a Comment for "Css/js Solution: On Hover Of Child Element, Change Parent Div"