javascript execute function pressing 'esc' key - javascript

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;
}
}

Related

Adding keyboard arrow navigation to custom js

I am using wordpress and my content looks like this
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/2/"><img src="blah1.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/3/"><img src="blahab.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/4/"><img src="blahco.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/5/"><img src="blahneat.jpg" alt=""/></a></div>
I have a custom javascript that loads the next image when the user clicks on the image. Now I want to add left & right keyboard arrow navigation to this script and I don't know how I can I implement to it since I'm not familiar with javascript.
$('body').on('click', '.image-wrap', function(e) { // listen for 'click' on our '.image-wrap' element
e.preventDefault(); // Prevents default behavior on the a element
$.ajax({
url: $(this).find( 'a' ).attr( 'href' ), // the url we are fetching by ajax
success: function (response) {
newImg = $(response).find('.image-wrap').html(), // get the new href link and image from the response, contained in div.image-wrap
$( 'div.image-wrap' ).html( newImg ); // set the new html for our inner div
}
}).fail(function (data) {
if ( window.console && window.console.log ) {
console.log( data ); // log failure to console
}
});
});
EDIT:
By pressing the right arrow key I want it to click the ajax link that is inside image-wrap div which should load the next image. If pressing the left arrow key it should go back to the previous image. Any idea how to do this?
You can use mousetrap.
function GoToLocation(url)
{
window.location = url;
}
Mousetrap.bind("right", function() {
document.getElementById('next-image').click();
});
<script src="https://craig.global.ssl.fastly.net/js/rainbow-custom.min.js?39e99"></script>
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.js?bc893"></script>
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/2/"><img src="blah1.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/3/"><img src="blahab.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/4/"><img src="blahco.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/5/"><img src="blahneat.jpg" alt=""/></a></div>
if you are use attachment.php or image.php based gallery. you can also use this : Wordpress Attachment Page Navigate with Keyboard
You need to bind a handler to the document keyup event, and test the key code for the event. A handy reference to key codes: https://css-tricks.com/snippets/javascript/javascript-keycodes/
Below is an example. When you run it, click in the output panel to give it focus before testing the keys.
var selectedIndex = 0;
var elements = $('.navigable').toArray();
var maxElements = elements.length;
function nextSelection() {
selectedIndex++;
if(selectedIndex >= maxElements) {
selectedIndex = 0;
}
selectElement();
}
function prevSelection() {
selectedIndex--;
if(selectedIndex < 0) {
selectedIndex = maxElements - 1;
}
selectElement();
}
function selectElement() {
$('.navigable').removeClass('selected');
$(elements[selectedIndex]).addClass('selected');
}
handleKeyUp = function(ev) {
if(ev.keyCode == 37) { // left arrow key
prevSelection();
}
if(ev.keyCode == 39) { // right arrow key
nextSelection();
}
if(ev.keyCode == 27) { // escape key
$(document).off('keyup', handleKeyUp);
}
}
$(document).on('keyup', handleKeyUp);
selectElement();
div {
padding: 30px;
margin: 10px;
border: 1px solid #aaa;
background: #fee;
display: inline-block;
}
div.selected {
background: #faa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navigable">1</div>
<div class="navigable">2</div>
<div class="navigable">3</div>
<br>
<br>
<p> Click in this panel to give it focus. Use arrow keys to navigate between divs. Press `ESC` to disable `keyup` handler.</p>

Two functions on Keypress won't work (textarea)

I have created two function on Enter Key press
to hide show dive on Enter key press
to auto resize textarea Height on Enter when it reached to end.
Here is the fiddle : http://jsfiddle.net/rz3f3gng/2/
$('.one').hide();
$(function() {
//hide show dive on enter press and on other keys hide div
$('#mainContent').on('keypress', function(e) {
if (e.which == 13) {
e.preventDefault();
$('.one').show();
} else {
$('.one').hide();
}
});
function TextareaAuto(o) {
o.style.height = "200px";
o.style.height = (2 + o.scrollHeight) + "px";
}
});
.one {
width: 100px;
height: 30px;
background: red;
}
textarea {
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="one">
</div>
<textarea id="mainContent" onkeydown="TextareaAuto(this)" style="overflow:hidden">
</textarea>
Only One function seems to work at time, either Hide show div or auto size textarea.
You should never mix inline event handlers with jQuery handlers. Just use two jQuery handlers or call the function from the existing handler:
e.g.
$('#mainContent').on('keypress', function(e){
if (e.which == 13) {
e.preventDefault();
$('.one').show();
}
else{
$('.one').hide();
}
TextareaAuto(this);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/rz3f3gng/3/
Update
As you still want the Enter to work (see comment below), just get rid of your e.preventDefault()
e.g.
$('#mainContent').on('keypress', function(e){
if (e.which == 13) {
$('.one').show();
}
else{
$('.one').hide();
}
TextareaAuto(this);
});
http://jsfiddle.net/TrueBlueAussie/rz3f3gng/4/
Which now means it can be reduced using toggle() to
$('#mainContent').on('keypress', function(e){
$('.one').toggle(e.which == 13);
TextareaAuto(this);
});
http://jsfiddle.net/TrueBlueAussie/rz3f3gng/5/

Eventlistener for an input "form"?

Here is a common problem I have no good way to handle:
On a web page I display an input form when a button is clicked. Behind the form I put a background that dim the page:
var bgDiv = document.createElement("div");
var formDiv = document.createElement("div");
bgDiv.appendChild(formDiv);
document.body.appendChild(bgDiv);
With ids and css something like this:
#zreaderwp-bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(30, 30, 30, 0.7);
z-index: 100;
}
#zreader-form {
margin-top: 100px;
margin-left: auto;
margin-right: auto;
width: 600px;
height: 600px;
background: white;
}
I attach an eventlistener to bgDiv in a hope that ESC should hide the form:
bgDiv.addEventListener("keydown", function(ev) {
ev.stopPropagation();
console.log("ev.keyCode", ev.keyCode);
if (27 == ev.keyCode) {
console.log("was 27");
bgDiv.style.display = "none";
}
});
To my disappointment this never works as I expect it to. The reason is of course that focus is not always inside bgDiv (though it visually seems to be that).
Is there a good and simple way to handle this?
UPDATE: I created a fiddle to illustrate the problem a bit better, http://jsfiddle.net/lborgman/Musqs/1/. As can be seen there moving the event handler does not solve the problem.
If you want to hide bigDiv whenever esc is pressed globally, add the event listener to document itself (though stopPropagation() could cause some issues, so I've moved it inside the if statement, modified for accuracy.):
document.addEventListener("keydown", function(ev) {
console.log("ev.keyCode", ev.keyCode);
if (27 == ev.keyCode && bgDiv.style.display !== "none") {
ev.stopPropagation();
console.log("was 27");
bgDiv.style.display = "none";
}
});
Additionally, use triple equals === in your if statement. It probably won't change much here, but is a good habit to get into. For more details, see: == vs ===
Fiddle answer here.
FIDDLE
Attach it to document instead and don't stop the event from propogating when its a key press inside the input.
Here you go
var docInp = document.getElementById("doc-input");
docInp.focus();
docInp.addEventListener("keydown", function(ev){
if (27 !== ev.keyCode && bgDiv.style.display !== "none") {
// we won't stop event propogation if the ESC key was pressed and the bgDiv was visible
ev.stopPropagation();
}
alert("Hi, it's me, docInp? Did u want something?");
});
var bgDiv = document.createElement("div");
bgDiv.setAttribute("id","bg");
var formDiv = document.createElement("div");
formDiv.setAttribute("id","form");
bgDiv.appendChild(formDiv);
formDiv.appendChild(document.createTextNode("Press ESC!"));
document.body.appendChild(bgDiv);
document.addEventListener("keydown", listenToKeys, false);
function listenToKeys(ev) {
ev.stopPropagation();
if (27 == ev.keyCode) {
bgDiv.style.display = "none";
document.removeEventListener("keydown", listenToKeys, false);
}
}
I am a bit hesitating to answer my own question, but since others may face the same problem it looks most helpful to me. After chatting with #SomeKittens Ux2666 yesterday and struggling with the problem that focus will not stay inside "bg" I found a solution that I think is reasonable, see http://jsfiddle.net/lborgman/Musqs/31/.
This solution uses "focusout" (which is unfortunately not supported by FF at the moment, see https://developer.mozilla.org/en-US/docs/Web/Reference/Events/focusout):
bgDiv.addEventListener("focusout", function(ev){
// Fix-me: Won't currently work in FF, but it is not
// really essential and FF will probably support this
// later.
ev.stopPropagation();
var to = ev.relatedTarget;
var from = ev.target;
console.log("bg got focusout, to", to, "from", from);
var inBg = false;
n = 0;
while (!inBg && to && n++ < 5) {
to = to.parentNode;
inBg = to === bgDiv;
}
if (!inBg) {
console.log("trying to keep focus in bg");
from.focus();
}
});
The other half of the solution is where to add the ESC keydown eventlistener. That has been addressed in the answer by #SomeKittens and #Lucky Soni, thanks. (But the eventlistener may actually stay on "bg" when the problem with focus has been solved!)

event onmouseover : function launched many times when a <div> includes a <div>

I have a javascript event onmouseover which is linked to a <div> called div1. As soons as the mouse enter the <div>, it writes something into the console. Right.
If i include an other <div> called div2 into the first one, the problem is that the event will be launched at each time the mouse goes from the first into the second, without escaping from div1. The event should be launched only one time, when the mouse enters div1
The code is pretty simple and can be tested here (please open a js console and put your mouse between red and blue)
<html>
<head>
<style>
#div1{
position : absolute ;
top: 100px;
left: 100px;
width : 200px;
height : 200px;
background : red;
}
#div2{
position : absolute ;
top: 10px;
left: 10px;
width : 100px;
height : 100px;
background : blue;
}
</style>
</head>
<body>
<div id="div1" >
<div id="div2">
</div>
</div>
</body>
<script>
var div1 = document.getElementById('div1');
div1.onmouseover = function(){
console.log('Function launched!');
};
</script>
</html>
In my website, it sends an AJAX request at each event... so it involves to many data transfer.
Use next(), previous() methods or use nth-child or nth-of-type. Thanks and Good luck
Try this.
<script>
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
flag = 0;
div1.onmouseover = function(event){
if (event.target === this && flag == 0)
{
console.log('ok');
}
};
div1.onmouseout = function(event){
if (event.target === this)
{
flag = 0;
}
};
div2.onmouseover = function(event){
if (event.target === this)
{
flag = 1;
}
};
</script>
The above code will not allow to listen mouse over event of inner div.
Try to stop the event propagation by using stopPropagation().
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}

click anywhere to close div inside and outside

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/

Categories

Resources