The Gmo
The Gmo

Reputation: 274

Slide Menu - Click div to close not working on a certain div

I'm trying to build a slide menu that (a) opens, places a white faded overlay over the rest of the page and (b) closes when I click a link in the menu or when I click anywhere the white overlay.

(a) this works fine. (b) Here is where I have the problem. I get the menu to close on a link in the menu, and on the cross icon.

I don't get it to close on the appended div.

That's the jQuery (which surely could be smoother somehow).

$(".menu").click( function (){
  $('.slide-menu').slideDown();
  if ( $('#container').hasClass('with-overlay') ) {
    $('.bg-overlay').show();
  }
  else {
    $('#container').prepend('<div class="bg-overlay"></div>').addClass('with-overlay');  
  }
});

$(".close-trigger").click( function (){
  $('.slide-menu').slideUp();
  $('.bg-overlay').hide();
});

$(".bg-overlay").click( function (){
  $('.slide-menu').slideUp();
  $('.bg-overlay').hide();
});

What am I missing?

Upvotes: 1

Views: 99

Answers (2)

Gideon Pyzer
Gideon Pyzer

Reputation: 23978

Your overlay does not exist in the DOM when you register the click handler. You can add event handlers to dynamically created elements by using on with a base container that exists already.

$(document).on('click', '.bg-overlay', function () {
    $('.slide-menu').slideUp();
    $('.bg-overlay').hide();
});

Upvotes: 0

Eugene Hauptmann
Eugene Hauptmann

Reputation: 1279

http://plnkr.co/edit/NtGGqpC41ycD2x7FL8wX?p=preview

You forgot that you dynamically create the overlay, therefor you need to add event listener

function hide(){
    $('.slide-menu').slideUp();
    $('.bg-overlay').hide();
}

$(".menu").click( function (){
  $('.slide-menu').slideDown();
  if ( $('#container').hasClass('with-overlay') ) {
      $('.bg-overlay').show();
  }
  else {
    $bgOverlay = $('<div class="bg-overlay"></div>');
    $bgOverlay.click(hide);
    $('#container')
    .append( $bgOverlay )
    .addClass('with-overlay');
  }
});

$(".close-trigger").click(hide);

Upvotes: 1

Related Questions