Nick LaMarca
Nick LaMarca

Reputation: 8188

Hovering Over Text and popping up an image

Is it possible to hover over some text and display an image? Once your mouse is off the text the image goes away?

<p>I have a word, when I hover over it, I see an image </p>

When you put your mouse over the word "image" it displays "image1.jpg"

Upvotes: 1

Views: 19882

Answers (5)

David Thomas
David Thomas

Reputation: 253308

Because you want functionality to occur by hovering over a piece of text, which isn't wrapped in an element, this becomes a little more complex, but not impossible by any means. The following takes your 'simple' html, and creates span tags around the text you want to have hover functionality:

$('p').each(
    function(){
        var text = $(this).text();
        var spanText = text.replace('image','<span class="imgText">image</span>');
        $(this).html(spanText);
    });

$('.imgText').live(
    'mouseenter',
    function(){
        $('<img src="path/to/img.png" />')
            .appendTo($(this));
    });

$('.imgText').live(
    'mouseleave',
    function(){
        $(this).find('img').remove();
    });

JS Fiddle demo.

Upvotes: 1

gparis
gparis

Reputation: 1267

Something like this:

HTML:

<p id="text">Foo</p>
<div id="image_to_show" style="display:none"><img src="image1.jpg"/></div>

JavaScript:

$('#text').mouseenter(function(){
  $('#image_to_show').fadeIn();
}).mouseleave(function(){
  $('#image_to_show').fadeOut();
});

Upvotes: 1

Jason
Jason

Reputation: 15358

Hey, to do that what you need to use is the jquery.hover() method.

What you can do is setup a link tag

Working Example

http://jsfiddle.net/HDhws/

Upvotes: 1

mVChr
mVChr

Reputation: 50177

This can be done with pure HTML:

<a href="#">Hover over me<img src="whatever.gif" /></a>

and CSS:

a img { display:none; }
a:hover img { display:block; }

See example!

Upvotes: 3

mpj
mpj

Reputation: 5367

$('.yourTextClass').hover(function() {
  // mouseOver function
  $('#yourImg').show();
}, function() {
  // mouseOut function
  $('#yourImg').hide();
});

You can also use fadeIn() and fadeOut instead of show and hide if you want some basic animation.

Upvotes: 1

Related Questions