How to limit characters on mouse paste event in javascript [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you handle oncut, oncopy, and onpaste in jQuery?
$(document).ready(function() {
$('#Description').bind('keyup', function() {
var characterLimit = 350;
var charactersUsed = $(this).val().length;
if (charactersUsed > characterLimit) {
charactersUsed = characterLimit;
$(this).val($(this).val().substr(0, characterLimit));
$(this).scrollTop($(this)[0].scrollHeight);
}
});
});
http://jsfiddle.net/qCasN/
This is my code. I am trying to paste some content in description box using mouse right click paste, but it is not handled by the code. I don't know where it goes wrong, can anybody help on fixing this for me.
Thanks in advance

You should use change or input events instead of keyup. If you don't mind little performance loss you could do:
$('#Description').bind('keyup change input', function () { .. });
http://jsfiddle.net/3HdAd/

You'll need to use the mouseup event, instead of the keyup event. keyup is for keyboard actions.
I am not sure if the page will receive a mouseup event from a context menu, though. (right-click -> "paste" makes you click a "paste" button on a non-DOM element.
Or the events Miszy suggested would be a better choice.

you can use onpaste event to handle this :-
$("#Description").bind("paste", function(){} );
check this link :- How do you handle oncut, oncopy, and onpaste in jQuery?

you can use the default jquery keyup event like below:
var characterLimit = 360;
$("#Description").keyup(function(){
if($("#Description").val().length > characterLimit){
$("#Description").val($("#Description").val().substring(0,characterLimit));
}
});
or you can use keydown event as
var characterLimit = 360;
$("#Description").keydown(function(){
if($("#Description").val().length > characterLimit){
return false;
}
});

Related

Detecting the event that causes focus of HTML span tag

I need to determine the event that causes the focus of an HTML span tag. The span tag is a glyhpicon from bootstrap v3.
Right now, I have a .focus() event handler attached to the span tag to catch when the focus occurs but I can't figure out how to tell if the focus was caused by a click or a tab.
HTML tag: <span class="glyphicon glyphicon-ok-circle col-xs-6"></span>
Jquery:
$("span").focus(function (e) {
var event = "click" //This "event" var is the event that caused the focus
if(event == "click"){
//do something
}else{
//if not a click event, do something else
}
});
Do I use the eventData(e) parameter to detect this?
So far, I haven't been able to find the property that shows what caused the focus inside the eventData(e) parameter. The "originalEvent" property only returns "focus" and not what caused it.
Edit: The answer in Differentiate between focus event triggered by keyboard/mouse doesn't fulfill my question. That user is trying to find whether a click or keyboard event occurs on a jquery "autocomplete" element. I need to find the event that causes the focus on a span tag... not an input tag. The ".focus()" event of the element occurs before all other events.
Answer: Check my post below.
$('span').on('focus', function(e){
$( 'span' ).mousedown(function() {
alert( "focus using click" );
});
$(window).keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
// Using tab
}
});
});
I appreciate everyone's feedback! The answer suggested in the comments helped to partially solve the problem. However, I can't give full credit because it didn't fully answer the question.
The answer suggested in the link was to create a "click" and "keypress" event to update a flag that would be checked on the ".focus()" event to determine the source of how it was triggered. My scenario was more complex. The ".focus()" event occurs before a "click()" event... so the flags wouldn't trigger until after the focus has already occurred and passed. The answer also suggested using a "setTimeout()" to make the focus event wait.. which I found unnecessary in my conclusion.
Conclusion
After some research, it was apparent that a ".mousedown()" event occurs before the ".focus()" event. Using the binded flags listed in the suggested answer above, I created the code below to solve my problem.
$(document).bind('mousedown', function () { isClick = true; }).bind('keypress', function () { isClick = false; });
$("span").focus(function () {
if (isClick) {
//Focused by click event
} else{
//Focused by keyboard event
}
});
I also noticed during research that ".bind()" has been deprecated in Jquery v3.0... so I will be switching my code to read:
$(document).mousedown(function () { isClick = true; }).keypress(function () { isClick = false; });
$("span").focus(function () {
if (isClick) {
//Focused by click event
} else{
//Focused by keyboard event
}
});
Please add any comments/suggestions/optimizations as a comment to my answer! Would love to hear other input.

JQuery focus without entering key event shortcut

Using keymaster library for defining and dispatching keyboard shortcuts, I defined shortcut key / to focus input element.
key('/', function() {
$(".topbar input").focus();
});
The issue is that when the / key is pressed, the input is focused with / entered value. I want to get rid of that.
Try this.
key('/', function(event) {
$(".topbar input").focus();
event.preventDefault();
});
It gets focused because you tell it to do so.
Remove this line:
$(".topbar input").focus();
Or give it a function so that you can do stuff when it gets focused
$(".topbar input").focus(function(){
});

Virtual Keyboard with Jquery

I have a div that operates as a button. Once the button is clicked, I want it to simulate the pressing of a key. Elsewhere on Stackoverflow, people have suggested using jQuery.Event("keydown"); but the suggestions all use a .trigger() bound to the button as opposed to .click. So, my example code looks like this:
var press = jQuery.Event("keydown");
press.which = 69; // # The 'e' key code value
press.keyCode = 69;
$('#btn').click( function() {
$('#testInput').focus();
$(this).trigger(press);
console.info(press);
});
I've set up a dummy example at JSFiddle:
http://jsfiddle.net/ruzel/WsAbS/
Eventually, rather than have the keypress fill in a form element, I just want to register the event as a keypress to the document so that a MelonJS game can have it.
UPDATE: It looks like triggering a keypress with anything other than the keyboard is likely to be ignored by the browser for security reasons. For updating a text input, this very nice Jquery plugin will do the trick: http://bililite.com/blog/2011/01/23/improved-sendkeys/
As for anyone who comes here looking for the solution in the MelonJS case, it's best to use MelonJS's me.input object, like so:
$('#btn').mousedown(function() {
me.input.triggerKeyEvent(me.input.KEY.E, true);
});
$('#btn').mouseup(function() {
me.input.triggerKeyEvent(me.input.KEY.E, false);
});
I'm not sure why, but even though this is triggering the event correctly, it doesn't fill the input with the character.
I've modified the code to show that the document is indeed receiving keypress events when we say $(document).trigger(p)
Try it out:
http://jsfiddle.net/WsAbS/3/
var press = jQuery.Event("keydown");
press.which = 69; // # Some key code value
press.keyCode = 69;
press.target = $('#testInput');
$(document).on('keydown', function(event) {
alert(event.keyCode);
});
$('#btn').click( function() {
$(document).trigger(press);
});
I believe this should be good enough for your end goal of a MelonJS game picking up keypresses.
If you want a virtual keyboard (As the title suggests) you can use this one.

How to trigger backspace on a textfield?

Say I have this:
<textarea id="myarea">Hello</textarea>
How would i trigger backspace on that textarea possibly using trigger() and key codes. The code for backspace is 8.
And i am not looking for this:
$('#myarea').val( $("myarea").val().slice(0,-1) );
I need to simulate someone actually pressing the 'backspace' key on their keyboard.
Thanks
You can create a keydown event:
var e = jQuery.Event("keydown", { keyCode: 20 });
Then trigger it in your textarea:
$("#myarea").trigger( e );
Update:
After doing some more research and testing, I realize that this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keydown event, it does not replicate the user going into the element and pressing that key.
To simulate the user going into that textbox and pressing that key, you would have to create a dispatch event
The dispatch event is also not globally supported. Your best bet would be to trigger the keydown event and then update the text area as intended.
I found this:
http://forum.jquery.com/topic/simulating-keypress-events (answer number 2).
Something like this should work, or at least give you an idea:
<div id="hola"></div>
$(function(){
var press = jQuery.Event("keyup");
press.ctrlKey = false;
press.which = 40;
$('#hola').keyup(function(e){
alert(e.which);
})
.trigger(press); // Trigger the event
});
Demo: http://jsfiddle.net/qtPcF/1/
You shouldn't be forcing key events in js. Try simulating the character removal instead.
const start = textarea.selectionStart - 1;
const value = textarea.value;
const newValue = value.substr(0, start) + a.substr(start);
textarea.value = newValue;
Or if you just want the event, instead call the handler directly, rather than forcing the event. This is too hacky.

Looking for a better workaround to Chrome select on focus bug

I have the same problem as the user in this question, which is due to this bug in Webkit. However, the workaround provided will not work for my app. Let me re-state the problem so that you don't have to go read another question:
I am trying to select all the text in a textarea when it gets focus. The following jQuery code works in IE/FF/Opera:
$('#out').focus(function(){
$('#out').select();
});
However, in Chrome/Safari the text is selected--very briefly--but then the mouseUp event is fired and the text is deselected. The following workaround is offered in the above links:
$('#out').mouseup(function(e){
e.preventDefault();
});
However, this workaround is no good for me. I want to select all text only when the user gives the textarea focus. He must then be able to select only part of the text if he chooses. Can anyone think of a workaround that still meets this requirement?
How about this?
$('#out').focus(function () {
$('#out').select().mouseup(function (e) {
e.preventDefault();
$(this).unbind("mouseup");
});
});
The accepted answer (and basically every other solution I found so far) does not work with keyboard focus, i. e. pressing tab, at least not in my Chromium 21. I use the following snippet instead:
$('#out').focus(function () {
$(this).select().one('mouseup', function (e) {
$(this).off('keyup');
e.preventDefault();
}).one('keyup', function () {
$(this).select().off('mouseup');
});
});
e.preventDefault() in the keyup or focus handler does not help, so the unselecting after a keyboard focus seems to not happen in their default handlers, but rather somewhere between the focus and keyup events.
As suggested by #BarelyFitz, it might be better to work with namespaced events in order to not accidentally unbind other event handlers. Replace 'keyup' with 'keyup.selectText' and 'mouseup' with 'mouseup.selectText' for that.
Why not simply:
$('#out').focus(function(){
$(this).one('mouseup', function() {
$(this).select();
});
});
Seems to work in all major browsers...
A very slightly different approach would be to separate the focus event from the mouse sequence. This works really nicely for me - no state variables, no leaked handlers, no inadvertent removal of handlers, and it works with click, tab, or programmatic focus. Code and jsFiddle below -
$('#out').focus(function() {
$(this).select();
});
$('#out').on('mousedown.selectOnFocus', function() {
if (!($(this).is(':focus'))) {
$(this).focus();
$(this).one('mouseup.selectOnFocus', function(up) {
up.preventDefault();
});
}
});
https://jsfiddle.net/tpankake/eob9eb26/27/
Make a bool. Set it to true after a focus event and reset it after a mouse up event. During the mouse up, if it's true, you know the user just selected the text field; therefore you know you must prevent the mouse up from happening. Otherwise, you must let it pass.
var textFieldGotFocus = false;
$('#out').focus(function()
{
$('#out').select();
textFieldGotFocus = true;
});
$('#out').mouseup(function(e)
{
if (textFieldGotFocus)
e.preventDefault();
});
$(document).mouseup(function() { textFieldGotFocus = false; });
It's important that you put the mouseup listener that resets the variable on document, since it's not guaranteed that the user will release the mouse button over the text field.
onclick="var self = this;setTimeout(function() {self.select();}, 0);"
Select the text before putting the focus on the input box.
$('#out').select().focus();
digitalfresh's solution is mostly there, but has a bug in that if you manually trigger .focus() using JS (so not using a click), or if you tab to the field, then you get an unwanted mouseup event bound - this causes the first click that should deselect the text to be ignored.
To solve:
var out = $('#out');
var mouseCurrentlyDown = false;
out.focus(function () {
out.select();
if (mouseCurrentlyDown) {
out.one('mouseup', function (e) {
e.preventDefault();
});
}
}).mousedown(function() {
mouseCurrentlyDown = true;
});
$('body').mouseup(function() {
mouseCurrentlyDown = false;
});
Note: The mouseup event should be on body and not the input as we want to account for the user mousedown-ing within the input, moving the mouse out of the input, and then mouseup-ing.
tpankake's answer converted to a reusable jQuery function..
(If you upvote this, please also upvote his answer)
Load the following AFTER loading the jQuery library:
$.fn.focusSelect = function () {
return this.each(function () {
var me = $(this);
me.focus(function () {
$(this).select();
});
me.on('mousedown.selectOnFocus', function () {
var me2 = $(this);
if (me2.is(':focus') === false) {
me2.focus();
me2.one('mouseup.selectOnFocus', function (up) {
up.preventDefault();
});
}
});
});
};
Use it like this:
$(document).ready(function () {
// apply to all inputs on the page:
$('input[type=text]').focusSelect();
// apply only to one input
$('#out').focusSelect();
});

Categories