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?

4
  • 1
    check .hover event api.jquery.com/hover Commented Jul 16, 2015 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. Commented Jul 16, 2015 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' Commented Jul 16, 2015 at 19:51
  • you can iterate the cssRules on the styleSheet object, which lets you see the selector (including pseudos) Commented Jul 16, 2015 at 20:32

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.