Hello stack overflow community!
I am writing a script to make simple drag and drop able document maker. i wrote all my current code by myself, but i had no clue how to enable dragging of desktop files to the document. here is the code i have written so far(sorry for the messedup indenting, the codeblock feature messed it up):
<html>
<head>
<style>
#main { position:absolute; top:10px; left:50%; margin-left:-450px; width:900px; height:900px; border:dashed 1px lightgrey; }
#trash { margin-top:10px; width:200px; height:200px; border:dotted 4px black; position:absolute; top:0px; left:5px; }
#new { width:200px; height:200px; border:dotted 5px black; }
.new { float:right; }
.drag { float:left; resize:both; overflow:hidden; height:110px; width:110px; }
.square { background-color:none; width:10px; height:10px; float:left; }
.drag * { resize:none; width:100px; height:100px }
.block { background-color:red; }
</style>
<script src="jq/jquery-1.9.1.js"></script>
<script src="jq/jquery-ui.js"></script>
<script>
var blockcolors = ["red","blue","green","yellow","white","black","lightgrey","lightblue"];
var color = 1;
var id = 2;
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
ev.target.appendChild(document.getElementById(ev.dataTransfer.getData("Text")));
}
function droptrash(ev)
{
ev.preventDefault();
$("#"+ev.dataTransfer.getData("Text")).remove();
}
function change(div)
{
var divw=parseInt(div.style.width);
var divh=parseInt(div.style.height);
var imgw=divw-10;
var imgh=divh-10;
div.children[0].style.width=imgw;
div.children[0].style.height=imgh;
div.style.border="dotted 3px grey";
}
function makeGrid()
{
var main = $("#main");
for (var i = 0; i < 8100; i++)
{
var square = document.createElement('div');
square.setAttribute('class', 'square');
square.ondragover = function(event) { event.preventDefault(); };
square.ondrop = function(event) { drop(event); };
main.prepend(square);
}
}
function additem() {
var newbox = document.getElementById("new");
newbox.innerHTML = '<div id="div'+id+'" class="drag" onmouseout="this.style.border=0" draggable="true" ' +
'ondragstart="drag(event)" onmousemove="change(this)"></div>';
div = document.getElementById("div"+id);
div.innerHTML = $("#newtype").val();
id+=1;
}
function blockcolor(block) {
block.style.backgroundColor = blockcolors[color];
if (color == blockcolors.length-1)
color = 0;
color++;
}
</script>
</head>
<body onload="makeGrid()" class="new">
<div id="new" class="new"></div>
<div style="clear:both"></div>
<select id="newtype" class="new">
<option value="<img draggable='false' src='glider.jpg'/>">Image</option>
<option value="<textarea></textarea>">Text box</option>
<option value="<div onclick='blockcolor(this)' class='block'></div>">Block</option>
</select>
<button onclick="additem()" class="new">add an item</button>
<div style="clear:both"></div>
<center>
<div style="clear:both"></div>
<div ID="main" overflow="auto">
</div>
</center>
<div style="clear:both"></div>
<div id="trash" ondragover="event.preventDefault()" ondrop="droptrash(event)" overflow="auto"><big>Trash</big></div>
</body>
</html>
this works, but it has no functionality for dragging in files. i wanted to add this code i found online which works by itself:
<html>
<head>
<style>
#drop { min-height: 150px; width: 250px; border: 1px solid blue; margin: 10px; padding: 10px; }
</style>
<script>
if(window.FileReader) {
var drop;
addEventHandler(window, 'load', function() {
drop = document.getElementById('drop');
var list = document.getElementById('list');
function cancel(e) {
if (e.preventDefault) { e.preventDefault(); }
return false;
}
// Tells the browser that we *can* drop on this target
addEventHandler(drop, 'dragover', cancel);
addEventHandler(drop, 'dragenter', cancel);
addEventHandler(drop, 'drop', function (e) {
e = e || window.event; // get window.event if e argument missing (in IE)
if (e.preventDefault) { e.preventDefault(); } // stops the browser from redirecting off to the image.
var dt = e.dataTransfer;
var files = dt.files;
for (var i=0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
//attach event handlers here...
reader.readAsDataURL(file);
addEventHandler(reader, 'loadend', function(e, file) {
var bin = this.result;
var img = document.createElement("img");
img.file = file;
img.src = bin;
drop.innerHTML = "";
drop.appendChild(img);
}.bindToEventHandler(file));
}
return false;
});
Function.prototype.bindToEventHandler = function bindToEventHandler() {
var handler = this;
var boundParameters = Array.prototype.slice.call(arguments);
//create closure
return function(e) {
e = e || window.event; // get window.event if e argument missing (in IE)
boundParameters.unshift(e);
handler.apply(this, boundParameters);
}
};
});
} else {
document.getElementById('status').innerHTML = 'Your browser does not support the HTML5 FileReader.';
}
function addEventHandler(obj, evt, handler) {
if(obj.addEventListener) {
// W3C method
obj.addEventListener(evt, handler, false);
} else if(obj.attachEvent) {
// IE method.
obj.attachEvent('on'+evt, handler);
} else {
// Old school method.
obj['on'+evt] = handler;
}
}
</script>
</head>
<body>
<DIV id="drop"></DIV>
<DIV id="list"></DIV>
</body>
</html>
my problem is combining them. the second script messes up all drag and drop functionality for the whole thing. i would much appreciate any help.
there is some minor change in the file drop script. Just rename the variable "drop" to "dropElement"( or any other name then "drop"), as it was conflicting with the function name "drop" in first script. so here is your second script.
<script>
if(window.FileReader) {
var dropElement;
addEventHandler(window, 'load', function() {
dropElement = document.getElementById('drop');
var list = document.getElementById('list');
function cancel(e) {
if (e.preventDefault) { e.preventDefault(); }
return false;
}
// Tells the browser that we *can* drop on this target
addEventHandler(dropElement, 'dragover', cancel);
addEventHandler(dropElement, 'dragenter', cancel);
addEventHandler(dropElement, 'drop', function (e) {
e = e || window.event; // get window.event if e argument missing (in IE)
if (e.preventDefault) { e.preventDefault(); } // stops the browser from redirecting off to the image.
var dt = e.dataTransfer;
var files = dt.files;
for (var i=0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
//attach event handlers here...
reader.readAsDataURL(file);
addEventHandler(reader, 'loadend', function(e, file) {
var bin = this.result;
var img = document.createElement("img");
img.file = file;
img.src = bin;
dropElement.innerHTML = "";
dropElement.appendChild(img);
}.bindToEventHandler(file));
}
return false;
});
Function.prototype.bindToEventHandler = function bindToEventHandler() {
var handler = this;
var boundParameters = Array.prototype.slice.call(arguments);
//create closure
return function(e) {
e = e || window.event; // get window.event if e argument missing (in IE)
boundParameters.unshift(e);
handler.apply(this, boundParameters);
}
};
});
} else {
document.getElementById('status').innerHTML = 'Your browser does not support the HTML5 FileReader.';
}
function addEventHandler(obj, evt, handler) {
if(obj.addEventListener) {
// W3C method
obj.addEventListener(evt, handler, false);
} else if(obj.attachEvent) {
// IE method.
obj.attachEvent('on'+evt, handler);
} else {
// Old school method.
obj['on'+evt] = handler;
}
}
</script>
Related
i used by javascrip upload multiple file but that files insert different columns.
Why is it that when uploading multiple files with drag drop, they are written in multiple rows instead of one line in the database?
Pictured is a view of the data after inserting it into the database
My php Code is : uploads.php
if(isset($_FILES)){
$upload_dir = "upload/";
$fileName = strtolower(pathinfo($_FILES["files"]["name"], PATHINFO_EXTENSION));
$new_file_name = rand() . '.' . $fileName;
$uploaded_file = $upload_dir.$new_file_name;
if(move_uploaded_file($_FILES['files']['tmp_name'],$uploaded_file)){
}
$content = $_POST['textpost'];
$data = array(
':file' => $new_file_name,
':uploaded_on' => date("Y-m-d H:i:s"),
':content' => $content,
);
$query = "
INSERT INTO images
(name, uploaded_on ,content)
VALUES (:name,:uploaded_on,:content)
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
The Below is the code I originally used. I used these codes as examples from other people’s codes. Then I made some changes myself and added a little functionality. For example, I added a few codes, such as deleting images, separating images and videos, and brought them to the function I needed. But the problem with me now is that When uploading multiple images at the same time as text, All data sent are insert into separate rows, Finally when I select the data from the database the content and images are not select out correctly.My goal is to insert images and text into a single line.
My javascript Code is :index.html
var dropRegion = document.getElementById("drop-region"),
// where images are previewed
imagePreviewRegion = document.getElementById("image-preview");
var file_drag_area = document.getElementById("file_drag_area");
var images_button = document.getElementById("images_btn");
var submit = document.getElementById("submit");
// open file selector when clicked on the drop region
var fakeInput = document.createElement("input");
fakeInput.type = "file";
fakeInput.accept = "video/*,image/*";
fakeInput.multiple = true;
images_button.addEventListener('click', function() {
fakeInput.click();
});
fakeInput.addEventListener("change", function() {
var files = fakeInput.files;
handleFiles(files);
});
function preventDefault(e) {
e.preventDefault();
e.stopPropagation();
}
file_drag_area.addEventListener('dragenter', preventDefault, false)
file_drag_area.addEventListener('dragleave', preventDefault, false)
file_drag_area.addEventListener('dragover', preventDefault, false)
file_drag_area.addEventListener('drop', preventDefault, false)
dropRegion.addEventListener('dragenter', preventDefault, false)
dropRegion.addEventListener('dragleave', preventDefault, false)
dropRegion.addEventListener('dragover', preventDefault, false)
dropRegion.addEventListener('drop', preventDefault, false)
function handleDrop(e) {
var dt = e.dataTransfer,
files = dt.files;
handleFiles(files)
}
dropRegion.addEventListener('drop', handleDrop, false);
file_drag_area.addEventListener('drop', handleDrop, false);
// when drag file the border change to other dotted
file_drag_area.addEventListener("dragenter", function(event) {
if ( event.target.className == "file_drag_area" ) {
event.target.style.border = "3px dotted #79d4ff";
}
});
// when drag file the border display none
file_drag_area.addEventListener("dragleave", function(event) {
if ( event.target.className == "trigger_popup_fricc_wrapper" ) {
event.target.style.border = "";
}
});
file_drag_area.addEventListener("drop", function(event) {
if ( event.target.className == "trigger_popup_fricc_wrapper" ) {
event.target.style.border = "";
}
});
function handleFiles(files) {
for (var i = 0, len = files.length; i < len; i++) {
if (validateImage(files[i]))
previewAnduploadImage(files[i]);
}
}
function validateImage(image) {
// check the type
var validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg','video/mp4', 'video/mkv', 'video/webm'];
var vedioType = validTypes.includes('video/mp4', 'video/mkv', 'video/webm');
if (validTypes.indexOf( image.type ) === -1 && vedioType.indexOf( video.type ) === -1) {
alert("Invalid File Type");
return false;
}
// check the size
var maxSizeInBytes = 10e6; // 10MB
if (image.size > maxSizeInBytes) {
alert("File too large");
return false;
}
return true;
}
function previewAnduploadImage(image) {
var fileType = image.type;
var match = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg','video/mp4', 'video/mkv', 'video/webm'];
if ((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3])) {
var imgView = document.createElement("div");
imgView.className = "image-view";
imagePreviewRegion.appendChild(imgView);
var icon = document.createElement("div")
icon.className = "image-icon";
//icon.setAttribute("onclick", "remove_image()");
imgView.appendChild(icon);
var remove = document.createElement("img")
remove.className = "img_class";
remove.setAttribute("height", "20px");
remove.setAttribute("width", "20px");
remove.setAttribute("src", "../../assets/images/cancel.png");
icon.appendChild(remove);
// previewing image
var img = document.createElement("img");
img.className = "remove_input";
img.setAttribute("height", "200px");
img.setAttribute("width", "300px");
imgView.appendChild(img);
var reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
}
reader.readAsDataURL(image);
}else if ((fileType == match[4]) || (fileType == match[5]) || (fileType == match[6])) {
// show video
var video = document.createElement("video")
video.classList.add("obj");
video.file = image;
video.className = "preview_vedio";
video.controls = true;
video.autoplay = true;
video.setAttribute("width", "500");
video.setAttribute("height", "300");
//icon.setAttribute("onclick", "remove_image()");
imagePreviewRegion.appendChild(video);
var reader = new FileReader();
reader.onload = function(e) {
video.src = e.target.result;
}
reader.readAsDataURL(image);
}
var formData = new FormData();
formData.append('image', image);
formData.append('action', 'files');
//formData.append('vedio', vediofiles);
$("#drop-region").css("display", "block");
$("#drop-region").slideDown("slow")
addEventListener('submit', (event) => {
var uploadLocation = 'uploads.php';
var ajax = new XMLHttpRequest();
ajax.open("POST", uploadLocation, true);
ajax.onreadystatechange = function(e) {
if (ajax.readyState === 4) {
if (ajax.status === 200) {
//var myObj = JSON.parse(this.responseText);
} else {
// error!
}
}
}
ajax.upload.onprogress = function(e) {
// change progress
// (reduce the width of overlay)
var perc = (e.loaded / e.total * 100) || 100,
width = 100 - perc;
overlay.style.width = width;
}
ajax.send(formData);
});
}
textarea
{
width: 100%;
margin: 0px;
padding: .2em;
border: none;
outline-width: 0;
text-align: start;
unicode-bidi: plaintext;
font-weight: 400;
cursor: text;
background-color: #ffffff;
overflow:hidden;
resize: none;
font-size: 18px;
}
input#submit {
width: 100%;
color: white;
background: #79d4ff;
font-size: 18px;
border: none;
border-radius: 8px;
outline-width: 0;
line-height: 2;
}
input#submit:hover
{
background: #3da0f5;
}
input#submit:focus{width: 98%;}
#drop-region {
background-color: #fff;
border-radius:20px;
box-shadow:0 0 35px rgba(0,0,0,0.05);
padding:60px 40px;
text-align: center;
cursor:pointer;
transition:.3s;
display:none;
}
#drop-region:hover {
box-shadow:0 0 45px rgba(0,0,0,0.1);
}
#image-preview {
margin-top:20px;
}
#image-preview .image-view {
display: inline-block;
position:relative;
margin-right: 13px;
margin-bottom: 13px;
}
#image-preview .image-view img {
max-width: 300px;
max-height: 300px;
transform: scale(.9);
transition: .4s;
}
#image-preview .overlay {
position: absolute;
width: 100%;
height: 100%;
top: 0;
right: 0;
z-index: 2;
background: rgba(255,255,255,0.5);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form id="fupForm"enctype="multipart/form-data" accept-charset="utf-8">
<textarea style="direction:ltr;" name="post_content" class="file_drag_area" id="file_drag_area" maxlength="1000" placeholder="Greate Post..." ></textarea>
<div id="drop-region">
<div id="image-preview">
</div>
</div>
<button type="button" class="emoji_button" id="images_btn"><img src="../../assets/images/image.png" width="25px" height="25px" ></button>
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Send Post" />
</form>
For your case, when you drag and drop the files (file upload), you will trigger the following function:
function handleFiles(files) {
for (var i = 0, len = files.length; i < len; i++) {
if (validateImage(files[i]))
previewAnduploadImage(files[i]);
}
}
It is obvious that this "handleFiles" function will process the files one by one. Hence the php is called ONCE for every file uploaded --- and that explains why the files are saved into separate records.
The above should explain what you encounter. So if you want to save the data into a single record, you need to amend the above codes
I am trying to implement drag and drop div, like this. Unfortunately, it doesn't work for me, when I try to drag to this div, a new tab with the selected file opens.
Here is my code
<div id="dropzone" style="height:200px; border: 4px double black;" ></div>
<script>
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(e) {
var length = e.dataTransfer.items.length;
for (var i = 0; i < length; i++) {
var entry = e.dataTransfer.items[i].webkitGetAsEntry();
if (entry.isFile) {
// do whatever you want
} else if (entry.isDirectory) {
// do whatever you want
}
}
};
</script>
How can I make it work?
var dropbox;
dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
#dropbox
{
height: 100px;
border: 4px double black;
background-color: lightgray;
font: 5em bold monospace;
text-align: center;
}
<div id="dropbox">
Drag files here!
</div>
The Google link is outdated, but this allows the file system to work in a very similar fashion. An example of this is above.
I want to create a web page in which a specific image is capable to drag.
so this was my code.
<! doctype html>
<html>
<head>
<title>
</title>
<script src="13.8.js"></script>
</head>
<body>
<img src="file:\\C:\Users\X555\Pictures\poster\yellowflowers.png" id="image" alt="white lion">
<script>
var mustDrag;
var image
function set() {
image = document.getElementById("image");
image.addEventListener("mousedown", function () { mustDrag = true }, false);
window.addEventListener("mouseup", function () { mustDrag = false; }, false);
window.addEventListener("mousemove", drag, false);
}
function drag(e) {
if (mustDrag) {
e.target.style.position = 'absolute';
e.target.style.left = Number(e.x);
e.target.style.top = Number(e.y);
}
}
window.addEventListener("load", set, false);
</script>
</body>
</html>
but it doesn't function correctly .sometimes it drag whit it shouldn't. and usually throw the image in lower-left side of the window while it mustn't. I don't realize at all that whats wrong with this code?
Refer this Example, hope you will get your answer
function startDrag(e) {
// determine event object
if (!e) {
var e = window.event;
}
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
if (targ.className != 'dragme') {return};
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// assign default values for top and left properties
if(!targ.style.left) { targ.style.left='0px'};
if (!targ.style.top) { targ.style.top='0px'};
// calculate integer values for top and left
// properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
// move div element
document.onmousemove=dragDiv;
return false;
}
function dragDiv(e) {
if (!drag) {return};
if (!e) { var e= window.event};
// var targ=e.target?e.target:e.srcElement;
// move div element
targ.style.left=coordX+e.clientX-offsetX+'px';
targ.style.top=coordY+e.clientY-offsetY+'px';
return false;
}
function stopDrag() {
drag=false;
}
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
.dragme{
position:relative;
width: 270px;
height: 203px;
cursor: move;
}
#draggable {
background-color: #ccc;
border: 1px solid #000;
}
<img src="https://lh4.googleusercontent.com/-8tqTFxi2ebU/Ufo4j_thf7I/AAAAAAAADFM/_ZBQctm9e8E/w270-h203-no/flower.jpg" alt="drag-and-drop image script"
title="drag-and-drop image script" class="dragme">
<div id="draggable" class="dragme">Test </div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>Basic Drag and Drop</title>
<style>
#drop {
min-height: 200px;
width: 200px;
border: 3px dashed #ccc;
margin: 10px;
padding: 10px;
clear: left;
}
p {
margin: 10px 0;
}
#triangle {
background: url(images/triangle.jpg) no-repeat;
}
#square {
background: url(images/square.gif) no-repeat;
}
#circle {
background: url(images/circle.jpg) no-repeat;
}
#red {
background: url(images/red.jpg) no-repeat;
}
#yellow {
background: url(images/yellow.jpg) no-repeat;
}
#green {
background: url(images/green.jpg) no-repeat;
}
.drag {
height: 48px;
width: 48px;
float: left;
-khtml-user-drag: element;
margin: 10px;
}
</style>
<script>
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (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"
// private scope to avoid conflicts with demos
addEvent(window, 'click', function (event) {
if (event.target.hash == '#view-source') {
// event.preventDefault();
if (!document.getElementById('view-source')) {
// pre.innerHTML = ('<!DOCTYPE html>\n<html>\n' + document.documentElement.innerHTML + '\n</html>').replace(/[<>]/g, function (m) { return {'<':'<','>':'>'}[m]});
var xhr = new XMLHttpRequest();
// original source - rather than rendered source
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
pre.innerHTML = this.responseText.replace(/[<>]/g, function (m) { return {'<':'<','>':'>'}[m]});
prettyPrint();
}
};
document.body.appendChild(pre);
// really need to be sync? - I like to think so
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);
}
});
})();
</script>
<style id="jsbin-css">
</style>
</head>
<body>
<div class="drag" id="triangle" draggable="true"></div>
<div class="drag" id="square" draggable="true"></div>
<div class="drag" id="circle" draggable="true"></div>
<div class="drag" id="red" draggable="true"></div>
<div class="drag" id="yellow" draggable="true"></div>
<div class="drag" id="green" draggable="true"></div>
<div id="drop"></div>
<script>
function cancel(e) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
var dragItems = document.querySelectorAll('[draggable=true]');
for (var i = 0; i < dragItems.length; i++) {
addEvent(dragItems[i], 'dragstart', function (event) {
// store the ID of the element, and collect it on the drop later on
event.dataTransfer.setData('Text', this.id);
});
}
var drop = document.querySelector('#drop');
// Tells the browser that we *can* drop on this target
addEvent(drop, 'dragover', cancel);
addEvent(drop, 'dragenter', cancel);
addEvent(drop, 'drop', function (e) {
if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.
this.innerHTML += '<p>' + e.dataTransfer.getData('Text') + '</p>';
return false;
});
</script>
<script>
document.getElementById('drop').ondblclick = function(){
this.innerHTML="";//remove your text here
};
</script>
</body>
</html>
in the line of below is to removed the whole box called drop name. but i want to removed the selected text that i added inside only. others text, i still want it to remain stay inside the drop box.Is it need to be code one by one for the data drop inside or how is going to work on? Please help me... thanks so much.
document.getElementById('drop').ondblclick = function(){
this.innerHTML="";//remove your text here
};
If you are looking to remove / manipulate selected text, then look at the Selection and Range object API's MDN, but bear in mind these may still be non-standard API's
There is a jFiddle example here which will report the selected range and also remove the selected text:
document.getElementById("drop").ondblclick = function() {
var sel = window.getSelection(),
range = sel.getRangeAt(0),
text = this.innerHTML,
toRemove,
editedText;
//console.log("sel ", sel, " range ", range);
toRemove = text.substring(range.startOffset,range.endOffset);
editedText = text.slice(0, range.startOffset) + text.slice(range.endOffset);
console.log("toRemove ", toRemove);
console.log("editedText ", editedText);
}
Bear in mind that double-clicking on an area of text may vary in behaviour - if I double click text in Chrome, it only selects a single word.
I'm implementing audio player in html5, which has drag-drop option for load and play mp3 files, but I have problem with plaing the file.
When the file is dropped on the area, I can see in the console properties of object, but there is no information about absolute path, because of security in web browser.
Is there an option, how to play mp3 this way ?
index.html and body content:
<div style="border: 1px solid black; width: 200px; height: 50px; padding: 10px;"" id="cudl">add file here</div>
<div id="play" style="border: 1px solid black; width: 200px; height: 50px; padding: 10px;">PLAY</div>
<div id="pause" style="border: 1px solid black; width: 200px; height: 50px; padding: 10px;">PAUSE</div>
<div id="progress" style="width: 1000px; height: 50px; background: black; "><div id="time" style="width: 0%; height: 50px; background: green;"></div></div>
javascript:
window.onload = function () {
var cudl = document.getElementById("cudl");
cudl.addEventListener("dragover", function (ev) {
ev.preventDefault();
}, false);
cudl.addEventListener("drop", function (ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("audio/mpeg");
var allAudio = document.getElementsByTagName("audio");
if (allAudio.length > 0) {
for (var i = 0; i < allAudio.length; i++) document.body.removeChild(allAudio[i]);
}
var audio = document.createElement("audio");
audio.setAttribute("src", ev.dataTransfer.files[0].name);
document.body.appendChild(audio);
console.log("append file");
console.log(ev.dataTransfer.files[0]);
audio.addEventListener("durationchange", function () {
console.log("dc " + this.duration);
});
audio.addEventListener("timeupdate", function () {
//console.log("ct " + this.currentTime);
var prog = document.getElementById("time");
prog.style.width = Math.floor(this.currentTime / this.duration * 100) + "%";
});
var play = document.getElementById("play");
play.addEventListener("click", function () {
document.getElementsByTagName("audio")[0].play();
});
var pause = document.getElementById("pause");
pause.addEventListener("click", function () {
document.getElementsByTagName("audio")[0].pause();
});
}, false);
};
Instead of using the absolute path to use as an src-attribute on an audio element, I suggest you read the contents of the file(s) and use the webAudio API for decoding the audio data.
Here is a working example for playing the dropped file immediately. But you can just save the buffer for later playback.
var context = new AudioContext()
window.addEventListener('load', function() {
var dropzone = document.querySelector('#dropzone');
dropzone.addEventListener('drop', handleDrop, false)
dropzone.addEventListener('dragover', handleDragOver, false)
})
var handleDragOver = function(e) {
e.preventDefault()
e.stopPropagation()
}
var handleDrop = function(e) {
e.preventDefault()
e.stopPropagation()
var files = e.dataTransfer.files
for (var i = 0; i < files.length; i++) {
var file = files[i]
var reader = new FileReader()
reader.addEventListener('load', function(e) {
var data = e.target.result
context.decodeAudioData(data, function(buffer) {
playSound(buffer)
})
})
reader.readAsArrayBuffer(file)
}
}
var playSound = function(buffer) {
var source = context.createBufferSource()
source.buffer = buffer
source.connect(context.destination)
source.start(0)
}
You can disable the web security of the browser. In the terminal, cd to the application and type "--disable-web-security" without the quotes.
I think you are forgetting to load the audio before playing it. I always forget this when retrieving audio files to play.
document.getElementsByTagName("audio")[0].load();
document.getElementsByTagName("audio")[0].play();