Alejandro Espinel
Alejandro Espinel

Reputation: 91

How can I subtract pixels from offset value?

I have the following:

setTimeout(function() {
  $(".htmltooltip").click(function() {
    var tooltip_content = $(this).attr("data-tooltip-content");
    var pos = $(this).offset();
    var top = pos.top;
    var left = pos.left;
    $("body").append(function() {
      $(this).append('<div style="top:' + top + 'px !important;left:' + left + 'px !important;" class="htmltooltip_content">' + tooltip_content + '</div>');
    });
  });
}, 100);

But I would like to subtract 60 pixels from pos.top and 70 pixels from pos.left

Is there a way I can do that? Any help is appreciated, thank you in advance!

Upvotes: 0

Views: 1734

Answers (1)

Cymen
Cymen

Reputation: 14429

You can simply subtract the desired amount of pixels. jQuery .offset() returns an object with numeric values:

{top: 20, left: 30}

So simply change the append line to this:

   $("body").append(function() {
      $(this).append('<div style="top:' + (top - 60) + 'px !important;left:' + (left - 70) + 'px !important;" class="htmltooltip_content">' + tooltip_content + '</div>');
    });

Although I would suggest keeping it cleaner like this:

setTimeout(function() {
  $(".htmltooltip").click(function() {
    var tooltip_content = $(this).attr("data-tooltip-content");
    var pos = $(this).offset();
    var top = pos.top - 60;
    var left = pos.left - 70;
    $("body").append(function() {
      $(this).append('<div style="top:' + top + 'px !important;left:' + left + 'px !important;" class="htmltooltip_content">' + tooltip_content + '</div>');
    });
  });
}, 100);

Upvotes: 1

Related Questions