Michael Pon Michael Pon - 7 months ago 19
HTML Question

text on anchor changes when hover

Is it possible to change the content of an anchor when hovered? i have this sample fiddle
i want to change the about anchor to some like My bio when hovered. and something else also for the home. the content attribute doesn't seem to work well with this.

HTML:

<ul>
<li><a href="#">About</a></li>
<li><a href="#">Home</a></li>
</ul>


CSS:

ul { list-style: none; }
ul li a:hover { color: red; content: 'Content'; }

Answer

"content property is used with the :before and :after pseudo-elements, to insert generated content." not with normal elements.

Reference: http://www.w3schools.com/cssref/pr_gen_content.asp

You can change it using jQuery:

$('li a').mouseenter(function(){
    $(this).data('text', $(this).text());
    $(this).text('Content');
}).mouseleave(function(){
    $(this).text($(this).data('text'));
});

http://jsfiddle.net/TrueBlueAussie/s6ao29eg/2/

This version simply saves the text to data on the element on mouseenter, and restores it on mouseleave. You can also use hover passing the same two functions.

e.g.

$('li a').hover(function(){
    $(this).data('text', $(this).text()).text('Content');
}, function(){
    $(this).text($(this).data('text'));
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/s6ao29eg/5/

I notice several other clever CSS-only solutions have been provided, so the choice depends on how much you can change your content, vs adding code.

If you want different text, use a data attribute:

<li><a href="#" data-content="About me!">About</a></li>

e.g.

$('li a').hover(function(){
    $(this).data('text', $(this).text()).text($(this).data('content'));
}, function(){
    $(this).text($(this).data('text'));
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/s6ao29eg/8/

Update to use a transition (fade) as requested:

$('li a').hover(function(){
    $(this).stop(true,true).fadeOut(function(){
       $(this).data('text', $(this).text()).text($(this).data('content')).fadeIn();
    });
}, function(){
    $(this).stop(true,true).fadeOut(function(){
        $(this).text($(this).data('text')).fadeIn();
    });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/s6ao29eg/10/

Further update now the rules have changed :)

As the HTML content apparently cannot be modified, use the index position of the LI combined with an array of text items:

var content = ["About me!", "My home!"];
$('li').hover(function(){
    var $a = $('a', this);
    $a.stop(true,true).fadeOut(function(){
       $a.data('text', $a.text()).text(content[$(this).index()]).fadeIn();
    });
}, function(){
    var $a = $('a', this);
    $a.stop(true,true).fadeOut(function(){
        $a.text($a.data('text')).fadeIn();
    });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/s6ao29eg/11/

Credit to @MariaMadalina who used an array before even knowing the HTML could not be modified :)