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

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

  •  24-06-2022
  •  | 
  •  

문제

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!

도움이 되었습니까?

해결책

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!

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top