Search code examples
javascriptjqueryqtip2

How to move qtip2 tooltip to another element?


I have an element with a qtip2 tooltip applied to it. See JSFfiddle example: http://jsfiddle.net/inodb/y7xqvceL/2/. The element in the example is an <a id="test"> element. I want to move said tooltip to another <a id="test2"> element programmatically. I imagine I should either

  1. update the target of the existing tooltip or
  2. copy all the options of the original and create a new qtip on the second anchor element supplying all those options

The context to the problem is that I have a library which shows tooltips when hovering over a SVG <circle> elements. I want to wrap those circles in a <g> tag such that I can put a <text> on the circle. The tooltip however only works on the circle, so if you hover over the text, the tooltip is not displayed. I figured moving the qtip2 tooltip from the <circle> element to the <g> element would be easiest.


Solution

  • When I am reusing qtip2 tooltips & their options, I find it helpful to create a function that generates or destroys the tooltip.

    Fiddle: http://jsfiddle.net/y7xqvceL/8/

    //custom function to create tooltips with similar options or destroy them
    function GenerateTooltip(tooltipElement, isCreating) {
        //if creating the tooltip, use these options
        if (isCreating) {
            $(tooltipElement).qtip({
                content: {
                    text: 'Tooltip content that should be moved',
                },
            });
        } else {
            //if isCreating == false, destroy the tooltip specified
            tooltipElement.qtip('destroy', true);
        }
    }
    //...
    GenerateTooltip($("#test"), false); //first destroy old tooltip
    GenerateTooltip($("#test2"), true); //create new tooltip
    

    If that is too complicated or this operation only needs to happen once, I would recommend destroying the first tooltip and creating the new one manually.

    Fiddle: http://jsfiddle.net/y7xqvceL/9/

    //this button click moves the tooltip to the other element
    $("#move-tt").click(function () {
        $('#test').qtip('destroy', true); //destroy old tooltip
    
        $("#test2").qtip({ //create new tooltip
            content: {
                text: 'Tooltip content that should be moved',
            },
        });
    });