Friday, April 3, 2015

Javascript drag/drop event listener

It is a cool feature that file processing is triggered when you drag a file and drop it onto a web page.

For example, the midi player demo page index.html from [1] has this in header javascript:

    if (FileReader){
        function cancelEvent(e){
            e.stopPropagation();
            e.preventDefault();
        }
        document.addEventListener('dragenter', cancelEvent, false);
        document.addEventListener('dragover', cancelEvent, false);
        document.addEventListener('drop', function(e){
            cancelEvent(e);
            for(var i=0;i            var
                file = e.dataTransfer.files[i]
            ;
            if(file.type != 'audio/midi' && file.type != 'audio/mid'){
                continue;
            }
            var
                reader = new FileReader()
            ;
            reader.onload = function(e){
                midiFile = MidiFile(e.target.result);
                synth = Synth(44100);
                replayer = Replayer(midiFile, synth);
                audio = AudioPlayer(replayer);
            };
            reader.readAsBinaryString(file);
            }
        }, false);
    }


What this does is, when you drag and drop a midi file on the page, it'll be read and played.

HTML5 has native support for drag/drop event. See [2].

[1] https://github.com/gasman/jasmid
[2] Native HTML5 Drag and Drop

No comments:

Blog Archive

Followers