Html 5 drag and drop to input file - javascript

I have no idea if this is possible, I can't seem to find anything.
What I want is to offer the user the option of either "drag drop" an image or use the normal html file input box.
I don't the image to be uploaded until the form is saved. So I guess the drag and drop area would just update the field?
How would I go about doing that?
Thanks in advance.

I came here looking for the same answer. Ended up do the following, which looks to fit your need.
Make a div for your image drop box, then add your input type="file" inside the div. Set height and width as desired. Set opacity to 0. Now your input fills the div, can't be seen, but still functions.
<div class="divClass">
<input class="inputClass" name="inputName" type="file">
</div>
Styles below
<Style>
.divClass{
position: relative;
// anything else
}
.inputClass{
opacity: 0;
position: absolute;
top:0;
left: 0;
height: x // as desired
width: x // as desired
}
</style>
=== Edit ===
Ignore my styling up there, you really just need to use a form with an input type=file. Style/layout as needed.
As pointed out, by Shazoo, drag and drop of image does not work in IE. Works with Firefox and Chrome. Unsure of Opera and Safari. You cannot use JavaScript on the input type=file for security reasons -- it is read only as Jasny said, so you have to rely on what the browser vendor allows.
With that in mind, you can just give the IE user the option of clicking the field to select and upload a file. The default input type="file" in IE offers this ability, so as long as you leave the input visible, they should see it. (Default Edge input type=file)
Filter for IE example (based on https://stackoverflow.com/a/31757969/3136874)
function stopIeDefault(){
window.addEventListener("dragover",function(e){
e = e || event;
e.preventDefault();
},false);
window.addEventListener("drop",function(e){
e = e || event;
e.preventDefault();
},false);
}
if (/MSIE 10/i.test(navigator.userAgent)) {
// This is internet explorer 10
stopIeDefault()
}
if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
// This is internet explorer 9 or 11
stopIeDefault()
}
if (/Edge\/\d./i.test(navigator.userAgent)){
// This is Microsoft Edge
stopIeDefault()
}
This tests for IE and edge. If it detects a version then it will use stopIeDefault to preventDefault for drag and drop. This keeps IE from loading the image if someone drags and drops it on the form. (Edge appears to prevent this by default, so you may not need to call stopIeDefault as I have.) Additionally, you could apply a different style or add blocks of code or what not to deal with IE. According to w3schools, IE browser share is 5.2-6.2% as of August 2016: http://www.w3schools.com/browsers/default.asp, if that helps you decide what to do.
If anyone can confirm if drag and drop works on safari or opera, please do.
=== Edit ===

No it can't be done. Dropped files can only be uploaded through AJAX.
The only way to upload a file in a normal HTML form is through <input type="file"> and file inputs are read-only.

Related

The script conflicts with the layout alignment of my responsive template.. How I can fix it?

I copied and customized one script taken from a past stackoverflow discussion. And now I can prevent the "Print screen" with the current key combinations: "ctrl+alt+printscr" , "ctrl+printscr" and "alt+printscr". But after I saved my blogger template, I did some tests with great resoults: the script really works great.. But not as expected, I encountered two problems:
If I click the address bar or leave the page unactive, the script automatically show the background image to cover the layout.
If I try to resize the window, the alignment of the elements fails..
I'm not expert with the javascript language, so probably I made some sort of mistake. I made a picture to show you the nature of the problem.
PS: My layout is totally responsive and I never got problems with the automatic alignment of the elements. Then I tried to remove the latest javascript and again works perfectly. Probably I made some unknown mistake into the code.
I installed many anti-stealing protection scripts, jquery and css (but they not conflict apparently..) Here is a screen demostration of the problem
Here is the code:
<script language='JavaScript'>
function copyToClipboard() {
// Create a "hidden" input
var aux = document.createElement("input");
// Assign it the value of the specified element
aux.setAttribute("value", "You can no longer give printscreen. This is part of the new system security measure.");
// Append it to the body
document.body.appendChild(aux);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
alert("Print screen disabled.");
}
$(window).keyup(function(e){
if(e.keyCode == 44){
copyToClipboard();
}
});
$(window).focus(function() {
$("body").show();
}).blur(function() {
$("body").hide();
});
</script>

Firefox seems to ignore event.preventDefault()

I'm working on a page where I have a draggable item (a map inside a container). When you click and drag with the mouse, the map moves and everything is fine. I then wanted to add the same functionality for touch devices (such as a smartphone or a tablet). I searched the net and found a working script that "changes" touch input to mouseinput and thus making it possible to drag the map without dragging the entire page (which is standard behaviour). This is done using the line
event.preventDefault()
It is even possible to have click events as well by timing how long apart the touches are. I am no coding genius and all this programming was done by others. You can see the discussion at Javascript Drag and drop for touch devices (I have used the original code in the top answer as well as the timing code in the answer just below the top answer).
So far, so good. It is now possible to drag the map around and click any links on it or the page just as you would, if you were using a mouse. This works on all touch browsers I have tried (I haven't tried a lot, but the ones I've tried work). The only problem is, that you cannot drag the page itself around, since the default behaviour of the touch has been disabled. This is a problem when the content of the page (for instance the size of the map container) is larger than the browser window.
Luckily an answer was provided for this as well (it is the bottom-most answer on the page I linked to above): replacing
event.preventDefault()
with
if (touches.length > 1) event.preventDefault();
the default scrolling/resizing etc. of a touch works if you use one finger, but if you use more than one finger, the default behaviour is prevented. In other words: If you use two fingers, you can drag the map around without dragging the page (just as before), but if you use one finger, you can drag the page around! I really like this solution as it seems quite elegant to me.
Well, I added the line and tested on the default browser on my HTC Incredible phone (way to small screen but it is what I have). The default browser is just called "Internet". Everything works perfectly!
So, I test on Firefox and Opera, and unfortunately, they are not working perfectly. It seems that once the
event.preventDefault()
is inside the "if" statement, it is completely ignored, so when I drag the map, it IS dragged (as the touch is still converted to a drag of the mouse), but the page itself is also dragged, regardless of the number of fingers I use. In short: The page behaves as if no
event.preventDefault()
is triggered.
I have looked around for several hours and have come to suspect that the event variable needs to be initialized or imported for Firefox and Opera to be able to use it, as described here: jQuery event.preventDefault() not working in Firefox (JSFiddle included)
My question (at long last): Could this be right, and how do I go about "importing" the event into the "if" statement?
The code is here (the init() function is triggered by body onload)
<script type="text/javascript">
var clickms = 400;
var lastTouchDown = -1;
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
var d = new Date();
switch(event.type)
{
case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
case "touchmove": type="mousemove"; lastTouchDown = -1; break;
case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
if (touches.length > 1)
{
event.preventDefault();
}
}
function init()
{
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
</script>
Edit: I should add that I have tried inserting an alert statement into the if statement, just to see whether Firefox or Opera actually register that a two-finger gesture is performed. The alert is triggered without problems, so perhaps the problem is that once Firefox or Opera has started a two-finger gesture, the standard behaviour of the gesture (draggring or resizing the page) cannot be stopped, at least not in this way.
I seem to have solved the problem (at least on the browsers at my disposal for testing)
What I did was changing
if (touches.length > 1) {
event.preventDefault();
}
to
if (event.touches.length > 1) {
event.preventDefault();
}
It's now possible to drag the draggable element around using two fingers without having the rest of the page move. It's still possible to drag the map with one finger on Firefox and Opera, but this is a minor thing, as soon as you adopt a "use only two fingers when you want to drag" attitude.
The only small issue is that both Firefox and Opera seem to jump back and forth between which fingertip they choose to focus on, making the draggable element jitter somewhat, especially when the fingers are a bit apart. This behaviour is not displayed in the "Internet" browser.

Looking for ibooks html input alternative

In IOS5 on the iPad, iPad2 etc. iBooks accepted <input type="color"> as a way to prompt the keyboard to display when you clicked on an input field, to say, type in the answer to a question. I've just recently updated to IOS6, and this workaround no longer seems to be working. I tried using the JavaScript I found here - http://www.linkedin.com/groups/How-Show-iPads-Keyboard-when-3877009.S.84287009
<script type="text/javascript">
function iPadTouchHandler(event) {
var type = "",
button = 0; /*left*/
if (event.touches.length > 1)
return;
switch (event.type) {
case "touchstart":
// OLD: On iPad2 clicking on a text input field did not show the keyboard
// if ($(event.changedTouches[0].target).is("select")) {
// NEW: Now on iPad2 the touchstart-Event on input fields is ignored and everything works fine
// change my by Roland Caspers, Scheer Management
if ($(event.changedTouches[0].target).is("select") || $(event.changedTouches[0].target).is("input")) {
return;
}
iPadTouchStart(event); /*We need to trigger two events here to support one touch drag and drop*/
event.preventDefault();
return false;
break;
</script>
However this code seems to be outdated and relevant to IOS5. I know of a workaround, which is to put the page with the input into an iFrame, in that case you can just use <input type="text">, however I'd prefer to stay away from iFrames as they tend to move the content around depending on where the input box is. Any thoughts as to other possible solutions or workarounds? Tyvm :)
I am also Facing the same issue on iOS6 for , the same is working perfectly on the <iframe> tag. But it omits the images & style and etc.
Review the code "http://www.linkedin.com/groups/How-Show-iPads-Keyboard-when-3877009.S.84287009", I feel some thing has to modify on below condition:
($(event.changedTouches[0].target).is("select") || $(event.changedTouches[0].target).is("input"))
I'd be great if anyone provide the earlier response.
Thanks
I struggled with this same problem in iBooks on iOS 7. The tricky part was, that iBooks probably makes all text input fields disabled by default. We are using prototype.js, so here is my solution written for prototype:
$('my-input-field-id').observe('touchstart', function(event) {
var element = event.element();
if (element.disabled)
element.disabled = false;
element.focus();
event.stop();
});
So just listen for the 'touchstart' event on the input field and enable and focus the field when touched. It works for ordinary text fields (<input type="text">). Simple :-).

Why doesn't dragging images using JavaScript work in Firefox?

I'm using the code below for dragging an image (#StndSoln1). It works perfectly in Chrome and all, but not in Firefox. Here startDrag() is the function which i attached to the mousedown event listener. Could anybody please help me.
function initialFunction(){
document.getElementById("StndSoln1").addEventListener('mousedown',startDrag,false);
document.getElementById("StndSoln1").addEventListener('mousemove',drag,false);
document.getElementById("StndSoln1").addEventListener('mouseup',stopDrag,false);
}
function startDrag()
{
if (!moveFlag){
currentTraget=document.getElementById("StndSoln1");
offsetX=currentTraget.offsetLeft;
offsetY=currentTraget.offsetTop;
ImgPlaced=false;
moveFlag=true;
x=window.event.clientX;
y=window.event.clientY;
event.preventDefault();
}
}
// Fn for drag the current target object...
function drag(){
if (moveFlag && !ImgPlaced){
currentTraget.style.left=(offsetX+window.event.clientX-x)+"px";
currentTraget.style.top=(offsetY+window.event.clientY-y)+"px";
}
}
I actually had a similar problem, so I can try to help even without the code you're using.
See, the Firefox developers had this bright idea of making it so that, when you drag an image, you can "move" it around and possibly drop it in an Explorer window to quickly and easily download it, or to the tab bar to open the image in a new tab. The obvious downside of this is that it results in a default behaviour that other browsers don't have.
The simple solution is to make sure that all your events are properly cancelling the default action (event.preventDefault, return false, that kind of thing). Should that fail too, then you should use a <div> element with a background-image instead of an <img> element.

Multiple key presses in JavaScript only working in IE

I have the following code:
function handle_paste_keydown(key)
{
if(key.keyCode == 86 && key.ctrlKey) // Ctrl + V
{
alert("Test...");
}
}
This works in IE, but none of the other browsers. My reason for doing this is that I have finished creating a rich-text editor, but I need to handle the onpaste event carefully because formatted text is able to make it in to my editor, which could pose a minor risk to security, but also butchers my layout if malicious <span>s and <div>s make it in.
My current method is to give focus to an off-screen textarea, which means all code will be pasted in to that (which removes formatting); then I immediately grab the textarea.value and insert it at the current caret position in my contentEditable <div>.
So anyway, how do I get the Ctrl+V to work in all browsers and why doesn't it work in its current state?
Thank you.
If it works in IE but nowhere else you did something wrong.
Use the keypress event rather than keydown.
http://jsfiddle.net/Lxvgr/1/
document.getElementById('foo').onkeypress = function(e) {
if(e.charCode == 118 && e.ctrlKey) alert('pasted');
};
#Eric Sites: "use jQuery" isn't the answer to every javascript question. including an entire external framework to solve a simple 4byte issue like this is ridiculous.

Categories