Search code examples
jquery-uijquery-tooltip

Change content in tooltip dynamically


Here I have this code:

 $(function() {
    $( document ).tooltip({
      items: ".draggable ui-draggable ui-resizable",
      track: true,
      content: function(){
      var time = $( this ).width();
      if(time<0) {
    time = 0;
}

var seconds = time%60;
var minutes = (time-seconds)/60;
var output;

if(minutes >= 10) {
    output = ""+minutes;
} else {
    output = "0"+minutes;
}
output += ":";
if(seconds >= 10) {
    output += seconds;
} else {
    output += "0"+seconds;
}

return output;
      }
    });
  });

.draggable class is also draggable and resizable, and I need to show dynamically changed content in tooltip (time hh/min)

How I can dynamically change content in a tooltip?

Demo: http://jsbin.com/erofot/119

Why tooltip content won't to change dynamically when I resize the div ?


Solution

  • The problem is that the content is only updated everytime the tooltip shows. You need to update the content every time the div is resized.

    Create a function for updating the contents as follows:

    function updateTooltipContent() {
        var time = $(this).width();
        if (time < 0) {
            time = 0;
        }
    
        var seconds = time % 60;
        var minutes = (time - seconds) / 60;
        var output;
    
        if (minutes >= 10) {
            output = "" + minutes;
        } else {
            output = "0" + minutes;
        }
        output += "h ";
        if (seconds >= 10) {
            output += seconds;
        } else {
            output += "0" + seconds;
        }
    
        return output + "min";
    }
    

    In your .resizable initialization, set the resize argument to updateTooltipContent as follows:

    // 3 make the clone resizable
    .resizable({
    resize: function(event, ui) {
        var $this = $(event.currentTarget);
        $this.tooltip('option', 'content', updateTooltipContent);
    }
    

    Finally, in your tooltip initialization, set content to updateTooltipContent as follows:

    $(function () {
        $(document).tooltip({
            items: ".draggable",
            track: true,
            content: updateTooltipContent
        });
    });
    

    Edit: Check out this fiddle.