Creating a very simple toolbox with jquery. How to insert text from title attr

StackOverflow https://stackoverflow.com/questions/18296783

  •  24-06-2022
  •  | 
  •  

Frage

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!

War es hilfreich?

Lösung

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!

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top