I am having some trouble removing an element created by jQuery in the same function. Here is what is happening:
I have created a jQuery function (toggleClick) that opens up a side panel and then creates an overlay element that is applied to the rest of the page (excluding the panel). What is supposed to happen is after the user clicks on the overlay it will close the panel and also get rid of the overlay element. Am I doing something wrong here?
jQuery Code:
jQuery(document).ready(function(){
/* DEFINE TOGGLECLICK */
$.fn.toggleClick=function(){
var functions=arguments
return this.click(function(){
var iteration=$(this).data('iteration')||0
functions[iteration].apply(this,arguments)
iteration= (iteration+1) %functions.length
jQuery(this).data('iteration',iteration)
})
}
/* DEFINE APANEL ID */
var aPanel = "#aPanel";
/* DEFINE APANEL FUNCTIONALITY */
jQuery('#apanel-fire,#aPanelOverlay').toggleClick(function() {
jQuery("body").addClass("active");
jQuery(aPanel).addClass("active");
jQuery("<div id='aPanelOverlay'></div>").appendTo(".page");
}, function() {
jQuery("body").removeClass("active");
jQuery(aPanel).removeClass("active");
jQuery("#aPanelOverlay").remove();
});
});
The /* DEFINE APANEL FUNCTIONALITY */ is where I am having the issue. Everything else above is defining the toggleClick function and the aPanel variable ID.
You can see a live version of the issue I am having below by clicking on the Menu button located in the top left of the screen.
Live Version:
Thank you so much!
First of all when you call jQuery('#apanel-fire,#aPanelOverlay').toggleClick
the overlay does not exist, as it is attached later. So it has no click handler and does not react to any click.
Second (which does not really matter anymore ;) return this.click(function(){
would attach a click handler to each element. jQuery(this).data('iteration',iteration)
would store the iteration
on #apanel-fire
on the first click. When you would now click on the overlay, its iteration
would still be 0. So the first function would be called again.
Update: a very simple solution
function showOverlay() {
jQuery("body").addClass("active");
jQuery(aPanel).addClass("active");
jQuery("<div id='aPanelOverlay'></div>").appendTo(".page").click(hideOverlay);
}
function hideOverlay() {
jQuery("body").removeClass("active");
jQuery(aPanel).removeClass("active");
jQuery("#aPanelOverlay").remove();
}
jQuery('#apanel-fire').click(showOverlay);