Simple(ish) JQuery Question

Hello. I hope you are all well.

My jQuery/JavaScript skills are fairly limited, and I have written the below code so that when you click the “Contact Us” page (or any page), it slides down after hiding the main page, or any other slide-down pages:

$(“#contactpage”).click(function() {
$(‘.mainpagecontent’).fadeOut(“50000”);
$(‘.whoareyoupage’).hide(“slow”);
$(‘.buynow’).hide(“slow”);
$(‘.questionspage’).hide(“slow”);
$(‘.contactpage’).slideToggle(“slow”);
});

(There is a similar one for the other three slide-downs).

It all works fine to that point, but when you then click “Contact Us” again, it does not bring back the main content. So then I added the below code but this opens the main page and the “Contact Us” element when clicked from another tab (not sure I am explaining myself that well!!)

function contactForm(){
var isOpen = false;

function toggleContactForm() {
if (isOpen) {
$(‘.mainpagecontent’).fadeIn(“50000”);
} else {
$(‘.mainpagecontent’).fadeOut(“50000”);
}
isOpen = !isOpen;
}

$('#contactpage').on('click', toggleContactForm);
$('#whoareyoupage').on('click', toggleContactForm);
$('#buynow').on('click', toggleContactForm);
$('#questionspage').on('click', toggleContactForm);

}

contactForm();

I’m getting myself a bit confused! My site is http://ineedaweatherforecast.co.uk/.

Can anyone help point me in the right direction please?

Thanks
James

1 Like

Every time you go back to contactForm(), you’re re-initializing isOpen to false.

You have basically 3 options. You can store it outside the function and use it for state, but you’re probably not encapulating your code code storing variables globally can be an issue. You can check the current state of the .mainpagecontents, but that’s an array and you’re going to have to treat every one individually. Or you can use jQuery’s .fadeToggle() function.

1 Like

.toggleClass might be a solution?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.