0

I'm about to create a very simple tooltip solution for my website based on jquery. Im using the following script:

jQuery(document).ready(function($){
$("a.tooltip").hover(function () {
    $('<div class="tooltip-box"><p></p></div>').text($this.attr('title')).appendTo(this);
    }, function () {
    $("div.tooltip-box").remove();
});
$("a.tooltip").on("click", function(event){
    event.preventDefault();
});

});

The markup:

<a href="#" title="Tooltip text here" class="tooltip"></a>

Somehow it isn't working at the moment. I tried a lot myself and searched here but can't figure it out. Sorry if is only simple syntax error. I'm a jquery beginner. Thanks for your help!

Philip
  • 3
  • 1

2 Answers2

0

I don't think that $('<div class="tooltip-box"><p></p></div>') is a valid jQuery selector (I could be wrong).

I would recommend not trying to always get everything on one line. Try something like this (untested):

jQuery(document).ready(function($){
$("a.tooltip").hover(function () {
    var titleText=$(this).attr("title");
    $(this).after("<div id='tooltip-box'>" +titleText+ "</div>");
    }, function () {
    $("div#tooltip-box").remove();
});
$("a.tooltip").on("click", function(event){
    event.preventDefault();
});
}); 

Here is a fiddle.

You will of course need to style the div with your own CSS.

Good luck!

kmoney12
  • 4,413
  • 5
  • 37
  • 59
  • Perfect thank you! I'm so new to jquery I actually wanted to do it by defining a variable first but failed because I didn't know how to embed the var in the append. It's working now! Just so that I learn something here: the correct way to define a variable in jquery is the way you did it and just like in javascript? I read somewhere that this is not valid... Thanks again :) my first post here and problem solved within 5min. Exciting! – Philip Aug 18 '13 at 07:56
  • jQuery is not a different language, it is just a library. Any javascript functions, variables, syntax, etc still work fine. When using jQuery you will usually run into some more advanced variables (complex objects and DOM's) - but the simple stuff still works fine too. – kmoney12 Aug 18 '13 at 07:58
0

I've taken your code and just modified something. Here it is working. I've put some text in your

tag to identify if the right tag is in effect.

jQuery

jQuery(document).ready(function(){

$('a').hover(function(){
    $('.tooltip-box p').text('test');
}, 
             function () {
    $("div.tooltip-box p").text('this will change');        
});

$("a.tooltip").on("click", function(event){
event.preventDefault();
});

});

HTML

<a href="#" title="Tooltip text here" class="tooltip">click</a>
<div class="tooltip-box">
    <p>this will change</p>
</div>

This is jsfiddle

Best of Luck.

Ariful Haque
  • 3,662
  • 5
  • 37
  • 59