javascriptjqueryonmouseoverjquery-hover

Display image when hover over text


I'm creating a simple inventory app, and currently have a table that lists all the items in stock. I would like an image of each item to display when the user hovers over the description of each item, but there could be many different items in the list and each has it's own picture. I was testing some code with the items below but it doesn't work correctly because only image displays for both items.

How can I get a different image to display for each item I have in a list?

HTML

 <li>
<a href="#">Get Well</a>
<div class="place-image"><img src="../img/Get%20Well.jpg"></div>
</li>

<li>
<a href="#">I Love You</a>
<div class="place-image"><img src="../img/I%20Love%20You.jpg"></div>
</li> 

Javascript

$('a').hover(
function() {
    $('.place-image').fadeIn('slow');
},function() {
    $('.place-image').fadeOut('slow');
}
);

Solution

  • The best way is that you just use jQuery.

    1. Link the jQuery library to your project, place it inside header tag
    2. Follow the code

    $(".Your_class").mouseenter(function(){
            if ($(this).parent('div').children('div.image').length) {
                $(this).parent('div').children('div.image').show();
            } else {
                var image_name=$(this).data('image');
                var imageTag='<div class="image" style="position:absolute;">'+'<img src="'+image_name+'" alt="image" height="100" />'+'</div>';
                $(this).parent('div').append(imageTag);
            }
        });
    
        $(".Your_class").mouseleave(function(){
            $(this).parent('div').children('div.image').hide();
        });
    <html>
    <head>
    <title>Bikash Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    <body>
    <div>
        <a class="Your_class" href="#" data-image="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">Show Image</a>
    </div>
    <div style="margin-left:250px;">
        <a class="Your_class" href="#" data-image="https://i.sstatic.net/q1b4w.jpg?s=64&g=1">Another Image</a>
    </div>
    </body>
    </html>

    1. data-image :-Keep your image name here
    2. Give appropriate styles to the div(imageTag string)fi