I call function from this code :
<div id="header-button-news" class="header-button-info">
<a href="javascript:;" title="Новости" onclick="showNews()"></a>
<div class="new">2</div>
</div>
My function is
function showNews()
{
//other js which show block
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
}
How can I make only once ajax call? so when content is loaded and page was not refresed not to load ajax? I tried to do boolean variables but nothing, I suppouse it is because I call everytime function. Please give me an idea how to do.
thank you
When you want to do something on that event.
Identify when you have already loaded your data.
var loaded = false;
function showNews() {
//other js which show block
jQuery("#loader").show();
if(loaded) return;
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
loaded = true;
}
Or use one.
when you want to call it once.
<a href="javascript:;" title="Новости" onclick="showNews()" class="showNews"></a>
jQuery('.showNews').one('click', function() {
// your code
});
"Attach a handler to an event for the elements. The handler is executed at most once per element."
reference
Use the .one()
function :
Attach a handler to an event for the elements. The handler is executed at most once per element.
<a href="#" title="Новости" id="shownews"></a>
I have added an id
attribute to the anchor to allow an easier bind, but you could use $("#header-button-news a").one
$(document).ready(function () {
$('#shownews').one('click', function (evt) {
evt.preventDefault(); // prevent default click action
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function (data) {
jQuery('#top-info-news').html(data);
},
complete: function () {
jQuery('#loader').hide();
},
});
});
});
Also used event.preventDefault()
to prevent the default action on the anchor from being followed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With