My objective is fairly simple. In my webapp, I have two pages and I want to call each one from the other page.
But the way I have implemented the function calls in Javascript seems to be flawed. I have read up on closure, bubbling, recursion and event.stopPropagation(), but still not sure what the right way to go about implementing this.
Here’s the smallest code that I could reproduce my problem in.
function init(){
var $div1 = 'Click to Load page 2';
$("#main").append($div1);
var $div2 = 'Click to go back to page 1';
$("#main").append($div2);
displayFirstPage();
}
function displayFirstPage() {
var $div1 = $("#div1");
var $div2 = $("#div2");
$div2.hide();
$div1.show();
alert("first called");
$div1.click(function(){
displaySecondPage();
});
}
function displaySecondPage() {
var $div1 = $("#div1");
var $div2 = $("#div2");
alert("second called");
$div1.hide();
$div2.show();
$div2.click(function(){
displayFirstPage();
});
}
After clicking the divs a few times, I end up with numerous alert’s popping up. I just want each call to be executed once. Clearly, I am missing the way to terminate the function call.
Any help appreciated.
Your
and
should be inside your
init()function. Every time you call those you are adding another click handler to the div. You only want to add them once, so just put them ininit().