Pablo Weber Pablo Weber - 1 month ago 4
HTML Question

How do you replace text with a link tag when using .hover()?

I'm trying to make a "contact" section in the navigation bar of a website (with jQuery) that includes

<a>Instagram</a>
and
<a>Email</a>
but that only appears when I hover on
#contact
.

So far I've only been able to make strings appear when I hover over
#contact
.

HTML:

<span id="contact">CONNECT</span>


jQuery:

$("#contact").hover(function(){
$(this).text(function(i, text){
return text === "CONNECT" ? "Instagram | Email" : "CONNECT";
})
});


How could I make I make it so "Instagram" and "Email" are links?

I tried this:

$("#contact").hover(function(){
$(this).text(function(i, text){
return text === "CONNECT" ? "<a>Instagram</a> | <a>Email</a>" : "CONNECT";
})
});


but when I hovered I got
"<a>Instagram</a>"
and
"<a>Email</a>"
as strings and not links.

Any help would be greatly appreciated!

Answer

You need to use .html() to update if you need to set HTML instead of .text().

jQuery(function($) {
  $("#contact").hover(function() {
    $(this).html(function(i, text) {
      return $(this).text() === "CONNECT" ? "<a>Instagram</a> | <a>Email</a>" : "CONNECT";
    })
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="contact">CONNECT</span>

Comments