Paste event in Javascript - javascript

How can I handle the paste selected through right click in javascript?
I tried with "onpaste" event and all other html events available but nothing works.

The onpaste event should work in all modern browsers (UPD Including Opera >= 12.101).
Bind it in jQuery like this:
$('#txt').on('paste', function() {console.log('text pasted!')})​
Here's a live example:
http://jsfiddle.net/7N6Xq/
In pure JavaScript it would look something like this for modern browsers
elem.addEventListener ("paste", handler, false); // all browsers and IE9+
and for old IE versions:
elem.attachEvent ("onpaste", handler); // IE<9
You can also combine it with oninput and other events (change, propertychange, dragdrop, etc.) to create a relatively bulletproof tracking of content change.
Footnotes:
1 Opera supports Clipboard API starting from Presto/2.10.286 which corresponds to 12.10 as suggested here. Blink versions of Opera (starting from 15) should also support it but I am unable to test it as there is still no Linux version.

The event isn't exposed by default as "onpaste" IIRC. You can do it quite simply in jQuery by issuing
jQuery(document).bind('paste', function(e){ alert('paste event caught') });

I was surprised question #4532473 got closed unanswered about what happens if you want to capture the afterpaste event. As this is probably the problem half of the cases a possible approach in firefox (tested) is to register an oninput event right inside the onpaste handler and remove the oninput handler as soon as it's done executing.
In ie the onpropertychange should be used instead of oninput. (not tested)

Nice pure JS solution (as requested...) is available on the Mozilla dev site
<!DOCTYPE html>
<html>
<head>
<title>onpaste event example</title>
</head>
<body>
<h1>Play with this editor!</h1>
<textarea id="editor" rows="3" cols="80">
Try pasting text into this area!
</textarea>
<script>
function log(txt) {
document.getElementById("log").appendChild(document.createTextNode(txt + "\n"));
}
function pasteIntercept(evt) {
log("Pasting!");
}
document.getElementById("editor").addEventListener("paste", pasteIntercept, false);
</script>
<h2>Log</h2>
<textarea rows="15" cols="80" id="log" readonly="true"></textarea>
</body>
</html>

Related

How to use relatedTarget across browsers?

Firefox supports relatedTarget for the focus/blur but not the focusin/focusout event.
IE supports it only for the focusin/focusout but not the focus/blur event.
Chrome supports both.
Is there a way to use relatedTarget across browsers?
Here is a blur example (working in Chrome and FF but not IE):
https://jsfiddle.net/rnyqy78m/
And here a focusin example (working in Chrome and IE but not FF):
https://jsfiddle.net/rnyqy78m/1/
Edit
I ended up using browser detection. So I use
var eventType;
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
eventType = 'blur';
} else {
eventType = 'focusout';
}
and then ….addEventListener(eventType, …).
(Posting as an answer so I can use code sample. Although this is more meant to be a comment.)
There's alot of duplicates of this question on SO, just no answers that work 100% of the time. Then again, this problem doesn't come up that often once you get to large/complex apps. If I need the order a user manipulated stuff in, I just save it as a variable.
So my code would just reverse the logic and use 'focus' instead of blur if you need it to work for the first focus as well.
If the blur event also needs to happen if the user doesn't click another input event, I would also bind the focus event handler to any click event on the page.
This kind of strategy would be crossbrowser, it's just not pretty and/or efficient.
This isn't perfect, since it will trigger two events after the first click, but that can be solved easily. But with playign around with the code a bit, it should be possible to find a combination of events that mimic the behaviour needed. (So I'd need more details on when the console element should get the id written or not to write anm exact implementation.)
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<input id="one" value="focus me first">
<input id="two" value="focus me next">
<input id="console">
<script>
var currentElement,
inputOne = document.getElementById('one'),
inputTwo = document.getElementById('two'),
inputConsole = document.getElementById('console'),
focusHandler = function( event ) {
if (currentElement) inputConsole.value += currentElement.id;
currentElement = event.target;
};
inputOne.addEventListener('focus', focusHandler);
inputTwo.addEventListener('focus', focusHandler);
// optional handler for 'focus non-input elements', aka blur the prev clicked element.
document.addEventListener('click', focusHandler);
</script>
</body>
</html>

jQuery document ready not working properly on IE

I am using jQuery .ready function to add some ajax calls on text input to my registration page's TextBoxes.
It's all working fine on Chrome, Firefox and Safari, but won't work on Internet Explorer (I'm using IE11).
This is the code I'm using on $(document).ready():
$(document).ready(function () {
$(reg_user).on('input', function (e) { ValidateEmailPass(reg_user); });
$(reg_pass).on('input', function (e) { ValidateEmailPass(reg_pass); });
$(reg_email).on('input', function (e) { ValidateEmailPass(reg_email); });
$(reg_age).on('input', function (e) { ValidateEmailPass(reg_age); });
});
It fires the validation function every time the text changes in them. Although, I IE, it tells me reg_user is undefined which causes an error and it won't trigger these functions.
I'm using jQuery 1.11.3 which supports old versions.
If you know how to fix it, please tell me. I don't know what's really causing this problem. I think IE acts otherwise with $(document).ready().
Replace
$(reg_user)
with right element(s) selector (ID or Class). You can't create link (var reg_user) to DOM element before DOM will ready.
P.S. Also IE11 has some problems with input event.
Here's a good read.
The oninput event is supported in Internet Explorer from version 9. If
you need an event that fires when the contents of these elements are
modified in Internet Explorer before version 9, use the
onpropertychange event.
So instead, you could use change - which as the comments suggest doesn't do exactly the same, but it is cross-browser compatible. Also, you should use valid selectors instead of a global variable. This is simply bad practice and I don't know how this behaves on all browsers.

Setting oninput event with JavaScript

The HTML5 oninput event is supported by some modern browsers, including Firefox 3.X
However, strangely, it only seems to work with inline JavaScript:
<input id = "q" oninput="alert('blah')">
When I try to set it using JavaScript code, it doesn't fire.
var q = document.getElementById("q");
q.oninput = function(){alert("blah");};
Is this just a bug in Firefox, or is there some reason this happens?
After downloading FireFox v3.6.27 and doing some test and search. I found my previous answer was wrong.
What I got is:
the oninput event property is supported in Firefox from version 4.
So to add a event listener in this case, you can do either
<input id = "q" oninput="alert('blah')">
or
q.addEventListener('input', function(){alert("blah");}, true);
But I prefer the later way. You can find reasons in addEventListener.
Also a similar function in IE attachEvent.

onpropertychange event vs keyup

I'm trying to mimic Google suggestions over here: yous-design
It works perfect in Chrome/Firefox etc. but not in IE. I googled for it and it turns out that IE doesn't support the oninput event which in the code looks like this:
el("inp").oninput=function(){
addScript("http://www.google.nl/complete/search?callback=suggest&q="+this.value);
}
Instead I would have to use the onpropertychange event for IE. But when I replace the event it still doesn't work. I think this piece of code is counteracting:
$('#inp').keydown(
function (e){
var curr = $('#test').find('.current'); etc.etc.etc.
I think the keydown(/keyup) is counteracting with the onpropertychange event. But what should I replace keydown/keyup with? Are there any other alternatives at all? Should I rewrite the code?
I would suggest that instead of onpropertychange, use onKeyUp on IE.
onpropertychange is buggy in IE and doesn't fire for all keys (delete and backspace I think).

Opera ignoring .live() event handler

I have the following jQuery which works in all major browsers except Opera:
jQuery(document).ready(function () {
jQuery("#GetResults").live("click", function(e){
e.preventDefault(); //Opera doesn't execute anything here
});
};
Which is supposed to fire when clicking the following link:
<a id="GetResults" href="Folder/File/javascript:void(0);">Get Results</a>
Only Opera ignores this. Any ideas?
Edit:
I've just discovered that if I substitute out .live() for .bind() everything functions as expected. I can't find any documentation relating to .live() bugs in Opera though, and it does work in jsFiddle which would point at something environmental. What could be causing this behavour?
This needs clarification. The answers above are correct, but nobody clearly explained where your problem comes from.
In fact I think that you could probably reproduce the problem in other browsers too.
That's because of how .live works:
It binds to the event on document and waits for a particular event to bubble up to there. Then it checks if the event.target is what you wanted to handle. *
If you click on a link element it's quite possible that the browser goes to the new page before the event bubbles high enough to trigger your code. In an app with lots of HTML and event handlers all the browsers should have problems. Opera just starts displaying the new page and destroys the previous quicker in this case. It really depends on a particular situation more than on the browser. For example: you probably won't see this happen if you had a high network latency while connecting to the site.
To prevent default action on a a element you have to use .bind like in the old days ;) when a eveloper had to be aware of what he loads with AJAX and bind new events to that in a callback.
* There is more to that and .live is more complicated. I just described what is needed here.
What happens when you attach the handler using:
$ (something).bind ("click", function (e) {
// do something
})
You can also try to attach the handler using .click() method.
The following code works as expected in Opera 11.50.
<!doctype html>
<title></title>
<a id="GetResults" href="http://google.com">Get Results</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery("#GetResults").live("click", function(e){
alert('doing something');
e.preventDefault(); //Opera doesn't execute anything here
});
});
</script>
Either it is a corrected bug, or something more subtle.
Can you check whether the above works on your version of Opera / jQuery?
Read this article: http://jupiterjs.com/news/why-you-should-never-use-jquery-live
try use delegate instead
Not sure if you want to do it, or if it will work for you. I had similar issues with Opera 9.5 and e.preventDefault() not working, the only solution I found was to just return false...
jQuery(document).ready(function () {
jQuery("#GetResults").live("click", function(e){
e.preventDefault();
return false;
});
};
There are two aspects of an event bubbling worth considering in this case: propagation and the default action.
Propagation refers to the event bubbling. First the anchor tag gets the click event, then its parent element, then its parent's parent, and so forth, up to the document element. You can stop an event from propagating at any time by calling e.stopPropagation().
The default action is what the browser will do if nothing is done to prevent it. The most well-known case is when an anchor with an href is clicked, the browser will try to navigate there. There are other examples too, though, for example when you click and drag an image, many browsers will create a ghost image you can drop on another application. In both cases, you can stop the browser from doing the default action at any time by calling e.preventDefault()
As mentioned in other answers to this question, jQuery's .live() feature sets a handler at a high level element (like document) and takes action after events have propagated up. If a handler in between the anchor and the document calls e.stopPropagaiton() without calling e.preventDefault() it would stop the live handler from responding, while still allowing the browser to navigate (the default action).
I doubt this is what's happening, since it would affect all browsers, but it's one possible explanation.
Ensure that document.ready event happens before you click on link.
Try to put all lives in the top of the document.ready wrapper. It may help, if you have a lot of javascript code.

Categories

Resources