Reputation: 231
I have an AJAX call for when a user clicks on some navigation links. The call updates the content of the page and the URL gets updated to the corresponding link of the resource, where the content is stored.
My problem is the more times a user clicks a link, the "swapContent()" function is being recursively called more and more times per click.
For example if I clicked the link for say "page 2", the function would be called once, then if I clicked back to the home page, the function is called 2 or 3 times, and so on...
Would anyone be able to point out why this might be?
function supports_history_api() {
return !!(window.history && history.pushState);
}
function swapContent(href) {
var req = new XMLHttpRequest();
req.open("GET",
"http://localhost/portfoliowebsite/PHP/" +
href.split("/").pop(),
false);
req.send(null);
if (req.status == 200) {
document.getElementById("homeContBox").innerHTML = req.responseText;
setupHistoryClicks();
return true;
}
return false;
}
function addClicker(link) {
link.addEventListener("click", function(e) {
if (swapContent(link.href) == true) {
history.pushState(null, null, link.href);
e.preventDefault();
}
}, true);
}
function setupHistoryClicks() {
addClicker(document.getElementById("home"));
addClicker(document.getElementById("cv"));
addClicker(document.getElementById("port"));
addClicker(document.getElementById("contact"));
}
window.onload = function() {
if (!supports_history_api()) { return; }
setupHistoryClicks();
window.setTimeout(function() {
window.addEventListener("popstate", function(e) {
alert("");
swapContent(location.pathname);
}, false);
}, 1);
}
Upvotes: 1
Views: 56
Reputation: 681
Problem is in setupHistoryClicks():
addClicker(link) keeps adding event listeners, hence you will be adding more executions to the link each time it loads content.
And consequently you will be executioning more clicks.
Upvotes: 3