This is my code snippet:
$.ctrl('J', function() {
$("#"+currentId).after('<div contentEditable="true">test</div>');
});
After running it, 2 divs with "test" will be added instead of 1.
What am I missing?
This is the CTRL function:
$.ctrl = function(key, callback, args) {
var isCtrl = false;
$(document).keydown(function(e) {
if (!args) args = [];
if (e.ctrlKey) isCtrl = true;
if (e.keyCode == key.charCodeAt(0) && isCtrl) {
callback.apply(this, args);
return false;
}
}).keyup(function(e) {
if (e.ctrlKey) isCtrl = false;
});
};
Thank you in advance.
Greetings
Edit:
maybe it has something to do with this:
$('div[id|="edid"]').focus(function() {
$('div[id|="edid"]').removeClass('onFocus');
$(this).addClass('onFocus');
var currentId = $(this).attr('id');
});
I've had a similar problem. May be you are using an old jquery version?
Major Bugfix in JQuery 1.4.4
- A function bound to the document ready event will now fire once (it
was firing twice).
What’s New in JQuery 1.4.4
You're probably including jQuery two times in your HTML code. Like this:
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
Related
I have created a simple code to handle keypress event:
var counter = 0;
$('input').on('keypress', function () {
$('div').text('key pressed ' + ++counter);
});
JSFiddle.
But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+).
What could be the issue?
I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.
Use the keyup event:
// JavaScript:
var counter = 0;
document.querySelector('input').addEventListener('keyup', function () {
document.querySelector('div').textContent = `key up ${++counter}`;
});
// jQuery:
var counter = 0;
$('input').on('keyup', function () {
$('div').text('key up ' + ++counter);
});
Use jQuery's input event, like this:
$( 'input' ).on( 'input', function() {
...
} );
With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/
$(document).ready(function() {
var pattForZip = /[0-9]/;
$('#id').on('keypress input', function(event) {
if(event.type == "keypress") {
if(pattForZip.test(event.key)) {
return true;
}
return false;
}
if(event.type == 'input') {
var bufferValue = $(this).val().replace(/\D/g,'');
$(this).val(bufferValue);
}
})
})
Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.
Eg:
function getKeyCode(str) {
return str && str.charCodeAt(0);
}
function keyUp(){
var keyCode = getKeyCode("1");
}
I think it is bad idea to use other events in place of 'keypress'.
What you need to do is just include a jQuery file into your project.
A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.
You can download it from : https://jquerymobile.com/download/
I use the following function on keyup event to redirect to another javascript function.
Problem is it does'nt seem to fire, although it does bind the function to the textbox.
$(document).ready(function () {
EnablePickTargetButton();
//clear contents; use a delay because tinyMCE editor isn't always fully loaded on document.ready
var t = setTimeout(function () {
if (typeof textEditorForCreate != 'undefined' && tinymce.editors.length > 0)
tinyMCE.activeEditor.setContent('');
}, 300);
var txtSearchUser = $('#txtSearchUser');
if(typeof txtSearchUser != 'undefined')
{
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
searchUser();
}
else
alert('cucu');
});
}
});
Not even the alert shows up. Checking the html, I can see it doesn't add onkeyup to the textbox; The textbox is in a popup window hosted in a div on the form; But on document.ready it runs the function without error.
Try this delegate on document or closest static element. (If the element is added dynamically)
$(document).on('keyup','#txtSearchUser',function(){
//Code
});
it works :
$(document).ready(function(){
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
else
alert('cucu');
});
});
http://jsfiddle.net/jMk5S/
check if you're referencing your html element properly. Perhaps you mix id with the class?
I edited your code and is working :
The problem is in your document ready function , you have a syntax error , next time check console in your browser to see what's wrong :
DEMO HERE
$(document).ready(function () {
//EnablePickTargetButton();
//clear contents; use a delay because tinyMCE editor isn't always fully loaded on document.ready
var t = setTimeout(function () {
if ($('#textEditorForCreate').length != 0 && tinymce.editors.length > 0)
tinyMCE.activeEditor.setContent('');
}, 300);
if($('#txtSearchUser').length!=0)
{
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
searchUser();
}
else
alert('cucu');
});
}
});
I googled and got the following codes on the Net.However, when I press a keyboard key,it is not displaying me an alert box. I want to get which character I have pressed in the alert box. How do I fix this?
<script type="text/javascript">
var charfield=document.getElementById("char")
charfield.onkeydown=function(e){
var e=window.event || e;
alert(e.keyCode);
}
</script>
</head>
<body id="char">
</body>
</html>
If you want to get the character typed, you must use the keypress event rather than the keydown event. Something like the following:
var charfield = document.getElementById("char");
charfield.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode > 0) {
alert("Typed character: " + String.fromCharCode(charCode));
}
};
try this jquery code
$("body").keypress(function(e){
alert(e.which);
});
I can't off the top of my head think of a good situation in which to use the "on some event" method of a DOM element to deal with events on that element.
The best practice is to use addEventListener (or attachEvent in older versions of Internet Explorer) like so:
charfield.addEventListener('keydown', function (e) { alert(e.keyCode); }, false);
If you want to account for attachEvent as well:
(function (useListen) {
if (useListen) {
charfield.addEventListener('keydown', alertKeyCode, false);
} else {
charfield.attachEvent('onkeydown', alertKeyCode);
}
})(charfield.addEventListener);
function alertKeyCode(e) {
alert(e.keyCode);
}
You'll get the appropriate key code:
charfield.onkeydown=function(evt){
var keyCode = (evt.which?evt.which:(evt.keyCode?evt.keyCode:0))
alert(keyCode);
}
How can I disable Paste (Ctrl+V) option using jQuery in one of my input text fields?
This now works for IE FF Chrome properly... I have not tested for other browsers though
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
Edit: As pointed out by webeno, .bind() is deprecated hence it is recommended to use .on() instead.
Edit: It's almost 6 years later, looking at this now I wouldn't recommend this solution. The accepted answer is definitely much better. Go with that!
This seems to work.
You can listen to keyboard events with jQuery and prevent the event from completing if its the key combo you are looking for.
Note, check 118 and 86 (V and v)
Working example here:
http://jsfiddle.net/dannylane/9pRsx/4/
$(document).ready(function(){
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
alert('thou. shalt. not. PASTE!');
event.preventDefault();
}
});
});
Update:
keypress doesn't fire in IE, use keydown instead.
As of JQuery 1.7 you might want to use the on method instead
$(function(){
$(document).on("cut copy paste","#txtInput",function(e) {
e.preventDefault();
});
});
jQuery('input.disablePaste').keydown(function(event) {
var forbiddenKeys = new Array('c', 'x', 'v');
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
return false;
}
}
}
return true;
});
I tried this in my Angular project and it worked fine without jQuery.
<input type='text' ng-paste='preventPaste($event)'>
And in script part:
$scope.preventPaste = function(e){
e.preventDefault();
return false;
};
In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.
The following code will disable cut, copy and paste from full page.
$(document).ready(function () {
$('body').bind('cut copy paste', function (e) {
e.preventDefault();
});
});
The full tutorial and working demo can be found from here - Disable cut, copy and paste using jQuery
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtInput" />
You can catch key event :
function checkEventObj ( _event_ ){
// --- IE explorer
if ( window.event )
return window.event;
// --- Netscape and other explorers
else
return _event_;
}
document.keydown = function(_event) {
var e = checkEventObject(_event);
if( e.ctrlKey && (e.keyCode == 86) )
window.clipboardData.clearData();
}
Not tested but, could help.
Source from comentcamarche and Zakaria
$(document).ready(function(){
$('#txtInput').live("cut copy paste",function(e) {
e.preventDefault();
});
});
On textbox live event cut, copy, paste event is prevented and it works well.
I have tested the issue on chrome browser and it is working for me.Below is a solution for preventing the paste code in your textbox and also prevent the right click.
$(".element-container").find('input[type="text"]').live("contextmenu paste", function (e) {
e.preventDefault();
});
$(document).ready(function(){
$('input').on("cut copy paste",function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
I'm having troubles getting the attachEvent to work. In all browsers that support the addEventListener handler the code below works like a charm, but in IE is a complete disaster. They have their own (incomplete) variation of it called attachEvent.
Now here's the deal. How do I get the attachEvent to work in the same way addEventListener does?
Here's the code:
function aFunction(idname)
{
document.writeln('<iframe id="'+idname+'"></iframe>');
var Editor = document.getElementById(idname).contentWindow.document;
/* Some other code */
if (Editor.attachEvent)
{
document.writeln('<textarea id="'+this.idname+'" name="' + this.idname + '" style="display:none">'+this.html+'</textarea>');
Editor.attachEvent("onkeyup", KeyBoardHandler);
}
else
{
document.writeln('<textarea id="hdn'+this.idname+'" name="' + this.idname + '" style="display:block">'+this.html+'</textarea>');
Editor.addEventListener("keyup", KeyBoardHandler, true);
}
}
This calls the function KeyBoardHandler that looks like this:
function KeyBoardHandler(Event, keyEventArgs) {
if (Event.keyCode == 13) {
Event.target.ownerDocument.execCommand("inserthtml",false,'<br />');
Event.returnValue = false;
}
/* more code */
}
I don't want to use any frameworks because A) I'm trying to learn and understand something, and B) any framework is just an overload of code I'm nog going to use.
Any help is highly appreciated!
Here's how to make this work cross-browser, just for reference though.
var myFunction=function(){
//do something here
}
var el=document.getElementById('myId');
if (el.addEventListener) {
el.addEventListener('mouseover',myFunction,false);
el.addEventListener('mouseout',myFunction,false);
} else if(el.attachEvent) {
el.attachEvent('onmouseover',myFunction);
el.attachEvent('onmouseout',myFunction);
} else {
el.onmouseover = myFunction;
el.onmouseout = myFunction;
}
ref: http://jquerydojo.blogspot.com/2012/12/javascript-dom-addeventlistener-and.html
The source of your problems is the KeyBoardHandler function. Specifically, in IE Event objects do not have a target property: the equivalent is srcElement. Also, the returnValue property of Event objects is IE-only. You want the preventDefault() method in other browsers.
function KeyBoardHandler(evt, keyEventArgs) {
if (evt.keyCode == 13) {
var target = evt.target || evt.srcElement;
target.ownerDocument.execCommand("inserthtml",false,'<br />');
if (typeof evt.preventDefault != "undefined") {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
/* more code */
}
Just use a framework like jQuery or prototype. That's what they are there for, this exact reason: being able to do this sort of thing w/out having to worry about cross-browser compatibility. It's super easy to install...just include a .js script and add a line of code...
(edited just for you Crescent Fresh)
With a framework, the code is as simple as...
<script type='text/javascript' src='jquery.js'></script>
$('element').keyup(function() {
// stuff to happen on event here
});
Here is a function I use for both browsers:
function eventListen(t, fn, o) {
o = o || window;
var e = t+Math.round(Math.random()*99999999);
if ( o.attachEvent ) {
o['e'+e] = fn;
o[e] = function(){
o['e'+e]( window.event );
};
o.attachEvent( 'on'+t, o[e] );
}else{
o.addEventListener( t, fn, false );
}
}
And you can use it like:
eventListen('keyup', function(ev){
if (ev.keyCode === 13){
...
}
...
}, Editor)
Different browsers will process events differently. Some browsers have event bubble up throw the controls where as some go top down. For more information on that take a look at this W3C doc: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
As for this specific issue setting the "userCapture" parameter to false for the addEventListener will make events behave the same as Internet Explorer: https://developer.mozilla.org/en/DOM/element.addEventListener#Internet_Explorer
You might be better off using a JavaScript framework such as MooTools or jQuery of your choice to ease cross-browser support. For details, see also
http://mootools.net/docs/core/Element/Element.Event
http://api.jquery.com/category/events/
MooTools port of parts of your sample code:
var Editor = $(idname).contentWindow.document;
...
$(document.body).grab(new Element('textarea', {
'id' : this.idname,
'name' : this.idname,
'style': 'display:none;',
'html' : this.html
});
Editor.addEvent('keyup', KeyBoardHandler);
By the way, is it on purpose that you use both idname and this.idname in the code above ?