Positioning of jQuery tooltip

Viewed 91

I´m using the jQuery UI tooltip plugin.

How can I change the tooltip position depending on the windows´ resolution?

At the moment I still need to reload the browser so the script takes effect. It can´t adjust the position in real time when changing the browser windows´ size

var res = $(window).width();
var arr = {};
if(res < 960){
  arr = {my: "left+3 bottom-3", of: event, collision:"fit"};
}else{
  arr = {my: "left+153 top+20", collision: "flipfit" };    
}

init_tooltip(arr);

function init_tooltip(param){
  $('*[data-id]').tooltip({
      tooltipClass: "tooltipitem",
      content: '<div class="loading">Laden...</p>',
      hide: {
        effect: "slideData",
        delay: 0
      },
      position: arr,
  });
}

$('*[data-id]').hover(function (event, ui) {

            let $tooltip = $(this);
            let id = $tooltip.attr("data-id");

            ajaxManager.add({
                url: "../datenbank/itemscript.php",
                type: "GET",
                cache: "true",
                data: {
                    "var": id
                },

                success: function (data) {

                    console.log(data);

                    $tooltip.tooltip({
                        content: data
                    });
                }
            });
        });
1 Answers

You could use ternary operator:

var res = $(window).width();

$('*[data-id]').tooltip({
    tooltipClass: "tooltipitem",
    content: '<div class="loading">Laden...</p>',
    hide: {
        effect: "slideData",
        delay: 0
    },
     position: (res < 960 ? {my: "left+3 bottom-3", of: event, collision:"fit"} : { my: "left+153 top+20", collision: "flipfit" }),
});

or classic if else

var res = $(window).width();


function init_tooltip(param){
  $('*[data-id]').tooltip({
      tooltipClass: "tooltipitem",
      content: '<div class="loading">Laden...</p>',
      hide: {
        effect: "slideData",
        delay: 0
      },
      position: param,
  });
}

to trap the change of window width:

$(window).resize(checkWidth);

checkWidth();

function init_tooltip(param){
  $('*[data-id]').tooltip({
      tooltipClass: "tooltipitem",
      content: '<div class="loading">Laden...</p>',
      hide: {
        effect: "slideData",
        delay: 0
      },
      position: param,
  });
}


function checkWidth(){
    var res = $(window).width()
    var arr = {};
    if(res < 960){
      arr = {my: "left+3 bottom-3", of: event, collision:"fit"};
    }else{
      arr = {my: "left+153 top+20", collision: "flipfit" };    
    }

    init_tooltip(arr);

}
Related