Keyup Event Not Triggered When iFrame in Focus - javascript

Let me start by saying I have no control over the iframe.
Like "stumbling" I let the user navigate to the next page by using the right arrow key.
The problem is that if the user has clicked anywhere inside of the iframe window, the keyup event on the containing document is ignored.
<script type="text/javascript">
$(document).ready(function() {
$(document).on('keyup', null, function(event) {
var stumblenext = $('#stumblenext');
if (event.keyCode == 39) { top.location=stumblenext.attr('href'); }
if (event.keyCode == 37) { history.back(); }
});
});
</script>

When you detect that the focus is on the iframe change the focus to some other element on your page.
Script :
function changeFocus() {
if (document.activeElement == document.getElementsByTagName("iframe")[0]) {
document.getElementById("YOUR_ID").focus();
}
}
window.setInterval(changeFocus, 1000); // Set time accordingly

Try binding keyup on the iframe as well.
$(document, $("#idOfiFrame").contents()).on('keyup', null, function(event) {
var stumblenext = $('#stumblenext');
if (event.keyCode == 39) { top.location=stumblenext.attr('href'); }
if (event.keyCode == 37) { history.back(); }
});

Related

Pressing space on iframe scrolls parent page down, how to prevent that without breaking keyup event

My iframe game is reading the keyboard including space, but on some browsers (Firefox, Safari) pressing Space also scrolls my page down, that causes my game to partially go out of screen. Sometimes it seems the page even scrolls back up when some other keys are pressed...
My game handles keypresses on "keyup" event.
input.addEventListener("keyup", function (e) {
//game handles all keys including space here
}
Because of using keyup event, this answer is not suitable to prevent space ;
Pressing spacebar scrolls page down?
If I add this code, my game does not receive keyup events:
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
When I add this code above to parent html page, having ifreme, it only works if keyboard focus is clicked to parent html. When focus is inside iframe, the code does not work.
It seems above code fixed issue for Safari!
The onkeypress event fires the browser scrolling. You can call preventDefault in this event, and the keyup and keydown events will continue to fire as intended.
window.onkeypress = function(e) {
if (e.keyCode == 32) {
e.preventDefault();
}
};
window.onkeyup = function(e) {
console.log("Space key up!")
};
You need preventDefault
window.addEventListener('keydown', (e) => {
if (e.keyCode === 32) {
e.preventDefault();
}
});
See this codepen for a demo: https://codepen.io/xurei/pen/MWyveEp
You have to find the right window object first
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
var myFrame = document.getElementById('targetFrame');
var frame_win = getIframeWindow(myFrame);
and then add the listeners to stop the spacebar event from bubbling up.
if (frame_win) {
var preventSpace = (e) => {
if (e.keyCode === 32) {
e.preventDefault();
}
};
frame_win.addEventListener('keydown', preventSpace);
frame_win.addEventListener('keyup', preventSpace);
frame_win.addEventListener('keypress', preventSpace);
}

How to fix keypress event for enter key that is running a function twice while only being called once

I am creating a tip calculator. I have a button on the page that calculates the tip if you press it or if you press enter on the keyboard. When I press the enter key, the function that calculates the tip runs but then it runs again even though I did not call it again anywhere in my code. The odd thing is, is that the second time it runs, it goes into the variable where the function is stored and runs the function. I don't know why it goes into a variable that wasn't called.
I tried debugging to see if I missed a step and if I called the function twice somewhere, but I didn't.
Here is the keypress event:
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
Then right after that code is the calculateTip variable:
var calculateTip = function() {
some code that does calculations
}
After the key is pressed, calculateTip is executed, then it goes straight into the above variable to run calculateTip again.
I have my code inside an IIFE. I already tested to see if the code outside of this IIFE affected anything, it doesn't. The 'click' event listener works perfectly and only executes the calculateTip function once.
In this version of my code, calculateTip will print 'test' to the console twice if enter is clicked.
The IIFE:
var controller = (function(calcCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.button).addEventListener('click', calculateTip);
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
});
};
var calculateTip = function() {
console.log('test')
};
return {
init: function() {
setupEventListeners();
}
}
})(calculateController, UIController);
controller.init();
with jquery you can solve it
$(document).unbind('keypress').bind('keypress', function (e) {
if (e.keycode === 13 || e.which === 13) {
calculateTip();
}
});
Just add event.preventDefault(); inside the callback, it helped me.
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
event.preventDefault();
calculateTip();
}
}
It's give one time would you please check this out.
<script type="text/javascript">
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
});
var calculateTip = function() {
console.log("enter clicked");
}
</script>
Try to put the following to your event listener function:
event.stopImmediatePropagation();

Capture keyDown for current page only

I have forms on different pages of my applications. Upon pressing 'Enter' or 'Esc', the form on the current page must be 'Submitted' or 'Cancelled'. The keydown() function should be triggered anywhere on the page and not tied to a specific DOM element.
.js
$(document).keydown(function(e) {
if(e.which == 13) {
// enter pressed
$('#submitCreateAccountForm').click();
$('#submitForm').click();
$('#submitNewSubmissionForm').click();
}
if(e.which == 27) {
// esc pressed
$('#submitCreateAccountFormCancel').click();
$('#submitFormCancel').click();
$('#submitNewSubmissionFormCancel').click();
}
});
What should 'document' be replaced by? Thanks
try this
$(function(){
$('html').bind('keypress', function (e) {
if (e.keyCode == 13) {
//do somethings
}
else if (e.keyCode == 27) {
return false;
}
});
});
You can try this code:
$("body").keyup(function(event){ // bind keyup event to body
if(event.keyCode == 13){ // 13 - code of enter key (find for ESC)
$("#enter").click(); // bind enter press for clicking botton with id="enter" and corresponding actions
}
});

How to simulate tab key with enter key on javascript

<script type="text/javascript">
function onDataBound(e) {
$("#batchgrid").on("click", "td", function (e) {
$("input").on("keydown", function (event) {
if (event.keyCode == 13) {
event.keycode=9;
return event.keycode;
}
});
});
}
</script>
here i'm using above script to fire tab key press event when i press the enter key.but it doesn't behave as tab key pressed when i press the enter key.
please help me here..
return event.keycode is effectively return 9, and even return event will not help, as returning the event does not mean that will be handled properly, what you probably want to do instead is to take the enter event and then manually change focus to the next required field:
function onDataBound(e) {
$("#batchgrid").on("click", "td", function (e) {
$("input").on("keydown", function (event) {
event.preventDefault();
if (event.keyCode == 13) {
$(this).next("input, textarea").focus()
}
});
});
}
It will not simulate until you prevent the default enter key event.
event.preventDefault(); should be the first command of your function.Then implement the tab key event.Your code should be something like this :
<script type="text/javascript">
function onDataBound(e) {
$("#batchgrid").on("click", "td", function (e) {
$("input").on("keydown", function (event) {
event.preventDefault();
if (event.keyCode == 13) {
event.keycode=9;
return event.keycode;
}
});
});
}
</script>
Hope it will work.

How to stop of running the keycodes 37 and 39 when there is a textarea selected

Simply I have a js script that change the page with left and right arrows, but how to stop that if a specific textarea is selected ?
This is my js to change the page
$(document).keydown(function(event) {
if(event.keyCode === 37) {
window.location = "http://site.com/pics/5";
}
else if(event.keyCode === 39) {
window.location = "http://site.com/pics/7";
}
});
$('textarea').on('keypress', function(evt) {
if ((evt.keyCode === 37) || (evt.keyCode === 39)) {
console.log('stop propagation');
evt.stopPropagation();
}
});
See example fiddle: http://jsfiddle.net/GUDqV/1
Update: after OP clarification this works even on jQuery 1.2.6 on Chrome: http://jsfiddle.net/GUDqV/2/
$('textarea').bind('keyup', function(evt) {
if ((evt.keyCode === 37) || (evt.keyCode === 39)) {
console.log('stop propagation');
evt.stopPropagation();
}
});​
see screenshot of this code on Chrome and jQ1.2.6
Probably the simplest approach is to factor event.target into your code, checking to see if it is the textarea:
$(document).keydown(function(event) {
if (event.target.id == "myTextArea") {
return true;
}
else if(event.keyCode === 37) {
window.location = "http://site.com/pics/5";
}
else if(event.keyCode === 39) {
window.location = "http://site.com/pics/7";
}
});
Any key events that originate from a textarea element with an id of myTextArea will then be ignored.
You can check if the textarea is in focus by doing something like:
if (document.activeElement == myTextArea) {
// Don't change the page
}
$("#mytextarea").is(":focus") This will let you know if the element is focused.
Also $(document.activeElement) will get the currently focused element.
You can check to see if your text area is focused, and disable the script that navigates when using left and right arrow keys.
A little bit of code showing what you've tried might bring in more specific responses.
Hope this helps.

Categories

Resources