Select one element only on .hover() function among other elements with same class
Hi all, I'm very new to code and doing some practice on jQuery.
I'm trying to use jQuery (aware that @media query would be probably easier as CSS only solution) to have background images fade in and out on on selected words of a text with a .hover() event.
As all the images have the same CSS properties, they share the same class, and (obviously) jQuery doesn't make the distinction of which specific one to fade in/out, if not instructed to do so. Which is what I am struggling with.
Here the basic HTML structure. <p> has the CSS property display: inline; and I'm using <span> to select the desired words.
- <div>
- <p>Text text text text <span>SHOW IMAGE
- <div class="bg">
- <img src="image.jpg"/>
- </div></span>
- </p>
- <p>other text other text <span>SHOW OTHER IMAGE
- <div class="bg">
- <img src="other-image.jpg"/>
- </div></span>
- </p>
- </div>
The script is as follows. It works, but the result is that it shows always the last image on the HTML. I've tried out option with 'this', or $(this).siblings('.bg'), and even .find(), but none of them worked.
It's surely very simple, but can't figure it out ;)
Many thanks!
antonio
- var main = function () {
- $('span').hover(function() {
- $('span').css('cursor','pointer');
- $('.bg').fadeIn();
- }, function(){
- $('.bg').fadeOut();
- });
- }
- $(document).ready(main);