Trigger an event when the browser back button is clicked - javascript

I am trying to run some code when the browser back button is clicked.
How can i found out browser's back button with out changing the browser history?
I tried the code below.
I got an exception in the else block saying: "event is not defined".
window.onunload = HandleBackFunctionality();
function HandleBackFunctionality()
{
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked…");
} else {
alert("Browser refresh button is clicked…");
}
} else {
if(event.currentTarget.performance.navigation.type == 1)
{
alert("Browser refresh button is clicked…");
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Browser back button is clicked…");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

use
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
}
if (direction == 'forward') {
// do something else
}
});

Okay. Besides the fact that you should not initially trigger the event and to .unload = FunctionName and not .unload=FunctionName() and that you need to pass the event-argument I checked the code in the browser.
currentTarget is empty - this totally makes sense as there is no event-target like onclick but it is just the site reloading/unloading.
Please debug the code by yourself by using this and fit it to your needs:
window.onunload = HandleBackFunctionality;
function HandleBackFunctionality(event)
{
console.log(event, window.event);
}
You will see that currentTarget is not set (while event is).

This is the only solution that works for me with IOS safari.
<script>
window.addEventListener( "pageshow", function ( event ) {
var pagehistory = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( pagehistory ) {
// back button event - Do whatever.
}
});
</script>

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

Accessing window.event.altkey in a setInterval

I have the following code:
function optionkey()
{
e = window.event;
if( e.altKey )
{
return "down";
}
else
{
return "up";
}
}
interval = setInterval(function(){
if( optionkey() == "down" ) {
clearInterval(interval);
alert( 5 );
}
}, 100);
Basically the code should run alert(5) when the user presses the optionkey, but instead I get a load of errors: Uncaught TypeError: Cannot read property 'altKey' of undefined
Can anyone tell me why it does this and how to fix it?
Thanks.
jsfiddle
Please let me know if I have misinterpreted your needs, but if you want an alert to fire when pressing the key you need to create an event listener for onkeydown like so
window.onkeydown = function ( e ) {
if(e.altKey){
alert(5);
}
}
First of all event.altKey can only be detected on keypress (input) events like keydown and keyup. However calling a function from setInterval will not trigger the altkey. You will need to catch that in a event handler and pass it on.
function optionkey()
{
if( window['globalAltKey'])
{
return "down";
}
else
{
return "up";
}
}
interval = setInterval(function(){
if( optionkey() == "down" ) {
clearInterval(interval);
alert( 5 );
}
}, 100);
window.addEventListener("keydown", function(e){
if (e.altKey)
{
globalAltKey = true;
}
else
{
globalAltKey = false;
}
}, false)
Now the interval will still test if the optionkey() will return down or up. Only when the user clicks alt this will fire the alert.
I don't know why you have chosen this approach, you can simply attach a click handler to a button and use the keydown event I provided to check if the alt key is globally pressed.

Keypress don't work on some Android devices

I have issue with Android in jQuery Terminal, I've almost fix it, it work on devices I've tested. Demo. But it seems that keypress event don't fire at all (It should echo keypress) on some devices.
On mobile I have code that keep focus on textarea (I resued clipboard) so virtual keyboard is open.
I have this code in keydown:
function keydown_event(e) {
...
if (enabled) {
...
} else {
// this get fired while typing
$.terminal.active().echo('keydown else');
prevent_keypress = false;
return;
}
// this will prevent for instance backspace to go back one page
prevent_keypress = true;
$.terminal.active().echo('keydown return false');
return false;
}
...
}
}
and in keypress:
var doc = $(document.documentElement || window);
doc.bind('keypress.cmd', function(e) {
var result;
if (e.ctrlKey && e.which === 99) { // CTRL+C
return;
}
// this line never get fired while typing
$.terminal.active().echo('keypress');
if (prevent_keypress) {
$.terminal.active().echo('prevent');
return;
}
if (!reverse_search && $.isFunction(options.keypress)) {
result = options.keypress(e);
}
if (result === undefined || result) {
...
self.insert(String.fromCharCode(e.which));
...
} else {
return result;
}
}).bind('keydown.cmd', keydown_event);
Anybody had same issue and know how to fix it, it's hard for me because it work on my devices.
UPDATE I've create simple test to isolate the problem and it seems that keypress is not fired at all.
I manage to fix (almost) the issue by detecting if keypress was not fired and get value from clipboard (for mobile the content it's always the same as terminal input)
var no_keypress;
doc.bind('keydown.cmd', function(e) {
no_keypress = true;
...
}).bind('keypress.cmd', function(e) {
no_keypress = false;
...
}).bind('keyup.cmd', function() {
if (no_keypress) {
// Some Androids don't fire keypress - #39
self.set(clip.val());
}
});

javascript android window.onorientationchange fires continuously

I'm trying to detect orientation changes on mobile devices and trigger a function once an orientation has been completed, but the code inside the function is continuously firing in Android and I'm not sure why. Here's my code:
var supportsOrientationChange = "onorientationchange" in window;
var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent,
function() { alert ('orientation changed'); },
false
);
Does anyone know how to write this so that it only triggers once, after orientation change has been completed?
I used a work-around for this in my app. I added an event listener for orientationchange and then set a timeout so the orientationchange could occur and I could get a new width value that actually reflected the width after the orientation change.
var device_width = 0;
$(document).ready(function () {
var oc_timer;
$(window).bind('orientationchange', function () {
clearTimeout(oc_timer);
oc_timer = setTimeout(function () {
device_width = $(window).width();
}, 500);
});
});
I am not positive this will solve your continuously firing function problem but this is a solution I found to work.
I found a way to do this in case others are still having the same issue, check it out:
function onOrientationChange() {
if (typeof(this.orientation) === "undefined"){
if (window.orientation == -90 || window.orientation == 90) {
this.orientation = "landscape";
} else {
this.orientation = "portrait";
}
// alert ("in 1");
// you code here for change
}
if ((window.orientation == -90 || window.orientation == 90) && (this.orientation == "portrait")) {
this.orientation = "landscape";
// alert ("in 2");
// you code here for change
}
if ((window.orientation == 0 || window.orientation == 180) && (this.orientation == "landscape")) {
this.orientation = "portrait";
// alert ("in 3");
// you code here for change
}
}
Simple solution for less detailed applications
//bind orientation change event
$(window).bind("orientationchange", orientationChange);
//later,
function orientationChange(){
//whatever needs to happen when it changes.
alert("changed");
}
You could also use $.on() instead if you need to pass information.
In browsers that do not support it, the event does not fire. You could then write a custom detection script as a fallback to fire the event if the orientation changes on a device that does not support onorientationchange.

jquery code is not workign after postback

I wrote the following jquery code to allow only numbers in a textbox.
$("[id$='txtPriority']").keydown(function (event) {
if (event.keyCode == 48) {
var value = $("[id$='txtPriority']").val();
if (value == "") {
event.preventDefault();
return;
}
}
else if (event.keyCode == 86 || event.keyCode == 118) {
event.preventDefault();
return;
}
else {
$("[id$='txtPriority']").numeric();
}
});
});
This works fine ,when the page is loaded for first time.But after post back the code is not working.What might be the reason.
I you are changing something with ajax then the event will not work.
Try using the live function ( http://api.jquery.com/live/ )
$("[id$='txtPriority']").live('keydown', function (event) {
I had this problem once and it was because I was replacing the html for the form in the postback. You need to reset your event handlers after replacing the controls or use the .live() handler which will work even for elements you add later:
$("[id$='txtPriority']").live('keydown', function (event ) {

Categories

Resources