Search code examples
jqueryqtip2

Is it possible to set position of a Qtip programmatically?


I'm currently implementing Qtip2 tooltips thoughout my site, and they're working very well.

However, I need to set the position of the tooltip on a per-element basis. For this I've setup a couple of data attributes like this:

<img src="/images/help-icon.png" 
    class="tooltip" 
    title="Lorem ipsum dolor sit amet consectetur adipiscing elit" 
    data-tooltip-my-position="right center" 
    data-tooltip-target-position="left center" />

I have tried using a function to get the data attribute, however it appears that the my and at properties do not accept a function, as this simply places the tooltip in the bottom right/top left which appears to be the default positioning.

$(this).find('.tooltip').qtip({
    show: {
        event: 'mouseenter click'
    },
    position: {
        my: function() {
            return $(this).data('tooltip-my-position'); // doesn't work
        },
        at: function() {
            return $(this).data('tooltip-target-position'); // doesn't work
        }
    }
});

I have looked through the documentation, but there appears to be no guidance on programmatically setting positioning properties on or after initialisation.

Does anyone know if what I'm trying to do is possible, and if so, how?


Solution

  • I just came up with a solution, typically enough just after I posted here.

    I hooked up a function to the show event which is passed the target element as a parameter which I can then grab the data attributes from:

    $(this).find('.tooltip').qtip({
        show: {
            event: 'mouseenter click'
        },
        events: {
            show: function(event, api) {
                var $el = $(api.elements.target[0]);
                $el.qtip('option', 'position.my', $el.data('tooltip-my-position') || 'right center');
                $el.qtip('option', 'position.at', $el.data('tooltip-at-position') || 'left center');
            }
        }
    });
    

    I'll leave this answer here in case it's useful to someone in the future.