Skip to content Skip to sidebar Skip to footer

Html5 Drag And Drop File Field

I want to enhance a critical form with drag and drop functionality. I know that modern browser are capable of this via HTML5 file API. However I do NOT want an instant upload or to

Solution 1:

Here is what ended up working, I set the vanilla upload field to opacity : 0 and positioned it under the mouse when the mouse is over the visible dropZone div, via the 'dragover' event.

'dragover' overcomes the problem with the browser window being out of focus, and provides .pageX and .pageY which I then bound to the invisible file field's .top and .left.

However the resulting position of the file field is different on osx vs windows OSs, so a catch had to be put in to position the file field appropriately based on OS. I am pasting my working code below, and I have written a lib that detects browsers, OS and devices. So you will need to find your own way to detect osx vs windows.

dropText  = $ '#dropText'
jdropZone = $ '#resume'
fileField = $ '#draggy'

unless $.browser.msie

    `var addEvent=(function(){if(document.addEventListener){returnfunction(el,type,fn){if(el&&el.nodeName||el===window){el.addEventListener(type,fn,false)}elseif(el&&el.length){for(var i=0;i<el.length;i++){addEvent(el[i],type,fn)}}}}else{returnfunction(el,type,fn){if(el&&el.nodeName||el===window){el.attachEvent('on'+type,function(){return fn.call(el,window.event)})}elseif(el&&el.length){for(var i=0;i<el.length;i++){addEvent(el[i],type,fn)}}}}})();(function(){var pre=document.createElement('pre');pre.id="view-source";addEvent(window,'click',function(event){if(event.target.hash=='#view-source'){if(!document.getElementById('view-source')){var xhr=new XMLHttpRequest();xhr.onreadystatechange=function(){if(this.readyState==4&&this.status==200){pre.innerHTML=this.responseText.replace(/[<>]/g,function(m){return{'<':'&lt;','>':'&gt;'}[m]});prettyPrint()}};document.body.appendChild(pre);xhr.open("GET",window.location,true);xhr.send()}document.body.className='view-source';var sourceTimer=setInterval(function(){if(window.location.hash!='#view-source'){clearInterval(sourceTimer);document.body.className=''}},200)}})})();`

    x = 0
    y = -50

    x = -200 unless device.mac
    x = -130if device.mac      

    #alert x

    dragover = (e) ->
        #e.preventDefault()
        fileField.css top : e.pageY+y, left : e.pageX+x

    dropZone = document.getElementById 'resume'

    addEvent dropZone, 'dragover', dragover

    fileField.on 'change', ->
        fieldVal = fileField.attr 'value'
        fieldVal = fieldVal.split 'fakepath'
        fieldVal = fieldVal[fieldVal.length-1]
        fieldVal = fieldVal.substr 1, fieldVal.length if $.browser.webkit
        dropText.text 'Your Resume: '+fieldVal

else

    fileField.css
        position : 'static'
        opacity  : 1
    dropText.text 'Upload Your Resume Here: '

Post a Comment for "Html5 Drag And Drop File Field"