click anywhere to close div inside and outside - javascript

This is a jscript to close the window when someone clicks anywhere outsite the Div to close.
my question is to make this window close when someone clicks on this by performing the action.
<div id="box"
style="height: 3em; position:absolute; top: 20%; left: 15%; border: 3px double">
<p>Click anywhere outside this box to close it.
</div>
<script>
document.onclick = function (e) {
e = e || event
var target = e.target || e.srcElement
var box = document.getElementById("box")
do {
if (box == target) {
// Click occured inside the box, do nothing.
return
}
target = target.parentNode
} while (target)
// Click was outside the box, hide it.
box.style.display = "none"
}
</script>
How to make a Div close when the click was occurred inside the DIV

In your HTML code itself,
<div id='box' style='height:10px; width:10px' onclick='CloseMe(this)'>...</div>
Implement the CloseMe function
function CloseMe( obj )
{
obj.style.display = 'none';
}

For the specific thing talking here, I didn't test it but I think change that loop to the following code could make it.
do {
if (box != target) {
// Click occured outside the box, do nothing.
return
}
target = target.parentNode
} while (target)

If you use JQuery you can use the event.stopPropagation(); on the click function for you div
$(function(){
$('html').click(function() {
$('#box').hide();
});
$('#box').click(function(event){
event.stopPropagation();
});
});
http://jsfiddle.net/nCqwy/1/

Related

how to close created div by clicking outside of it?

I have a div that is created on a button pressed and I'm trying to have it deleted by clicking outside of it but it takes the original button press as clicking outside and immediately closes the div.
closediv();
}
function closediv() {
document.addEventListener("click", (evt) => {
const maindiv = document.getElementById('div3');
let targetElement = evt.target;
do {
if (targetElement == maindiv.childNodes[1]) {
return;
}
targetElement = targetElement.parentNode;
} while (targetElement);
var viewpost = maindiv.childNodes[1];
viewpost.parentNode.removeChild(viewpost);
});
}
In your button click handler, you could use
theButton.addEventListener("click", function(ev) {
ev.stopPropagation();
// rest of the code
});
and the click event would not propagate to the parent containers.
just add a click event on body to close your div and then add prevent default into your div to block closing action when user click on your div
document.body.addEventListener('click', (e) =>{
//close your div here
})
document.addEventListener("click", (evt) => {
evt.preventDefault()
// your code
}

js test if clicked element is child/descendent of

I want to test if a click is on an element within a specific hierarchy.
Using:
var elements = parentElement.getElementsByTagName("*");
I can put all elements into array, but then I can't get the test right:
function isClicked(e){
if(elements.indexOf(e.target) != -1){
//do something
}
};
How do I do this correctly, please? Thanks...
(PS I am trying to create a click-away function where clicking upon anything in the body except the displayed info will close it)
Use Node.prototype.contains:
var button = document.querySelector('button');
var dialog = document.querySelector('.dialog');
button.addEventListener('click', function () {
dialog.classList.add('open');
});
document.body.addEventListener('click', function (e) {
if (button !== e.target && dialog !== e.target && !dialog.contains(e.target)) {
dialog.classList.remove('open');
}
});
.dialog:not(.open) {
display: none;
}
.dialog {
background-color: yellow;
}
span {
color: red;
}
<button>Open dialog</button>
<div class="dialog">
<h1>Hello, World!</h1>
<p>Hello, World! <span>Nested element<span></p>
</div>
<p>Click somewhere here to close the dialog! <span>Nested element</span></p>
Try to following:
function isClicked(e){
//check e.currentTarget.children()
};
You could use the Underscore's contains function. So, your condition should be in that case:
if (_.contains(elements, e)) {
// ...
}

javascript execute function pressing 'esc' key

I have 2 javascript functions: one of them shows div 'PhotoFull' another hides. 'PhotoFull' is a container Div.. Just black background for another Div inside of it. When the user clicks on black background, PhotoFull dessapears.. but if affects also the Div which is inside of 'PhotoFull' (PhotoFull dessapears while clicking the div which is inside). So For the Div which is inside I use event.stopPropagation();
Both functions work, but I also need to hide Div hideDiv() when "ESC" key is pressed. hideDiv() is executing Div
function showDiv() {
document.getElementById('PhotoFull').style.display = "inherit";
event.stopPropagation();
}
function hideDiv() {
var target = event.target || event.srcElement;
if (event.currentTarget == target) {
document.getElementById('PhotoFull').style.display = "none";
}
}
window.onload=function() {
document.onkeyup = key_event;
}
function key_event(e) {
if (e.keyCode == 27) hideDiv();
}
And HTML:
<div id="PhotoFull" style="position: absolute; width: 100%; height: 100%; background-color: rgba(0,0,0, 0.75); display:none; z-index: 999;" onclick="hideDiv()">
<div style="width: 960px; border-radius: 3px; background-color: #ffffff; margin-top: 100px;">
<img id="one_full" src="numbers/1.jpg" style="max-width: 940px; margin: 10px;" />
</div>
</div>
Without event.stopPropagation(); Pressing ESC button executes function hideDiv() but with it, nothing happens. Don't know why.
Thanks for attention
When you press Esc key it goes in hideDiv function but the condition goes worng due to below reason.
See Debug trace in picture.
See watchExpression section in debugger. I have added event object to watch.
You can see full object description in watchExpression in above image.
You have write below condition in hideDiv function
var target = event.target || event.srcElement;
if (event.currentTarget == target) {
document.getElementById('PhotoFull').style.display = "none";
}
in debug trace you can see that event.currentTarget is body target local variable in the hideDiv function is document because you have added your listener for document object canbe seen from your code
window.onload=function() {
document.onkeyup = key_event;
}
So the solution is you have to register event listener on proper object which is body.
use below code for window.onload function..
window.onload=function() {
document.body.onkeyup = key_event;
}
window.onkeypress = keypress;
function keypress(event) {
if (event.keyCode == 27) {
alert("Hidding div *magic runing...*");
}
}
You should consider using onkeypress event to handle it.
Try this,
document.onkeydown=function(e){
if(e.which == 27) {
hidediv();
return false;
}
}

How to manage events on a specific div?

I would like to catch some events for a specific div if the user clicked on the div (focus the div), keyboard events are catch (not if the last click was out of the div (unfocus the div)
I tried some things, but haven't succeeded : JSFiddle
document.getElementById("box").onkeydown = function(event) {
if (event.keyCode == 13) { // ENTER
alert("Key ENTER pressed");
}
}
This code doesn't work even if I click on the div.
Pure JS solution please
The div element isn't interactive content by default. This means that there isn't a case where the return key will ever trigger on it. If you want your div element to be interactive you can give it the contenteditable attribute:
<div id="box" contenteditable></div>
In order to now fire the event you need to first focus the div element (by clicking or tabbing into it). Now any key you press will be handled by your onkeydown event.
JSFiddle demo.
Giving the 'div' a tabindex should do the trick, so the div can have the focus:
<div id="box" tabindex="-1"></div>
If you click on the div it gets the focus and you can catch the event.
JSFIDDEL
If you set 'tabindex' > 0 you can also select the div using TAB.
You could catch all the click events, then check if the event target was inside the div:
var focus_on_div = false;
document.onclick = function(event) {
if(event.target.getAttribute('id') == 'mydiv') {
focus_on_div = true;
} else {
focus_on_div = false;
}
}
document.onkeyup = function(event) {
if (focus_on_div) {
// do stuff
}
}
try this code i hope this work
var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
}, false);
window.onkeydown = function(event) {
var x = mousePosition.x;
var y = mousePosition.y;
var elementMouseIsOver = document.elementFromPoint(x, y);
if(elementMouseIsOver.id == "box" && event.keyCode == "13") {
alert("You Hate Enter Dont You?");
}
}
DEMO

After initial click, have to click twice with Jquery click()

Couldn't find a solution that actually worked, but I want that on a click, a div shows.
Now this works when I load the page, but then after that first click, I have to click twice every time for the div to show.
Any ideas?
$(document).ready(function () {
setMenu();
});
function setMenu()
{
var headerExtIsOpen = false;
$('#headerExt').hide();
$('#header').click(function () {
if (!headerExtIsOpen) {
$('#headerExt').show();
headerExtIsOpen = true;
} else {
$('#headerExt').hide();
headerExtIsOpen = false;
}
});
}
There is no need to remember the state, just use toggle()
$(function () {
setMenu();
});
function setMenu()
{
$('#headerExt').hide();
$('#header').on("click", function (e) {
e.preventDefault();
$('#headerExt').toggle();
});
}
You said you want to toggle other things.
Best thing would be to toggle a class to change the color
$('#header').on("click", function (e) {
e.preventDefault();
$(this).toggleClass("open");
$('#headerExt').toggle();
});
another way is to check the state
$('#header').on("click", function (e) {
e.preventDefault();
var child = $('#headerExt').toggle();
var isOpen = child.is(":visibile");
$(this).css("background-color" : isOpen ? "red" : "blue" );
});
if the layout is something like
<div class="portlet">
<h2>Header</h2>
<div>
<p>Content</p>
</div>
</div>
You can have CSS like this
.portlet h2 { background-color: yellow; }
.portlet > div { display: none; }
.portlet.open h2 { background-color: green; }
.portlet.open > div { display: block; }
And the JavaScript
$(".portlet h2 a").on("click", function() {
$(this).closest(".portlet").toggleClass("open");
});
And there is layouts where it would be possible to have zero JavaScript involved.
Turns out I had some script hidden in my .js file that closes the menu again when the user clicks elsewhere, that I forgot about.
function resetMenu(e) {
var container = $('#headerExt');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$('#header').css("background-color", "inherit");
container.hide();
headerExtIsOpen = false;
}
}
I forgot to set the headerExtIsOpen back to false again after closing it in this function (code above shows the fix). Now it works fine :)

Categories

Resources