Friday, March 18, 2016

close div when clicked outside the div area

Leave a Comment

I have this piece of code.I am trying to close the div,when clicked outside the Div,I have searched through this forum but can not find a solution -Here is a fiddle- Demo

$('#hideshow1').on("click", function() {     var text = $(this).val();     $("#req").toggle();  });  $(window).on("click keydown", function(e) {   //e.preventDefault() /*For the Esc Key*/   if (e.keyCode === 27 || !$(e.target).is(function() {return $("#req, #hideshow1")})) {     $("#req").hide()   } }).focus() 

4 Answers

Answers 1

Div req width is 100% of screen. The frame width is the same as the border.

$('#hideshow1').on("click", function() {    if ($("#frame").is(":visible") == false) {      $("#frame").show();    }    $('#hideshow1').text("Click outside div to hide it.");  });  $(document).mouseup(function(e) {    var container = $("#frame"); //Used frame id because div(req) width is not the same as the frame     if ($("#frame").is(":visible")) {      if (!container.is(e.target) //check if the target of the click isn't the container...        && container.has(e.target).length === 0) {        container.hide();        $('#hideshow1').text("Click to see div");      }    }  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>  <div id="clickme">    <a class="req_pic_link" id="hideshow1">Click outside div to hide it.</a>  </div>  <div id="req">    <iframe id="frame" src="https://www.google.com"></iframe>  </div>

Answers 2

Please check this out.

$('html').click(function() {   $("#req").hide();   // add some code });  $('#clickme').click(function(event) {   event.stopPropagation();   // add some code }); 

Test code here jsfiddle

Answers 3

The function argument for .is() is used to test every element in the set, and needs to return a boolean value as to whether the element matches or not - it should not return a jQuery collection.

However for what you are trying to do you should only pass a selector instead of a function to .is() like this:

if (e.keyCode === 27 || !$(e.target).is("#req, #hideshow1")) {     $("#req").hide() } 

Here is a working jsFiddle. (Note that it won't work if you click to the right of the div, but that is because you are still clicking on #req because it doesn't have a specified width.)

Answers 4

You need to add click event to the document and check that clicked target and any of it parent don't have required class:

$(document).on('click', function (e) {    var divClass = 'my-class';    if (!$(e.target).hasClass(divClass) && !$(e.target).parents().hasClass(divClass)) {      // do something...    }  });

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment