9

I want to add a tooltip in a text so for example if I have a code like this:

<a href="http://google.com" title="The World's Largest Search Engine!">Google!</a>

On mouse hover, I want to show that tooltip. Using title is a good way but how can I style to look it better? Any help: JSFIDDLE

Estina Esitna
  • 317
  • 3
  • 5
  • 11
  • 1
    if your'e using jquery, you can also use the jquery-ui library which in addition to other cool stuff also has a tooltip feature: https://jqueryui.com/tooltip/ – MorKadosh Dec 14 '15 at 23:08

1 Answers1

4

If you wish to create it dynamically using jquery, you may do the following :

<a href="http://google.com" data-title="The World's Largest Search Engine!">Google!</a>
<style>  
.box
{
  border: 1px solid green;
  position:absolute;
  color: white;
  top: 19px;
  left: 30px;
  background-color: black;
}
</style>
<script>
$().ready(function(){
$( "a" ).hover(
  function() {   
   var title = $(this).attr("data-title");  // extracts the title using the data-title attr applied to the 'a' tag
    $('<div/>', { // creates a dynamic div element on the fly
        text: title,
        class: 'box'
    }).appendTo(this);  // append to 'a' element
  }, function() {
    $(document).find("div.box").remove(); // on hover out, finds the dynamic element and removes it.
  }
);
  });
</script>

Example : http://jsfiddle.net/9RxLM/5164/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • 1
    Why use `data-title`? Just use `title` then _enhance_ it — get the text to use in the styled tip then remove the title attribute from the element, or as [an answer](http://stackoverflow.com/a/17579580/17300) in the ["duplicate question"](http://stackoverflow.com/questions/9927640/styling-native-tooltip-from-title-tooltip-text) suggests, use `aria-label` since that's its purpose. – Stephen P Dec 14 '15 at 23:40
  • 1
    You can also do that. I did that to avoid unnecessary steps involved in removing an attribute of the element. – DinoMyte Dec 14 '15 at 23:44