shenkwen
shenkwen

Reputation: 3880

Simulating a CSS hover with javascript

I have a page with the following code in order to show grandchildrens when I hover a parent.

.parent:hover .grandchildren {
    visibility: visible;
    opacity: 1;
}

I want to adjust the grandchildren and its children's styles.

Every time I make a few modifications and refresh the page, I have to look for the said parent in developer tools and switch its state to "hover" by clicking the little checkbox.
Now I am using a laptop without a mouse, you can imagine how this repetitive F12 pressing, HTML element locating, and checkbox clicking could be annoying.

So I am thinking if there is anyway to make the said parent element automatically 'hovered' every time I refresh the page (of course only when I am still developing the page).

I've tried the following, but none of them works:

$('.parent').mouseover()
$('.parent').hover()
$('.parent').trigger('mouseover')

I guess it is because the hover is a CSS thing and the above only trigger jQuery events which don't trigger CSS hover.

Am I right? Actually I could use a brief illustration of the differences between CSS hover and jQuery hover.

So is there any way to simulate a hover, besides the way provided by browser developer tools?

Upvotes: 1

Views: 454

Answers (1)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Given these styles:

p:hover {
  background: yellow;
  border: 1px solid black;
}

p {
  background: lightgreen;
  color: blue;
}

… you could simulate a permanent hover by changing the stylesheet to look like this:

p {
  background: yellow !important;
  border: 1px solid black !important;
}

p {
  background: lightgreen;
  color: blue;
}

Note that I removed :hover from the first selector, and I added !important to all its styles.

This will cause p elements to have a yellow background, black border, and still maintain their default blue color.

The following works in Chrome, Opera, and Safari. If you need an IE or Firefox solution, let me know:

function change() {
  var ss= document.styleSheets;
  for(var i = 0 ; i < ss.length ; i++) {
    var rules= ss[i].cssRules ? ss[i].cssRules : ss[i].rules;
    for(var j = 0 ; j < rules.length ; j++) {
      if(rules[j].selectorText==='p:hover') {
        rules[j].selectorText= 'p';
        rules[j].style.cssText= rules[j].style.cssText.replace(/;/g,' !important;');
      }
    }
  }
}
p:hover {
  background: yellow;
  border: 1px solid black;
}

p {
  background: lightgreen;
  color: blue;
}
<button onclick="change()">Change <b>p:hover</b> to <b>p</b></button>
<p>Testing</p>

Upvotes: 1

Related Questions