I need help with getting the keydown of up arrow to trigger. I dont really understand what the problem with this is, most likely my messy formatting, but the keydown just doesn't trigger.
<script>
window.addEventListener('keyup', (event) => {
if (event.key == 'ArrowUp') {
close();
window.open("https://bsd.instructure.com/?login_success=1");
}
});
</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Check out the window.close()
and window.open()
API.
JavaScript cannot open windows if the browser blocks them. I tried your code and it says:
"Firefox prevented this site from opening a pop-up window. [Options]".
You can only open windows user-generated (e.g. button / link click).
Your event is working fine, but the browser is preventing the pop-up window.
window.addEventListener('keyup', (event) => {
if (event.key == 'ArrowUp') {
window.close(); // Blocked for certain standards
window.open("https://bsd.instructure.com/?login_success=1"); // Blocked in the user's preferences
}
});
I also recommend you use document
events instead of window
:
document.addEventListener('keyup', (event) => {
if (event.key == 'ArrowUp') {
// Action here
}
});
You can use the window location
property to navigate to pages.
document.addEventListener('keyup', (event) => {
if (event.key == 'ArrowUp') {
window.close();
window.location.replace("https://bsd.instructure.com/?login_success=1");
}
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Only for the sake of completeness. as @Mike 'Pomax' Kamermans already answered the question correctly. bind the document object to the event instead of the window object.
document.addEventListener('keyup', (event) => {
if (event.key == 'ArrowUp') {
console.log('Arrow UP');
close();
}
});
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>