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()
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>
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With