user1896653
user1896653

Reputation: 3327

How to close an expanded div by clicking outside with calling click function for close event

Well, there are lots of solution for this kinds of problems at here. But, my problem is I am not allowed to edit existing functionality. The existing functionality is:

$('body').on('click', '.parent.normal', function () {
  // code for Expanding a div
});

and

$('body').on('click', '.parent.expand', function () {
  // code for Closing expanded div
});

What I can do is defining another click function for clicking outside of the expanded div which will call the existing click event for closing expanded div. To do that, I have written this:

  if($('.parent.expand').length > 0) {
    $('div:not(".parent.normal, .expanded-content, .expanded-content > div")').click(function () {
      $('.parent.expand').click();
    });
  }

Which is not working actually. How can I make it working?

Fiddle Demo

Upvotes: 0

Views: 237

Answers (3)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

Adding this to your existing code must fix the issue.

$(document).on('click',function(e){   
  if (!$(e.target).parents('.content').length > 0){
     $('.parent.expand').click();
  }
});

Here is a working Fiddle

Upvotes: 1

Chris
Chris

Reputation: 783

This will do it without making any changes in existing functions:

$(document).mouseup(function (e) {

   var elem_not = $(".parent.normal, .parent.expand, .expanded-content, .expanded-content > div");

   if (!elem_not.is(e.target) && elem_not.has(e.target).length === 0) {
       $('.parent.expand').click();
   }

});

Updated your FIDDLE

Upvotes: 1

bastos.sergio
bastos.sergio

Reputation: 6764

You need to edit your css so that your body has 100% width and 100% height. This will create an area for your click events to register outside of the div.

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

And then use this javascript:

// open expand content
$('body').on('click', '.parent.normal', function (e) {
  e.stopPropagation();
  e.preventDefault();
  $(this).removeClass('normal');
  $(this).addClass('expand');
  $(this).parent().find('.expanded-content').slideDown(300);
});

// close expand content
$('body').on('click', '.parent.expand', function (e) {
  e.stopPropagation();
  e.preventDefault();
  $(this).removeClass('expand');
  $(this).addClass('normal');
  $(this).parent().find('.expanded-content').slideUp(300);
});

$('body').on('click', function (e) {
  e.stopPropagation();
  e.preventDefault();
  $('.parent.expand').click();
});

Fiddle demo

Upvotes: 0

Related Questions