javascriptjquerytipsy

How to reapply jquery tipsy to existing elements


I am using the jquery tipsy tooltip to display additional information. I now made my website responsive so I added a resize event listener and depending on the size of the page more or less elements are shown. Therefore I have to reapply the tipsy tooltips. E.g I now might have new elements which did not yet have a tipsy.

Unfortunately it seems that after each reapply I have not replaced already existing tipsys but added another one on top.

Please look at the jsfiddle for the effect. After resizing the html result pane you can see multiple callbacks in the javascript console when the tooltip is displayed.

http://jsfiddle.net/7mbbcmvz/1/

Html Code:

<body>
    <a href="xy">xxx</a>
</body>

Javascript Code:

var i = 0;

function addTipsy(event) {
    $('a').tipsy({
        title: function() {
            i = i + 1;
            console.log('mouseenter ' + i);
            return 'test';
        }
    });
};

addTipsy();

window.addEventListener('resize', addTipsy);

Solution

  • Unbinding mouseenter and mouseleave before reapplying the tipsy handler seems to work:

    var i=0;
    
    function addTipsy(event) {
        $("a").unbind('mouseenter mouseleave');
        $('a').tipsy({
           title: function() {
                i = i + 1;
                console.log('mouseenter ' + i);
                return 'test';
            }
        });
    };
    
    addTipsy();
    
    window.addEventListener('resize', addTipsy);
    

    An alternative would be to remember those elements, that already have the tipsy handler by adding a class, and to add the tipsy handler only to those elements that do not have that class:

    function addTipsy(event) {
        $('a').not(".tipsyApplied").addClass("tipsyApplied").tipsy({
            title: function() {
                i = i + 1;
                console.log('mouseenter ' + i);
                return 'test';
            }
        });
    };