Reputation: 129
I have a container element that is being loaded multiple times to show variable content on a click event through an Ajax request and upon ajax Complete i have some functions being called including a function (A) inside an if statement.
My problem is when function (A) finally gets called, it gets called multiple times depending on how many times the container had been loaded before the if statement is true.
Here is simple version of my code:
$(".button").on("click", function(){
loadContainer();
});
var loadContainer = function(){
$(".container").load(url, function(){
var x = $(".x");
if(x.length>0){
A();
};
});
};
x
is an element $(".x")
that will be loaded in the container and the function (A) should only be called when that element gets loaded. i.e. $(".x").length>0
if (x.length>0) is true after say 3 times of loading the container then function (A) will be called 3 times then.
is there a way around this or a way to make sure function (A) gets called only once??
Edit: My full code:
ajaxBtn.on("click", function(e) {
loadContainer(url, curtain, mainContainer, body, links);
});
var loadContainer = function(url, curtain, maincontainer, body, links) {
$(".main-container").load(url + " .main-container > *", function() {
$("#logo").css({
"z-index": "400"
});
mainFun();
curtain.removeClass("full");
links.removeClass("here");
body.removeClass("no-scroll");
clearInterval(timer);
getFlexIndex();
position = 0;
if (vidContainer.length > 0) {
youTubeLazyLoad();
}
});
};
please assume that all the variables are already defined.
Upvotes: 1
Views: 1027
Reputation: 171698
It sounds like you are adding the same button click listener numerous times
You should look into how this occurs as there is not enough shown for us to know why. Is it embedded inside another event handler perhaps? Or in a function that gets called numerous times?
A workaround is to remove the click listener before adding a new one
Change
$(".button").on("click"...
to
$(".button").off('click').on("click"...
Upvotes: 1