1

On my page, I have several divs which change their background image when the cursor hovers over them. The setup is akin to this:

#myDiv1 {
  background-image: url("http://example.com/firstImage.png");
}
#myDiv1:hover {
  background-image: url("http://example.com/secondImage.png");
}
#myDiv2 {
  background-image: url("http://example.com/thirdImage.png");
}
#myDiv2:hover {
  background-image: url("http://example.com/fourthImage.png");
}
<div id="myDiv1">Hello</div>
<div id="myDiv2">World</div>

I would like to read the URL of each div's :hover background using JavaScript, without needing to invoke the :hover state itself. Are there any selectors that can retrieve that data?

Nick D
  • 23
  • 5
  • 1
    check .hover event https://api.jquery.com/hover/ – Amr Elgarhy Jul 16 '15 at 19:42
  • 2
    @Amr Elgarhy It looks to me like the .hover event is used to fire functions instead of retrieve data. I don't think it's what I'm looking for. – Nick D Jul 16 '15 at 19:48
  • @NickD no, it will not fire the hover, it will watch for hover, 'to be executed when the mouse pointer enters and leaves the elements' – Amr Elgarhy Jul 16 '15 at 19:51
  • you can iterate the cssRules on the styleSheet object, which lets you see the selector (including pseudos) – dandavis Jul 16 '15 at 20:32

1 Answers1

0

Update: This answer doesn't work and there is no 100% accurate way to get this information. The second parameter to Window.getComputedStyle() is a pseudo-element and :hover is a pseudo-class. See the duplicate question for more information: Read :hover pseudo class with javascript

You can use Window.getComputedStyle() like this:

var style = window.getComputedStyle(document.querySelector("#myDiv1"), ":hover").getPropertyValue("background-image");
alert(style);
#myDiv1 {
  background-image: url("http://example.com/firstImage.png");
}
#myDiv1:hover {
  background-image: url("http://example.com/secondImage.png");
}
#myDiv2 {
  background-image: url("http://example.com/thirdImage.png");
}
#myDiv2:hover {
  background-image: url("http://example.com/fourthImage.png");
}
<div id="myDiv1">Hello</div>
<div id="myDiv2">World</div>
Community
  • 1
  • 1
Dave
  • 10,748
  • 3
  • 43
  • 54