I'm making a javascript extension for chrome. It will allow you to edit the page like a word document. Here's the code:
document.body.contentEditable = 'true';
document.designMode='on';
void 0;
document.body.onclick = function(e) {
e.preventDefault()
};
window.addEventListener("keydown", function(e) {
if (e.keyCode == 27) {
document.body.contentEditable = 'false';
document.designMode='off';
void 0;
}
});
The problem is, whenever I'm done and press esc (hence the if (keycode == 27)), sometimes the links don't work. I think that what happens is that e.preventDefault is still going. Can I have a little help?
Make sure you really need the void operator
There's no thing as an event.preventDefault "still going on". It will only be applied once for each event.
You can remove the event listener or create an if statement on your event handler to check it the event default behavior should be prevented or not.
Related
I'm loading every pages in AJAX so I'm using return false on my links to load them in ajax.
Problem: if the guys want to open it in a new window he can't, ctrl+click activates the ajax as well, I haven't tried middle button because I don't have a mouse.
I then tried e.preventDefault and it still prevents the dude to open it in another tab.
Any idea how I could circumvent this?
(if you want to try: www.p1x3L.com)
e.preventDefault() will prevent the link from being followed by the browser at all.
What I'd be tempted to do is just check the status of the Ctrl (or cmd on a Mac) when the click occurs, and then handle the action.
You'll need to track the action of the keypresses. Consider the following example, which assigns a boolean value to ctrlPressed:
var ctrlPressed = false;
$(window).on('keydown', function(e) {
if (e.metaKey || e.ctrlKey) ctrlPressed = true;
}).on('keyup', function(e) {
if (e.metaKey || e.ctrlKey) ctrlPressed = false;
});
Now inside your click handler, you can just check the status of ctrlPressed:
$('a').on('click', function(e) {
if(ctrlPressed)
{
return true;
}
// Handle your AJAX here. No need for an else{} block
// since return true will already have executed.
});
I am working on a scrollbar in Javascript. All works fine except for one problem. I notice that while dragging the scrollbar, if I move the mouse over the context that is being scrolled, the content gets selected. I don't want that to happen, so I used the preventDefault method from the event object, which worked perfectly for IE9 and the other modern browsers. But on IE7 and IE8, the problem persists. I did some searches and found that I should set the returnValue parameter of the event object to false. But the problem still persists. Also, if I write alert(window.event.returnValue) it pops up undefined.
scrollbar.onmousedown = function (event) {
if (typeof event == 'undefined') event = window.event;
if (typeof event.preventDefault != 'undefined') event.preventDefault();
event.returnValue = false;
// do some stuff
}
What am I doing wrong?
In IE7&8 there is no event Object as a parameter to the function, instead there exists window.event. Try
window.event.cancelBubble = true
to stop the propagation.
To avoid problems with FireFox etc. do something like this:
if (!event)
event = window.event;
//IE9 & Other Browsers
if (event.stopPropagation) {
event.stopPropagation();
}
//IE8 and Lower
else {
event.cancelBubble = true;
}
I fixed my problem in the end by adding event.returnValue = false in the 'onmousemove' event, instead on 'onmousedown' event and it worked. It doesn't answer the question about why the orginal code is wrong, but I wanted to post this for people that see my question, to not waste their time in trying to help me with a problem that I have already fixed. Thank you for your quick answers, I appreciate.
I too had the same problem.
preventDefault was not working in IE.
so I added the below code to stop propagation
if (a_event.preventDefault) {
a_event.preventDefault();
} else if (typeof a_event.returnValue !== "undefined") {
a_event.returnValue = false;
}
I'm using a bit of jQuery mixed in to an ASP.NET page and it doesn't seem to do what it ought to. I'm trying to re-assign the up and down arrows and enter key for text boxes so that the user can navigate up and down through the column (like in Excel). I have the event handler set up OK and it works, but I can't get the following part to work correctly:
e.preventDefault;
e.stopPropogation;
Particularly with the enter key, it is still submitting the form even with those two lines in. The only way I can get it working is with the following:
event.cancelBubble = true;
event.returnValue = false;
But from what I've read you shouldn't use those because the two jQuery methods are browser independant. Any help understanding all of this would be great :-)
UPDATE
I've got the handler in a block like this:
//handles the up/down arrow behaviour of the score boxes
$('.gScoreTB').keydown(function (e) {
if (event.keyCode == 13) {
event.cancelBubble = true;
event.returnValue = false;
}
});
Just a simple example to try and stop the enter key behaviour at the moment: will add keyCode == 38 and 40 for the other arrows once this is nailed.
Both preventDefault and stopPropagation are functions, so you should be doing:
e.preventDefault();
e.stopPropogation();
But it's easier to just return false (which is the same as invoking both):
//handles the up/down arrow behaviour of the score boxes
$('.gScoreTB').keydown(function (e) {
if (e.keyCode == 13) {
return false;
}
});
Users don't like the fact that the Enter key submits the page. So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.
I have tried many javascript snippets found on the net but none have worked so far. The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.
e.returnValue = false;
e.cancel = true;
Page still submits with the above in the keydown event handler. Same effect with return false in the keydown event handler. The handler is firing, tested by putting a breakpoint in it with firebug.
This needs to work with both IE and Firefox.
Don't say "don't do this".
1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.
2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.
This just feels icky, but you could use event.preventDefault as you mentioned and then call focus() on the next closest input:
Here's a simple example:
$("input").bind("keydown", function(event) {
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
$(this).next("input").focus();
}
});
Example: http://jsfiddle.net/andrewwhitaker/Txg65/
Update: If you have elements in between your inputs, using plain next() will not work. Instead, use nextAll():
$("input").bind("keydown", function(event) {
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
$(this).nextAll("input").eq(0).focus();
}
});
http://jsfiddle.net/andrewwhitaker/GRtQY/
$("input").bind("keydown", function(event) {
if (event.which === 13 && this.type !== 'submit') {
event.preventDefault();
$(this).next("input").focus();
}
});
Based on this post:
http://forum.jquery.com/topic/how-to-find-next-node-in-focus-order
I came up with this. I eventually chose not to use focasables though, and instead use input to get the effect I wanted. The .not is to prevent image buttons and submit buttons from being effected, so that they still have the default action of submit on enter whenever they have focus.
$(document).ready(function() {
var focusables = $(":input").not('[type="image"]').not('[type="submit"]');
focusables.keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
var current = focusables.index(this),
next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
next.focus();
}
});
});
I don't want my website's user to use backspace to go to the previous page,
but I still want to keep the use of backspace,
just like deleting wrong typing.
How can I do?
Thanks a lot.
As others have mentioned there are methods in which you can monitor for backspace key events and perform different actions.
I recommend against catching the backspace key for a couple of reasons:
1) It's simply irritating and irritated users are likely to not return to your page.
2) Backspace is not the only method of returning to the previous page. There are other key combinations that can accomplish the same thing, as well as the obvious "back button".
Don't do it - but if you must, use onbeforeunload() rather than trapping browser specific key strokes.
Solution: Place the following code toward the end of all your pages that contain forms:
<!-- Block the Backspace and Enter keys in forms, outside of input texts and textareas -->
<script type="text/javascript">
function blockBackspaceAndEnter(e) {
if (!e) { // IE reports window.event instead of the argument
e = window.event;
}
var keycode;
if (document.all) {
// IE
keycode = e.keyCode;
} else {
// Not IE
keycode = e.which;
}
// Enter is only allowed in textareas, and Backspace is only allowed in textarea and input text and password
if ((keycode == 8
&& e.srcElement.type != "text"
&& e.srcElement.type != "textarea"
&& e.srcElement.type != "password")
|| (keycode == 13 && e.srcElement.type != "textarea")) {
e.keyCode = 0;
if (document.all) {
// IE
event.returnValue = false;
} else {
// Non IE
Event.stop(e);
}
}
}
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].onkeydown = blockBackspaceAndEnter;
}
</script>
I have the following comments about what other people answered here before:
Someone said:
"Please don't. Users like
backspace-to-go-back; going back is
one of the most vital browser features
and breaking it is intolerably rude."
My answer to him is:
Yes, usually people DO use the back-button to go back, BUT NOT on pages with FORMS. On the other hand it is really easy for people to accidentally click near or outside an input text or textarea, and then press the back button, so they will lose all their edits, as someone else also noticed:
"Users aren't in a textbox and hit the
backspace, completely losing all the
form information they've just entered.
Wouldn't normally be a problem, but
for us, we're filling out lots of text
on long state forms."
The same undesired behaviour can also be said about the Enter key to submit the form, which usually is only desirable (if ever) for small forms with a few fields, but not for forms with many fields and select boxes and input boxes and textareas, in which most of the time you DO NOT want that the form is submitted when you press Enter.
So this is why I suggest the code above, which applies to all <FORM> tags the function suggested by webster, but without the checks for ALT, which I don't think is useful, and without the checks for CTRL+N and CTRL+R and CTRL+F5, which we don't want to block, because when they are used they are NOT accidental.
Unfortunately, the code above does not work in Firefox when you have DIVs and TABLEs inside your FORM! That is because the keydown event seems to not be propagated to the containing form, and instead the default (UNDESIRED!) behaviour is applied for the Backspace and Enter keys.
I couldn't yet find a solution for this one...
You can use the "onbeforeunload" property on the body tag to prompt the user that he is leaving the page.
You can simply use the following code snippets to block the backspace when the cursor is in texarea, text and password controls.
function onKeyDown()
{
if((event.altKey) || ((event.keyCode == 8) &&
(event.srcElement.type != "text" &&
event.srcElement.type != "textarea" &&
event.srcElement.type != "password")) ||
((event.ctrlKey) && ((event.keyCode == 78) || (event.keyCode == 82)) ) || (event.keyCode == 116) ) {
event.keyCode = 0;
event.returnValue = false;}
}
Call this function from body tag onkeydown event
Filme Noi Cinema has the right answer, but the example code is a bit dated. I just needed this solution so I thought I would post the code I used.
//I use the standard DOM method for accessing the body tag, because the
//non-standard HTML DOM shortcuts are not stable. The correct behavior is
//dynamically attached to the entire body using the onkeypress event, which
//is the most stable event to target cross browser.
document.getElementsByTagName("body")[0].onkeypress = function (event) {
var a = event || window.event, //get event cross browser
b = a.target || a.srcElement; //get source cross browser
//the only thing that matters is the backspace key
if (a.keyCode === 8) {
//if you are a textarea or input type text or password then fail
if (b.nodeName === "textarea" || (b.nodeName === "input" && (b.getAttribute("type") === "text" || b.getAttribute("type") === "password"))) {
return true;
} else {
//backspace is disabled for everything else
return false;
}
}
};
This code needs to be executed before the user starts engaging the page. There are numerous ways to do this:
You can put the above code into any function that is already attached to the onload event.
You can wrap the above code that is bound to the page's onload event.
You can put the above code into a self executing function.
Examples:
//self executing function
(function () {
the solution code here
}());
//wrapper to onload event
document.getElementsByTagName("body")[0].onload = function () {
the solution code here
};
I am adding this code to Pretty Diff if you want to see an example in action.
You should be able to attach a onKeydown/Up/Press listener to your window. In this function, look at the keycode that was pressed, and at the event target. If the keycode is backspace, and the target is NOT an input box or a textarea, prevent the event.
I finally found one that works on all browsers.
It's by Hazem Saleh
His website address is:
http://www.technicaladvices.com/2012/07/16/preventing-backspace-from-navigating-back-in-all-the-browsers/
/*Starts here:*/
document.onkeydown = function (event) {
if (!event) { /* This will happen in IE */
event = window.event;
}
var keyCode = event.keyCode;
if (keyCode == 8 &&
((event.target || event.srcElement).tagName != "TEXTAREA") &&
((event.target || event.srcElement).tagName != "INPUT")) {
if (navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
event.stopPropagation();
} else {
alert("prevented");
event.returnValue = false;
}
return false;
}
};
/*Ends Here*/