Reputation: 25842
to sum it up quickly.. I have a jQuery tooltip on one of my table elements with a specific data attribute to select it. it works great, makes an ajax request, returns data and puts it in the tooltip. only problem is every time i mouse over the table element the ajax request gets triggered again.
$('p').tooltip({
items: "[data-whatever]",
content: function(){
var el = $(this),
content = el.data('ajax-content');
if(content)
return content;
return 'waiting for ajax';
},
open: function(){
var elem = $(this),
id = elem.data('whatever');
$.ajax('/echo/html/' + id).always(function(res) {
elem.tooltip('option', 'content', res[0].label);
elem.data('ajax-content', res[0].label);
});
}
});
all of this works fine ( i made a few changes to the code so its not identical to what i did because its incorporated into my works module pattern).. but is there a simple way to only hit the open function one time?
any help would be appreciated!
Upvotes: 0
Views: 803
Reputation: 5222
Try this, store ajax response in element data, now check in open event if tooltip exists in data, if yes show it else cal ajax.
$('p').tooltip({
items: "[data-whatever]",
content: function(){
var el = $(this),
content = el.data('ajax-content');
if(content)
return content;
return 'waiting for ajax';
},
open: function(){
if($(this).data("ajax-content") == undefined) {
var elem = $(this),
id = elem.data('whatever');
$.ajax('/echo/html/' + id).always(function(res) {
elem.tooltip('option', 'content', res[0].label);
elem.data('ajax-content', res[0].label);
});
}
else {
$(this).tooltip('option', $(this).data("ajax-content"));
}
}
});
Upvotes: 1
Reputation: 451
You can check if 'ajax-context' data is already set. If so do not trigger the ajax request.
$('p').tooltip({
items: "[data-whatever]",
content: function(){
var el = $(this),
content = el.data('ajax-content');
if(content)
return content;
return 'waiting for ajax';
},
open: function(){
var elem = $(this),
label = elem.data('ajax-content');
if (label) {
elem.tooltip('option', 'content', label);
} else {
var id = elem.data('whatever');
$.ajax('/echo/html/' + id).always(function(res) {
elem.tooltip('option', 'content', res[0].label);
elem.data('ajax-content', res[0].label);
});
}
}
});
Upvotes: 1