Reputation: 14283
I created a website with a sidebar, and everything is working as expected.
Theissue i've got is that i'm trying to close the sidebar when the user clicks on the overlay (or in general, everything that is not a link in the sidebar or the sidebar itself)
here an example of what i've got so far.
I'm basically trying to remove all the relevant classes on overlay click, like this:
function sideBarHandler() {
var body = $('body');
var overlay = $('body.no-scroll:before');
var menu = $('.hamburger');
var bar = $('.leftSidebar');
$(menu).click(function () {
$(body).toggleClass('no-scroll');
$(this).toggleClass('open');
$(bar).toggleClass('visible');
});
$(overlay).click(function () {
console.log(overlay);
$(body).removeClass('no-scroll');
$(menu).removeClass("open");
$(bar).removeClass("visible");
})
};
but it is not working.
Refer to the codepen example above for more code and details.
Thanks for any help.
Upvotes: 1
Views: 210
Reputation: 2550
@adeneo simplified things and it worked, and here's why:
When you were caching $('body.no-scroll') into a local var, it didn't exist at the time. no-scroll was not on body at the time, so when it came to call it in earnest, it had an old, empty jquery DOM reference. In order to fix that you needed to use .on http://api.jquery.com/on/ as adeneo did, from higher up the DOM tree. Note how he specified a selector in the arguments. On() looks at the state of the DOM as you call it and can never be out of date.
Ashkan was also correct, you were double $$-ing. When you have a jquery object set into a JS variable, there is no need to wrap it in $() again.
Good luck!
Upvotes: 1
Reputation: 34152
$(overlay).click(function () {
console.log(overlay);
body.removeClass('no-scroll');
menu.removeClass("open");
bar.removeClass("visible");
});
Upvotes: 0