I have a few <span> elements inside of a <div>. When you hover over one <span> it should highlight all the preceding<spans> and the hovered <span>.
How can I do this using just CSS or jQuery?
I suspect a jQuery answer will do the following, but I can’t find functions for 1 & 2.
- Get the child # of the currently hovered element
- Select all the children up to that number
- Add the ‘hover’ class to them
You can do this with jQuery :
Demonstration
This uses prevAll to select all the preceding spans of the same div. No need to use the index of the current element but you could have got it with the index function and then you would have used the lt selector (
$(this).sibblings(":lt("+$(this).index+")")). Of course prevAll is much simpler.As noticed by elclarns, this can be shortened in