//Function To Display Popup
function div_show(x) {
document.getElementById(x).style.display = "block";
div_hide(x);
}
//Function to Hide Popup
function div_hide(x){
window.onkeyup = function (event){
if(event.keyCode == 27)
document.getElementById(x).style.display = "none"};
}
I want to hide the popup I created, but the div_hide function doesn't work. I even tried an alert message and it results that the event keycode is undefined. Basically I can't catch the esc key.
Don't pass event as an argument. You will still be able to use event.keyCode inside your event handler.
Related
I have a page which has a keydown event listener, to listen for the Escape key, to navigate back. I also have a simple modal class, which also listens for the Escape key to close it. The main page listener checks if a modal is open, and if so, returns without doing anything.
window.addEventListener("keydown", function (ev) {
if (modal_is_open) { return; }
ev = ev || window.event;
if (ev.key == "Escape") { history.go(-1); }
});
modal_div.addEventListener("keydown",function (ev) {
ev = ev || window.event;
ev.stopPropagation();
ev.preventDefault();
ev.cancelBubble = true;
if (ev.key == "Escape") { close_the_modal(); }
return false;
});
My problem is, if a modal is open, the Escape key closes it, but still bubbles up to the main page handler and navigates back. How can I stop this?
I finally found the solution, replace stopPropagation with stopImmediatePropagation, and the window keydown handler no longer fires if the modal is open.
on down arrow keypress , click event is getting fired, event.keycode is undefined
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
var target = $(this).attr("target");
if (event.keyCode !== '40'){
if (!$(".li-menu").is(":visible") && target === undefined) {
location.href=this.href;
} else {
window.open(this.href, '_blank');
}
}
});
in this code i am trying to open main menu in new tab , but external link is getting open on down arrow keypress
call preventDefault() function.
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
event.preventDefault();
var target = $(this).attr("target");
if(event.keyCode!=='40'){
if (!$(".li-menu").is(":visible") && target===undefined) {
location.href=this.href;
}
else {
window.open(this.href,'_blank');
}
}
});
See the keycode for the reference https://css-tricks.com/snippets/javascript/javascript-keycodes/
in order to configure your app for particular key event
Looking at the classes dropdown-toggle, navbar-collapse, I'm guessing that you are using Bootstrap library.
If that is the case, the behaviour you are seeing is reasonable. Let's break down the issues:
on down arrow keypress , click event is getting fired
Q: You have only bind the handler on click event so why are it is being triggered on keypress?
A: Because this is a feature of bootstrap dropdown. To have better accessibilty, bootstrap triggers click event on the keydown of up, down, esc and space keys.
event.keycode is undefined
Since it is a click event handler and not some keyboard event handler like keydown or keypress, event.keyCode should be undefined
Note: You are using a strict equality in the following condition
if (event.keyCode !== '40')
This will check both the type and value of the operands. Now, event.keyCode always return a Number while '40' is a string, hence the above condtion will yield false even if keyCode is 40. You should correct it to:
if (event.keyCode !== 40)
Now, if you want to stop the redirect on down key, you should check whether the event triggered is an original event or was triggered by some js logic. For this, you may choose jQuery's event.isTrigger or event.originalEvent
Here's a code snippet:
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click", function(event) {
var target = $(this).attr("target");
// Check if NOT an triggered event
if (!event.isTrigger) {
if (!$(".li-menu").is(":visible") && target === undefined) {
location.href = this.href;
} else {
window.open(this.href, '_blank');
}
}
});
<a> tags will fire the click event when you press enter on them. However you will not have a keyCode on the event because it is not a Key* event. If you want to know the keyCode add a keyDown or keyUp handler as well. You could also handle both by doing something like the following:
$(".dropdown:not(.li-search) a.dropdown-toggle", ".navbar-collapse").on("click keydown", function(event) {
var target = $(this).attr("target");
if(event.type === 'keydown' && event.keyCode!=='40'){
if (!$(".li-menu").is(":visible") && target===undefined) {
location.href=this.href;
}
else {
window.open(this.href,'_blank');
}
}
});
You'll probably also want to add an event.preventDefault(); in there if you wish to prevent default browser behaviour from taking place.
This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
i've created a sample application which checks when i press a key or mouse, but the problem is when mouse or when key is pressed it prints the console "Enter is pressed" and "Enter is not pressed some Mouse event is clicked", that boolean checking is not working properly i think so,
can anyone please tell me some solution
$('#adminPanel').bind("searchMaster", function(event, data)
{
var press = true;
$(this).keypress(function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13)
{
console.log("Enter is pressed");
press = false;
}
});
if(press)
{
console.log("Enter is not pressed, some Mouse event is clicked");
// some other action to be triggered if key is not pressed
}
});
The problem is, (a) that you register the keypress event inside the click callback and (b) that you set press to false, if is pressed and (c) that you never reset the value of press every time you click with the mouse.
I suggest you split the two callbacks up and move press outside of the callbacks. In the example press => enterPressed. The enterPressed and the callbacks are wrapped in an IIFE to not poluted the global namespace.
(function () {
// by default, "enter" is not pressed
var enterPressed = false;
// Suppose this event is triggered by mouse clicks
$("#adminPanel").bind("searchMaster", function (event, data) {
if (!enterPressed) {
// Handle Mouse Click (no "enter" pressed here)
}
});
// This callback will be triggered if you press a key
// and if you release a key
$("#adminPanel").on("keydown keyup", function (e) {
var code = e.keyCode ? e.keyCode : e.which;
// check if the pressed/released key was "enter"
if (code === 13) {
enterPressed = !enterPressed;
}
});
})();
I wanted to make modal dialog accessible . I added two hidden focusable elements
Dialog Start
Some focussable Dialog Elements
Dialog end
function onblurevent(){
document.getElementById("dialog-start").focus();
}
When ever dialog-end element blur event happens i tried to move focus to dialog-start element calling focus() method
but the focus is moving to address bar .dialog start and end anchor tags are hidden by using below style
#dialog-start{
height:1px;
left:-9999px;
overflow:hidden;
position:absolute;
top:0;
width:1px;
}
Iam not sure if anchor styles are the reason or is the only way to make sure focus is inside the dialog is to get list of focusable elments and call focus() method in a keydown event handler on container.
The problem occurs because you don't handle your keydown event. When you pressing Tab on last link browser automatically switches focus to address bar. So you just need to preventDefault() default browser behavior if Tab pressed.
The following code will work:
window.onload = function() {
var firstAnchor = document.getElementById("dialog-start"),
lastAnchor = document.getElementById("dialog-end");
function keydownHandler(e) {
var evt = e || window.event;
var keyCode = evt.which || evt.keyCode;
if(keyCode === 9) { // TAB pressed
if(evt.preventDefault) evt.preventDefault();
else evt.returnValue = false;
firstAnchor.focus();
}
}
if(lastAnchor.addEventListener) lastAnchor.addEventListener('keydown', keydownHandler, false);
else if(lastAnchor.attachEvent) lastAnchor.attachEvent('onkeydown', keydownHandler);
}
(note that you dont need onblurevent function anymore)
$(document).ready(function () {
//set focus on first field in Bootstrap modal when loaded
$("#yourModal").on('shown.bs.modal', function () {
$(this).find('#yourField').focus();
});
});