window.confirm not working in FireFox - javascript

Background:
The goal is to keep a user from going back a page using the backspace. I've created code to disable the the key, except for a few input fields. But if they do, in fact, want to go back, I'd like for the confirm dialog to ask them if they REALLY want to go back or not.
Problem:
The following code works in IE and Chrome, but not FF. The confirm pops up but it still goes 'back' a page. This doesn't happen in IE/Chrome as the confirm dialog waits for user input.
Code:
<script type="text/javascript">
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' &&
(
d.type.toUpperCase() === 'TEXT' ||
d.type.toUpperCase() === 'PASSWORD' ||
d.type.toUpperCase() === 'FILE' ||
d.type.toUpperCase() === 'SEARCH' ||
d.type.toUpperCase() === 'EMAIL' ||
d.type.toUpperCase() === 'NUMBER' ||
d.type.toUpperCase() === 'DATE' )
) ||
d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
}
else {
var r = window.confirm("Leaving the page can cause data to be lost. Are you sure?");
if (!r) {
doPrevent = true;
}
}
}
if (doPrevent) {
event.preventDefault();
//event.stopPropagation();
}
});
</script>

This fixed it and worked in each browser (Safari too):
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Leaving the page can cause data to be lost. Are you sure?";
e.returnValue = confirmationMessage; // Gecko and Trident
return confirmationMessage; // Gecko and WebKit
});

Related

Disable Alt+Home in IE11 using JavaScript

I have been able to disable some browser hotkeys using Javascript but it seems that IE11 will not let me disable Alt+Home (see example code below). Any idea why this does not work in IE11?
jQuery(document).on('keydown', function(e) {
// Stop Browser History (ctrl + H)
if (e.ctrlKey && e.keyCode === 72) {
return false;
}
// Stop Alt + Home
if (e.altKey && e.keyCode === 36) {
return false;
}
...
I was able to get this to work in IE11, by adding an alert() call.
jQuery(document).on('keydown', function(e) {
// Stop Alt + Home
if (e.altKey && e.keyCode === 36) {
alert("Your message here");
return false;
}

Do not scroll page down when spacebar is clicked?

As you may know some browsers have this default functionality to scroll page down when spacebar is clicked. I usually like this feature, but due to nature of my website I need to get rid of it.
I've been using
window.onkeydown = function(e) {
return !(e.keyCode == 32);
};
which eats all spacebar functionality and gets the job done, however if user is typing in a comment or a search query and they press spacebar no space is added in a text as this functionality has been eaten up.
So is there a way to disable just the scrolling part and leave all other functionality as it is?
window.onkeydown = function(e) {
return !(e.keyCode == 32 && (e.target.type != 'text' && e.target.type != 'textarea'));
};
Maybe try this:
window.onkeydown = function(e) {
if(e.keyCode == 32 && e.target.nodeName.toUpperCase() === "BODY") e.preventDefault();
};
Probably need to equalise for IE:
window.onkeydown = function(e) {
var evt = e || window.event;
var elem = evt.target || evt.srcElement;
if(e.keyCode == 32 && elem.nodeName.toUpperCase() === "BODY") {
evt.preventDefault();
return false;
}
};
(untested)
But you would need to attach an event to/within each iframe, using iframeref.contentWindow.
After the page and iframes have loaded you could loop through the frames[] collection.

Catching the Submit works in Firefox but not in Chrome

I'm using this to catch the submit button press, validate everything, and then either stop it or let it go through, this works in Firefox, but not in Chrome, Chrome lets the form go through empty. I also have a reset function that works in Chrome but in firefox. I'm brand new to js and jquery and could use some help figuring this out since stuff working in one browswer and not in the other confuses the heck out of me :)
(Sorry about having my test alert in there still)
Here's the code:
$("form").submit(function(e){
if (e.originalEvent.explicitOriginalTarget.id=="btn") {
if (bizNameValid==false || bizWebValid==false || bizStreetValid==false || bizCityValid==false || bizStateValid==false || bizZipValid==false || bizPhoneValid==false || firstValid==false || lastValid==false || custStreetValid==false || custCityValid==false || custStateValid==false || custZipValid==false || custPhoneValid==false || custEmailValid==false || monValid==false || yearValid==false || typeValid==false || ccValid==false) {
alert("bizNameValid:" + bizNameValid+"\n bizWebValid:"+bizWebValid+"\n bizStreetValid"+bizStreetValid +"\n bizCityValid: "+bizCityValid+ "\n bizStateValid:"+bizStateValid+"\n bizZipValid: "+bizZipValid+"\n bizPhoneValid:"+bizPhoneValid+"\n firstValid:"+firstValid+"\n lastValid:"+lastValid+"\n custStreetValid:"+custStreetValid+"\ncustCityValid"+custCityValid+"\n custStateValid"+custStateValid+"\n custZipValid:"+custZipValid+"\n custPhoneValid"+custPhoneValid+"\n custEmailValid:"+custEmailValid+"\n monValid:"+monValid+"\n yearValid:"+yearValid +"\n ccValid:"+ccValid+" \nccType:"+typeValid);
e.preventDefault();
return false;
}
else if(total==0) {
$("#svc_desc").append("</br><label id='first_error' style='font-size:16pt;'>You must select a service to continue</label>");
alert("You must select a service to continue");
e.preventDefault();
return false;
}
else {
return true;
}
}
});
try
$("form").submit(function(e){
var target = e.originalEvent || e.originalTarget;
if($(target.srcElement || target.originalTarget).attr('id')=="btn"){
}
//rest of your code
});
ref: https://stackoverflow.com/a/8067990/1679410

Prevent backspace button from navigating back in Sharepoint 2010 and IE

As a user requirement I have to disable the backspace button from navigating back in the history. I made the following piece of code
//Bind back nutton to prevent escaping the page with backspace
$j(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8)
{
if(event.target == document.body){
if(event.preventDefault()){ event.preventDefault(); }
event.stopEvent();
event.returnValue = false;
}
}
});
This is working perfectly in all the browsers except IE7 and IE8. I cannot bind the input types as exceptions because the content editor in SharePoint allows modification of the text in the elements div, paragraph, etc. The solution is not working in IE8 because the event.target returns the element that is on mouseover when there are no controls that have the focus.
I'd recommend a tweak to Machinegon's fix. The code should also prevent default behavior if the user clicks the backspace key in a readonly input control of type text.
if ((nodeName === "input" && event.target.type === "text") ||
nodeName === "textarea") {
doPrevent = event.target.readOnly;
}
Solved by myself, case closed.
EDIT: Working in 2012 with SharePoint 2010 and jquery 1.x, not sure about today.
//Bind back button to prevent escaping the page with backspace
$(document).unbind('keydown').bind('keydown', function (event) {
if (event.keyCode === 8)
{
var doPrevent = true;
//Chrome, FF, Safari
if(event.target == document.body){
doPrevent = true;
}
//IE
else
{
var nodeName = event.target.nodeName.toLowerCase();
if((nodeName == "input" && event.target.type == "text") || nodeName == "textarea")
{
doPrevent = false;
}
var SPEditTabInstance = $(document).find("li[id='Ribbon.EditingTools']");
if(SPEditTabInstance != "undefined" && SPEditTabInstance != null && $(SPEditTabInstance).children().length > 0){
doPrevent = false;
}
}
if(doPrevent)
{
//Chrome, FF, Safari
if(event.preventDefault()){ event.preventDefault(); }
//IE
else
{
event.returnValue = false;
}
}
}
});
Try pushing back to the person(s) creating the requirements that breaking a ubiquitous and important function of all browsers is not a particularly great idea from a usability perspective. The costs of doing so (including time spent explaining to users why thier browser "don't work no more") will greatly outweight the costs of having the back button be a bit annoying occaisionally.
Machinegon's answer works well, I'm just adding to it to handle one more case.
If the input boxes are readonly or disabled, and if you hit backspace on them, then it goes to previous page. So the following code will work to handle that scenario:
//Bind back button to prevent escaping the page with backspace
$(document).unbind('keydown').bind('keydown', function(event) {
if (event.keyCode === 8) {
var doPrevent = true;
//Chrome, FF, Safari
if (event.target == document.body) {
doPrevent = true;
}
//IE
else {
var nodeName = event.target.nodeName.toLowerCase();
if (((nodeName == "input" && event.target.type == "text") || nodeName == "textarea")
&& !event.target.disabled && !event.target.readOnly) {
doPrevent = false;
}
}
if (doPrevent) {
//Chrome, FF, Safari
if (event.preventDefault()) {
event.preventDefault();
}
//IE
else {
event.returnValue = false;
}
}
}
});

Detect backspace and del on "input" event?

How to do that?
I tried:
var key = event.which || event.keyCode || event.charCode;
if(key == 8) alert('backspace');
but it doesn't work...
If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that
my code:
$('#content').bind('input', function(event){
var text = $(this).val(),
key = event.which || event.keyCode || event.charCode;
if(key == 8){
// here I want to ignore backspace and del
}
// here I'm doing my stuff
var new_text = 'bla bla'+text;
$(this).val(new_text);
});
no character should be appended in my input, besides what I'm adding with val()
actually the input from the user should be completely ignored, only the key pressing action is important to me
Use .onkeydown and cancel the removing with return false;. Like this:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
};
Or with jQuery, because you added a jQuery tag to your question:
jQuery(function($) {
var input = $('#myInput');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
});
});
​
event.key === "Backspace"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
keydown with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
Mozilla Docs
Supported Browsers
Have you tried using 'onkeydown'?
This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
InputEvent.inputType can be used for Backspace detection Mozilla Docs.
It works on Chrome desktop, Chrome Android and Safari iOS.
<input type="text" id="test" />
<script>
document.getElementById("test").addEventListener('input', (event) => {
console.log(event.inputType);
// Typing of any character event.inputType = 'insertText'
// Backspace button event.inputType = 'deleteContentBackward'
// Delete button event.inputType = 'deleteContentForward'
})
</script>
on android devices using chrome we can't detect a backspace.
You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
//Here's one example, not sure what your application is but here is a relevant and likely application
function addDashesOnKeyUp()
{
var tb = document.getElementById("tb1");
var key = event.which || event.keyCode || event.charCode;
if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) )
{
tb.value += "-"
}
}
Live demo
Javascript
<br>
<input id="input">
<br>
or
<br>
jquery
<br>
<input id="inpu">
<script type="text/javascript">
var myinput = document.getElementById('input');
input.onkeydown = function() {
if (event.keyCode == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.keyCode == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
};
//jquery code
$('#inpu').on('keydown', function(e) {
if (event.which == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.which == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
});
</script>

Categories

Resources