I'm using bootstrap 3.0 to display a tooltip (this example isn't specific to boot-strap) where the html inside the tooltip is fed from an AJAX call. In the future I want to be able to use the same element to fire different AJAX calls (something like fire a different AJAX call if the shift+click was used). To make that easy, I decided to use a tooltipManager
object. This object currently has two properties:
- title: in bootstrap, this is the html represented when an element is hovered over
- placement: the values for this are left,right,top,bottom
EDIT: I just got the program working, but I need to know WHY it's working because I tried something like this for hours and had nothing but bad luck. Why is setPlacement
able to return the correct value?
$(document).ready(function () {
//in the future there will be n amount of these
//each will have the ability to use different urls to make different AJAX calls (not implemented yet)
var tooltipManager = {
title: function () {
//ajax code to get title from database
$.ajax({
type: "POST",
contentType: "application/json",
url: "Service.asmx/GetDrugs",
dataType: "json",
success: function (data) {
//bootstrap uses the title attribute to set the html inside the tooltip
//here it's set to the results of the AJAX
$('#click').attr('title', data.d)
.tooltip({
trigger: 'click',
html: false,
//using the sizer function the tooltip is placed where it needs to be.
placement: tooltipManager.placement.setPlacement(data.d)
//it seems to me that it would be better design to call the tooltipManager
//setPlacement function, but since it's an async request, it fails
}).click();
},
error: function (xhr) {
console.log('failed: ' + xhr.status);
}
});
},
placement: {
left: 'left',
top: 'top',
right: 'right',
bottom: 'bottom',
setPlacement: function (data) {
if (data.length > 4) {
return this.bottom;
}
else {
return this.right;
}
}
}
}
$('#click').one('click', function () {
//how can I pass the entire state of the object here, instead of invoking these methods one by one.
tooltipManager.title();
});
//not sure if this is good design to have this not a property of the tooltipManager object
//this works currently for placing the tooltip in the correct position
function sizer(data) {
if (data.length > 4) {
return tooltipManager.placement.bottom
}
else {
return tooltipManager.placement.right
}
}
});