When i paste any text in any element with 'contentEditable' flag enabled, IE automatically finds the hyperlinks or email address and replaces them with
hyperlink.
How can i disable this automatic url detection for elements(e.g. div, span etc.) with 'contentEditable' flag in IE or aleast get the actual text that was pasted in the div.
Best Regards,Keshav
Unfortunately, there is no cross-version solution.
In IE9 there is opportunity, allowing to disable automatic hyperlinking:
document.execCommand("AutoUrlDetect", false, false);
More information: http://msdn.microsoft.com,
http://bytes.com
I don't think you can. You'll need catch the paste event and set a brief timer that calls a function that removes links.
Edit 30 September 2012
IE 9 and above has the ability to switch this off. See Maxon's answer.
I use preventDefault on space key, enter key, tab key's keydown event to prevent URL detection. Tested on IE11 and Chrome.
document.getElementById("input").addEventListener("keydown", function (e) {
var SPACEKEY = 32;
var ENTERKEY = 13;
var TABKEY = 9;
var whiteSpace = "";
if (e.keyCode == SPACEKEY || e.keyCode == ENTERKEY || e.keyCode == TABKEY) {
e.preventDefault();
if (e.keyCode == SPACEKEY) {
whiteSpace = " ";
} else if (e.keyCode == ENTERKEY) {
whiteSpace = "\n";
} else if (e.keyCode == TABKEY) {
whiteSpace = "\t";
}
var selection = document.getSelection();
var start = selection.anchorOffset > selection.focusOffset ? selection.focusOffset : selection.anchorOffset;
var end = selection.anchorOffset > selection.focusOffset ? selection.anchorOffset : selection.focusOffset;
$(this).text($(this).text().substring(0, start)
+ " "
+ $(this).text().substring(end));
var range = document.createRange();
range.setStart($(this)[0].firstChild, start + 1);
range.setEnd($(this)[0].firstChild, start + 1);
selection.removeAllRanges();
selection.addRange(range);
}
return false;
});
It seems that it works for Chrome: Hold Ctrl+Alt to disable the links temporarily. This extension disables links when you hold Ctrl+Alt. This allows to select text from the middle of the link, and generally eases selection, eliminating the risk to click the link while copying it.
Related
Move across each word in a sentences.
I have created shortcut key for enter in my application as, it will move towards and focus each input control in my page.
I need to set keyboard shortcuts for tab as, it has to select each string of a sentences which are in some textbox. For example txtAddress contain value like "Hi i am new user", if I press tab key it has to select a string "hi" then "i" then "am" then "new" then "user" after that it has to focus a next input control.
I have tried with following JS to focus next input control but don't know how to select each word in textbox.
$(document).unbind('keydown');
$(document).bind('keydown', 'tab', function assets() {
try {
var inputs = $(":input:not(input[type='hidden'])");
var CurInput = inputs.get(inputs.index(document.activeElement));
var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
if (CurInput && nextInput.type == "text" && CurInput.style.display != "none") {
var strval = CurInput.value;
if (!strval) {
if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
}
}
else if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
return false;
}
catch (e) {
}
});
http://jsbin.com/cihahigevo/1/edit?html,js,output
var textarea = $('textarea')[0],
index = 0;
$(document).on('keydown.tab', function(e){
if( e.keyCode == 9 ){
textarea.focus();
textarea.value = textarea.value.trim() + ' ';
index = textarea.value.indexOf(' ', index) + 1;
textarea.setSelectionRange(0, index);
}
return false;
});
It's never a good idea to override a users keyboard, especially the tab button.
The tab button is used by people who (for whatever reason) don't use a mouse to navigate sites by 'tabbing' between buttons, form fields, etc.
If you remove this functionality by overriding the tab key, you've suddenly made your site unaccessible to these users.
You may also run afoul of you countries laws on website accessibility (the Disability & Discrimation act in the UK).
The website I'm building has a searchbar at the top of it. Similar to Trello or Gmail I want to make it so when the user pushes the "/" key, their focus goes to that searchbox.
My javascript looks like this:
document.onkeydown = checkShortcuts;
function checkShortcuts(event) {
console.log(event.keyCode);
if (event.keyCode == 191) { // 191 == "/" key
var text_input = document.getElementById ('sitesearch');
text_input.focus ();
text_input.select ();
$('#sitesearch').val("");
}
}
The problem I'm having is that upon hitting the / key, not only is the focus put on my search bar, but the "/" character is ALSO displayed in my search bar. I've tried to remove that by doing a jquery .val("") but that gets conducted before the letter is typed.
If I move the onkeydown to onkeyup, then when I type "/" I get the quick find window in firefox which isn't what I want either.
Any ideas how I can set focus but then not type that character onto the text field?
If you already mixing JS/jQuery you could make it shorter e.g.
$(document).keydown(function() {
if(event.keyCode == 191) {
$('#sitesearch').focus();
return false;
}
});
One alternative is using setTimeout function.
JSFiddle
document.onkeydown = checkShortcuts;
function checkShortcuts(event) {
if (event.keyCode == 191) { // 191 == "/" key
var text_input = document.getElementById ('sitesearch');
text_input.focus ();
text_input.select ();
setTimeout(function(){$('#sitesearch').val("")},50);
$('#').val("");
}
}
Another alternative is simply returing false as #Goose mentioned:
JSFiddle
document.onkeydown = checkShortcuts;
function checkShortcuts(event) {
if (event.keyCode == 191) { // 191 == "/" key
var text_input = document.getElementById ('sitesearch');
text_input.focus ();
text_input.select ();
return false;
}
}
I tried to use this for a simple hotkey function, that reacts to keypress for some keys, but doesn't if your editing in the box with the given ID. Unfortunately now Hotkeys are disabled always. I get the alert() all the time :(
the textfield is on e.g. http://tyrant.40in.net/kg/news.php?id=160#comments
Inside the text area it works but my script does not recognize, whether I'm inside the text area or outside (it also doesn't help to click in textarea and click outside).
Please help me.
I also tried to do it another way by selecting (!$('#tfta_1 #search')) instead of $('html'), so that the hotkeys do not work wenn you are in of of these IDs. Unfortunately this did not work ether.
edit: the js also has tocheck if crtl, alt, shift to avoid interpret
// Hotkeys (listen to keyboard input)
$('html').keypress(
function(event){
// is cursor at the beginning / end of edit box
var textInput = document.getElementById("tfta_1"), val = textInput.value;
var isAtStart = false, isAtEnd = false;
if (typeof textInput.selectionStart == "number") {
// Non-IE browsers
isAtStart = (textInput.selectionStart == 0);
isAtEnd = (textInput.selectionEnd == val.length);
} else if (document.selection && document.selection.createRange) {
// IE branch
textInput.focus();
var selRange = document.selection.createRange();
var inputRange = textInput.createTextRange();
var inputSelRange = inputRange.duplicate();
inputSelRange.moveToBookmark(selRange.getBookmark());
isAtStart = inputSelRange.compareEndPoints("StartToStart", inputRange) == 0;
isAtEnd = inputSelRange.compareEndPoints("EndToEnd", inputRange) == 0;
}
// combine information -> is cursor in edit box?
var eb = isAtStart + isAtEnd;
// if in comment box
if ( eb ) {
// do nothing
alert('You are in the comment box');
}
// if key 'p' is pressed
else if (event.which == 112){
// open profile page
window.location = home + 'profile.php';
}
// if key 'q' is pressed
else if (event.which == 113){
// open quests overview
window.location = home + 'quests.php';
}
// if key 'r' is pressed
else if (event.which == 114){
// open raids overview
window.location = home + 'raids.php';
}
// if key 'f' is pressed
else if (event.which == 102){
// open fraction tracker
window.location = home + 'factiontracker.php';
}
}
);
You need to check the event.target property.
if ('textarea' == event.target.tagName.toLowerCase()) {
return;
}
Or:
if ($(event.target).is('textarea')) {
return;
}
As for the modifier keys, see event.shiftKey, event.ctrlKey and event.altKey.
This involves HTML + JS and/or JQuery:
I would have commented on the previous post, but I don't have comment reputation or cannot comment for some reason.
Josh Stodola's great code from Part I is as follows:
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
This works great except .replace puts the cursor at the end of the string on every keyup (at least in IE8 and Chrome).
As a result, it renders the left & right cursor keys useless, which is needed inside the input box.
Is there any way to enhance the above code so that the cursor keys do not activate it, but so that the text still gets updated on the fly?
The best solution is to avoid using key events to capture text input. They're not the best tool for the job. Instead, you should use the HTML5 oninput event (supported in the latest and recent versions of every current major browser) and fall back to onpropertychange for older versions of Internet Explorer:
var alreadyHandled;
txt.bind("input propertychange", function (evt) {
// return if the value hasn't changed or we've already handled oninput
if (evt.type == "propertychange" && (window.event.propertyName != "value"
|| alreadyHandled)) {
alreadyHandled = false;
return;
}
alreadyHandled = true;
// Your code here
});
These events don't fire for keys that don't result in text entry — don't you just hate it when you shift-tab back to a form element and the resulting keyup event causes the page's script to move focus forward again?
Additional benefits over key events:
They fire immediately when the key is pressed and not when the key is lifted, as in keyup. This means you don't get a visual delay before any adjustments to the text are made.
They capture other forms of text input like dragging & droppping, spell checker corrections and cut/pasting.
Further reading at Effectively detecting user input in JavaScript.
Update the function:
var func = function(e) {
if(e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40){
txt.val(txt.val().replace(/\s/g, ''));
}
}
try:
$(function() {
var txt = $("#myTextbox");
var func = function(e) {
if(e.keyCode != "37" && e.keyCode != "38" && e.keyCode != "39" && e.keyCode != "40"){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(function(evt){
if(evt.keyCode < 37 || evt.keyCode > 40) {
func;
}
}).blur(func);
});
Something like that should do it. It will run the function if the keycode isn't 37,38,39 or 40 (the four arrow key keycodes). Note that it won't actually stop the cursor position moving to the end when any other key is pressed. For that, you'd need to keep track of the current cursor position. Take a look at this link for jCaret plugin, which can do this
Is it possible to bind Ctrl+Alt+L to insert predefined string into focused textarea to cursor position? For example, I'm typing some text in textarea, then I'm pressing Ctrl+Alt+L and is inserted into current cursor position.
Yes. Use the keydown event and one of the caret-position-in-textarea functions floating around on Stack Overflow. For the key detection, note I've had to use the keydown event rather than the keypress event (which is what should be used for detecting what character has been typed) because IE doesn't fire the keypress events for Ctrl+Alt+L, so this could go wrong on differently mapped keyboards. For the cursor position, I've copied from this answer and have used something similar myself. See these answers for discussion of the problems with this in IE:
Caret position in textarea, in characters from the start
Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
Also, note that you may want to position the cursor somewhere sensible after doing this, which my code doesn't cover.
function getCaret(el) {
if ("selectionStart" in el) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(), rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint("EndToStart", re);
return rc.text.length;
}
return 0;
}
var textArea = document.getElementById("yourTextarea");
textArea.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.altKey && evt.keyCode == 76) {
var cursorPos = getCaret(this);
this.value = this.value.slice(0, cursorPos)
+ ''
+ this.value.slice(cursorPos)
return false; // Prevent any default browser behaviour
}
};
I'm not sure about Ctrl-Alt-L, but there are definately ways to do this. For example:
<textarea name="MyText" id="MyText" onKeyPress="handleKey(this);"
onKeyDown="CaptureKeyDown(this);"></textarea>
<script>
function handleKey(ta) {
if (event.keyCode == 12) { // Ctrl-L
// Do your insert here
}
}
</script>
It is more complicated than this. Check out this HTML editor (written in HTML and JavaScript) at http://www.boltbait.com/htmleditor/ (the source can be downloaded there).
EDIT: Oops! I didn't see your jquery tag.