Ralph David Abernathy Ralph David Abernathy - 2 months ago 22
CSS Question

How to (re)initialize tooltip with different options depending on screen size?

So I'm using the tooltipster.js library for tooltips and trying to change the default distance of the tooltip on different screen sizes.

So here is how the default init looks:

$(inputTooltipTrigger).tooltipster({
distance: 24,
theme: 'test',
trigger: 'custom'
});


If the window width is greater than 641px, then the distance changes to 6

if ($(window).width() > 641){
$(inputTooltipTrigger).tooltipster({
distance: 6,
theme: 'test',
trigger: 'custom'
});
}


If the window is resized and then is greater than 641px, then the distance changes to 6

$(window).resize(function(){
if ($(window).width() > 641){
$(inputTooltipTrigger).tooltipster({
distance: 6,
theme: 'test',
trigger: 'custom'
});
}
});


How can I get the plugin to reinitialize on resize and if the window width is greater than 641px? I tried using CSS, but I would have to use the
!important
flag to override the inline JS generated by the tooltip plugin, which is frowned upon.

Answer

I would try to write it all as one jQuery function:

jQuery(function($){
    if ($(window).width() >= 641){
        $(inputTooltipTrigger).tooltipster({
            distance: 6,
            theme: 'test',
            trigger: 'custom'
        });
    }
    $(window).resize(function () {
        if ($(window).width() >= 641) {
            $(inputTooltipTrigger).tooltipster({
                distance: 6,
                theme: 'test',
                trigger: 'custom'
            });
        }
    });
});