Browsed by
Month: January 2018

jQuery tooltips using ajax

jQuery tooltips using ajax

So you’ve got some tooltip text you want to show your user, but it’s a bit expensive to generate that text and you only really want to go to the bother of generating it when the user invokes the tooltip.

In my situation this was a bunch of numbers on a page, each of which had been calculated by a particularly long and complicated piece of business logic, and the users need to let the page ‘show its working’ now and again.  On a busy page, the agreed UI solution was to put the detail into a tooltip, but I didn’t want to have to pre-populate every cell with a tooltip, when the users probably wouldn’t bother looking at it at all, and when they did they’d only be interested in one or two cells.  So…

HTML: (on my page this bit is repeated many times)

<span
  class="tooltip"
  title="Default tooltip for when the ajax call fails"
  data-id="${line.someId}">${complicatedNumber}</span>

jQuery:

$("span.tooltip").tooltip({
	content: function( event, ui ) {
		var element = $( this );
		var id = element.attr("data-id");
		var tooltiptext = "Default tooltip";

		// Non-async ajax is deprecated, but we're using it
		// here because  we need to get the tooltip text
		// synchronously so that the response is processed
		// in time.
		$.ajax({
			async:false,
			dataType: 'text',
			url:'/tooltip/rest/' + id,
			type:'get',
			success: function(response) {
				tooltiptext = response;
			}
		});
		return tooltiptext;	   
	}
});