简体   繁体   中英

Clear title property while JQuery tooltip shows

I am using some very simple JQuery to create a hovering tool tip using text stored in elements' title attribute. It's working okay, but I need to stop the browser's default title behaviour occurring at the same time (or after the slight delay on hover).

在此输入图像描述

I think JQuery's .on() functionality may not be the best way, although I am trying to use the latest functionality (that I am aware of!).

Currently if I clear the existing title value, the actual tooltip appears but is empty. I think that is because the code runs continuously while the mouse is over the element.

在此输入图像描述

Can anyone offer a way to stop the browser's title text appearing, but restore the original value of title onmouseout? I need the code to work with JQuery 1.10.1+ with XHTML1.1 compatibility.

Thanks.

    $(document).ready(function () {
        $('<div/>', { id: 'ttfloat', 'class': 'tooltip' }).appendTo('body');
        BuildTipsV3();
    });

    function pageLoad() { // fired by ASP.NET after partial postback
        BuildTipsV3();
    }

    //var temptt;

    function BuildTipsV3() {
        $("[title]").on({
            mouseenter: function () {
                var o = $(this).offset();
                var y = o.top + 18;
                var x = o.left;
                temptt = $(this).attr("title"); // temp storage
                $(this).data('title', temptt);
                //$(this).attr('title', '');
                var tooltip = temptt;
                tooltip = tooltip.replace(/(\r\n|\n|\r)/gm, "<br/>");
                $("#ttfloat").css({top:y, left:x})
                             .html(tooltip)
                             .show();
            },
            mouseleave: function () {
                $("#ttfloat").hide();
                $(this).attr('title', $(this).data('title')); // reset for accessibility
            }
        });
    }

Try making these lines:

temptt = $(this).attr("title"); // temp storage
$(this).data('title', temptt);
//$(this).attr('title', '');
var tooltip = temptt;

do this instead:

var $this = $(this),
    tooltip = $this.attr('title') || $this.data('title');
$this
    .attr('title', '')
    .data('title', tooltip);

What the code above does is that if the title attribute is empty, the or ( || ) operator will then look for the title within the data.

Use $(selector).removeAttr('title'); to achieve your desired results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM