I'm newbie in html 5, and i'm trying some code for drop image from desktop, but my code doesn't work. This is my code:
script>
function OnDropTextarea(event) {
if (event.dataTransfer) {
if (event.dataTransfer.files) {
var leftbox = document.getElementById("leftbox");
for (var i = 0; i < event.dataTransfer.files.length; i++) {
var file = event.dataTransfer.files[i];
leftbox.innerHTML += file;
}
} else {
alert("Your browser does not support the files property.");
}
} else {
alert("Your browser does not support the dataTransfer property.");
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
return false;
}
</script>
<section id="leftbox" ondrop="return OnDropTextarea (event);"></section>
So, please! help me
I try new code, but i can only drag and drop box in other box, not from desktop.
Another code:
<script>
function doFirst() {
mypic = document.getElementById('pic');
mypic.addEventListener("dragstart", startDrag, false);
leftbox = document.getElementById('leftbox');
leftbox.addEventListener("dragenter", function(e) {
e.preventDefault()
}, false);
leftbox.addEventListener("dragover", function(e) {
e.preventDefault()
}, false);
leftbox.addEventListener("drop", dropped, false);
}
function startDrag(e) {
var code = '<img src="/assets/Koala.jpg">';
e.dataTransfer.setData('Text', code);
}
function dropped(e) {
e.preventDefault();
leftbox.innerHTML = e.dataTransfer.getData('Text');
}
window.addEventListener("load", doFirst, false);
</script>
<section id="leftbox">
</section>
<section id="rightbox">
<img src="/assets/Koala.jpg" id="pic"/>
</section>
You need to override dragover and dragenter and prevent the default action in order for an element to qualify as a valid drop target. MDN
EDIT: The drop should work now, I think (the only difference between your code in mine seems to be the fact that I also do e.dataTransfer.dropEffect = "copy" in my dragover and dragenter handlers). I wish people were more explicit with "doesn't work" - is the drop happening, but you're not getting the file contents?
If that is the case, the issue might be the fact that you are treating a File object as if it was a string. So instead of this,
leftbox.innerHTML += file;
try this:
var reader = new FileReader();
reader.onload = function(e) { leftbox.innerHTML += e.target.result; };
reader.readAsText(file);
ondrop="return OnDropTextarea (event);"
Should be:
ondrop="OnDropTextarea()"
May be this is useful for you,but you have to use the jquery library
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload images with Jquery</title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var obj = $("#dragandrophandler");
obj.on('dragenter', function (e)
{
e.stopPropagation();
e.preventDefault();
//$(this).css('border', '2px solid #0B85A1');
});
obj.on('dragover', function (e)
{
e.stopPropagation();
e.preventDefault();
});
obj.on('drop', function (e)
{ //alert('');
e.preventDefault();
/*$(this).css('border', '2px dotted #0B85A1');*/
var files = e.originalEvent.dataTransfer.files;
var data = new FormData();
var i=0,l=files.length;
for (i = 0; i < l; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: 'load.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(msg) {
});
});
$(document).on('dragenter', function (e)
{
e.stopPropagation();
e.preventDefault();
});
$(document).on('dragover', function (e)
{
e.stopPropagation();
e.preventDefault();
//obj.css('border', '2px dotted #0B85A1');
});
$(document).on('drop', function (e)
{
e.stopPropagation();
e.preventDefault();
});
});
</script>
<style type="text/css">
#dragandrophandler {
border: 2px dashed #ccc;
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div id="dragandrophandler">
Drop files here
</div>
<div id="meta"></div>
</body>
</html>
Related
I've tried all the solutions from other Stackoverflow topics, but I can't my jQuery file to work.
I use a Wampserver to test my code and I test inside of multiple browsers (Firefox, Chrome, Opera). Same problem every time.
HTML
<script src="js/scripts.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
I've put these lines before my closing <\body> tag
scripts.js`
(function($) {
'use strict';
// holds current image shown
var $currNr = 0;
var links, images;
/**
* Function to prevent closures; adds click event handler to links
*/
var addEvents = function(nr) {
// add click event to link
$(links[nr]).on('click', function(e) {
showImage(nr);
e.preventDefault();
});
};
/**
* Function to show an image
*/
var showImage = function(nr) {
// find image
var $img = $(images[nr]);
if (!$img) return;
// find big image
var $photoBig = $('#photoBig');
// change
$photoBig.attr('src', $img.attr('data-src-l'));
$photoBig.attr('alt', $img.attr('alt'));
// remember current image number
$currNr = nr;
};
/**
* Function to show the next image
*/
var showNextImage = function() {
if ($currNr != (links.length - 1)) {
showImage($currNr + 1);
} else {
showImage(0);
}
};
/**
* Function to show the previous image
*/
var showPrevImage = function() {
if ($currNr != 0) {
showImage($currNr - 1);
} else {
showImage(links.length - 1);
}
};
// start scripts
$(window).on('load', function() {
// find images and links
links = $('#thumbsmenu li>a');
images = $('#thumbsmenu li>a img');
// add link events
$(links).each(function(nr) {
$(this).on('click', function(e) {
showImage(nr);
e.preventBubble();
});
});
// controls
$('#lnkFirst').on('click', function(e) {
showImage(0);
e.preventDefault();
});
$('#lnkPrev').on('click', function(e) {
showPrevImage();
e.preventDefault();
});
$('#lnkNext').on('click', function(e) {
showNextImage();
e.preventDefault();
});
$('#lnkLast').on('click', function(e) {
showImage(images.length - 1);
e.preventDefault();
});
// keyboard
$(document).on('keydown', function(e) {
var $code = (e.keyCode ? e.keyCode : e.which);
switch (event.keyCode) {
case 37: showPrevImage(); e.preventDefault(); break;
case 39: showNextImage(); e.preventDefault(); break;
}
});
// play
var $timer;
$('#btnPlay').on('click', function(e) {
if (!$(this).prop('playing')) {
$(this).val('stop');
$(this).prop('playing', true);
$currNr = 0;
$timer = setInterval(showNextImage, 1000);
} else {
$(this).val('start');
$(this).prop('playing', false);
clearInterval($timer);
}
});
});})(jQuery);`
I use a self-invoking function and use it as parameter but I get a:
ReferenceError: jQuery is not defined
Normally this code should work, that was how I was taught back then. Anyone an idea what could be the real issue here?
You are loading scripts.js before jQuery
Change the following code:
<script src="js/scripts.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
To:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/scripts.js"></script>
Your script load ordering is wrong. Load jQuery first, then use it.
As other people suggested your order is wrong. In order for you to use JQuery in other script files it needs to be fully loaded. Change your HTML like so:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/scripts.js"></script>
I am trying to un-jQuery-fy a clever piece of code, but one that is just a bit too clever.
The objective is simple. Drag images from the desktop to the browser.
During this unjQueryfication, I find that, lo and behold, a dollar-sign function is actually implemented in Chrome and Firefox. So even without including jQuery, it sort of works already.
Here is what I came up with so far. What am I missing?
var el = document.getElementById('holder');
function stop_and_prevent(e) {
e.stopPropagation();
e.preventDefault();
}
function load_images(files) {
var images = document.getElementById("images");
files.map(function(file) {
var reader = new FileReader();
reader.onload = function(event) {
if (file.type.match('image.*')) {
var img = document.createElement('img');
img.src = event.target.result;
images.appendChild(img);
reader.readAsDataURL(file);
}}
});
}
function onDrop(e) {
e.stop_and_prevent();
load_images(e.dataTransfer.files);
return false;
}
el.addEventListener('dragenter', stop_and_prevent, false);
el.addEventListener('dragover', stop_and_prevent, false);
el.addEventListener('dragleave', stop_and_prevent, false);
el.addEventListener('drop', onDrop, false);
div#holder {
border: 5px dashed #ccc;
height:400px;
width:400px;
font-family:Verdana;
text-align:center;
}
<div id="holder">
<p>Drag files here</p>
<div id="images"></div>
</div>
You probably meant to use:
stop_and_prevent(e);
in your drop handler instead of the current:
e.stop_and_prevent();
Also, since files is of type FileList and not Array you won't be able to use map() directly on it. Just use a normal loop or a [].forEach.call() instead.
You don't need to prevent events on the dragleave handler.
Updated code:
var el = document.getElementById('holder');
function stop_and_prevent(e) {
e.stopPropagation();
e.preventDefault();
}
function load_images(files) {
var images = document.getElementById("images");
[].forEach.call(files, function(file) {
if (file.type.match('image.*')) {
var reader = new FileReader();
reader.onload = function() {
var img = document.createElement('img');
img.src = this.result; //=reader.result, or use event.target.result
images.appendChild(img);
}
reader.readAsDataURL(file);
}
});
}
function onDrop(e) {
stop_and_prevent(e);
load_images(e.dataTransfer.files);
return false;
}
el.addEventListener('dragenter', stop_and_prevent);
el.addEventListener('dragover', stop_and_prevent);
el.addEventListener('drop', onDrop);
div#holder {
border: 5px dashed #ccc;
height:400px;
width:400px;
font-family:Verdana;
text-align:center;
}
<div id="holder">
<p>Drag files here</p>
<div id="images"></div>
</div>
I'm trying to customize a jQuery lightbox plugin called LightGallery to achieve the following result:
1- Make the script fetch all images from a folder, using index increment as an image path;
2- Make the Lightbox open after clicking another element.
The problem is:
The plugin opens the lightbox one time only!.
I'm using trigger('click') to fires it for the first time, but after closing it and trying to click to repeat it again it does NOT work.
the plugin looks destroyed and it opens one image only!
I want it to opens the lightbox every time I click the targetted elements.
Here's my attempts: ( Pen here )
$(document).ready(function() {
var $lg = $('#lightgallery');
function fetchFolderImages() {
var checkImages, endCheckImages;
var img;
var imgArray = new Array();
var i = 1;
var myInterval = setInterval(loadImage, 1);
if ($lg.children().length > 0) {
checkImages = false;
endCheckImages = true;
} else {
checkImages = true;
endCheckImages = false;
}
function loadImage() {
if (checkImages) {
checkImages = false;
img = new Image();
img.src = 'http://sachinchoolur.github.io/lightGallery/static/img/' + i + '.jpg';
img.onload = moreImagesExists;
img.onerror = noImagesExists;
}
if (endCheckImages) {
clearInterval(myInterval);
console.log('function [loadImage] done');
runLightGallery();
return;
}
}
function moreImagesExists() {
imgArray.push(img);
$lg.append($('<a/>', {
'href': img.src
}).html(img));
i++;
checkImages = true;
console.log('function [moreImagesExists] done');
}
function noImagesExists() {
endCheckImages = true;
console.log('function [noImagesExists] done');
}
console.log('function [fetchFolderImages] done');
}
function runLightGallery() {
if ($lg.lightGallery()) {
//alert('working');
} else {
//alert('destroyed');
$lg.lightGallery({
thumbnail: true
});
}
//trigger click event on image to open the lightbox
$lg.children('a').trigger('click');
//empty method, thought we may can use
$lg.on('onAfterOpen.lg', function(event) {
//maybe we can use this method?
});
$lg.on('onCloseAfter.lg', function(event) {
$lg.children().remove();
$lg.toggle();
//$lg.lightGallery().destroy(true);
});
console.log('function [runLightGallery] done');
}
$('.gallery-item').each(function() {
$(this).on('click', function() {
$lg.toggle();
fetchFolderImages();
});
});
});
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/css/lightgallery.css" />
</head>
<body>
<div class="gallery">
<div class="gallery-item">Gallery Item 1</div>
<div class="gallery-item">Gallery Item 2</div>
<div class="gallery-item">Gallery Item 3</div>
</div>
<div id="lightgallery" style="display: none; border: 5px solid red"></div>
<!--============== scripts ==============-->
<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.js"></script>
<!-- jQuery mouse wheel -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.js"></script>
<!-- lightGallery : a lightbox jQuery plugin -->
<script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lightgallery.js"></script>
<!-- lightGallery plugin for thumbnails -->
<script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lg-thumbnail.js"></script>
</body>
</html>
LightGallery needs to be destroyed and initialized again
To destroy LightGallery use this code $lg.data('lightGallery').destroy(true);
source : https://github.com/sachinchoolur/lightGallery/issues/238#issuecomment-161020492
Pen
$(document).ready(function() {
var $lg = $('#lightgallery');
function fetchFolderImages() {
var checkImages, endCheckImages;
var img;
var imgArray = new Array();
var i = 1;
var myInterval = setInterval(loadImage, 1);
if ($lg.children().length > 0) {
checkImages = false;
endCheckImages = true;
} else {
checkImages = true;
endCheckImages = false;
}
function loadImage() {
if (checkImages) {
checkImages = false;
img = new Image();
img.src = 'http://sachinchoolur.github.io/lightGallery/static/img/' + i + '.jpg';
img.onload = moreImagesExists;
img.onerror = noImagesExists;
}
if (endCheckImages) {
clearInterval(myInterval);
console.log('function [loadImage] done');
runLightGallery();
return;
}
}
function moreImagesExists() {
imgArray.push(img);
$lg.append($('<a/>', {
'href': img.src
}).html(img));
i++;
checkImages = true;
console.log('function [moreImagesExists] done');
}
function noImagesExists() {
endCheckImages = true;
console.log('function [noImagesExists] done');
}
console.log('function [fetchFolderImages] done');
}
function runLightGallery() {
if ($lg.lightGallery()) {
//alert('working');
} else {
//alert('destroyed');
$lg.lightGallery({
thumbnail: true
});
}
//trigger click event on image to open the lightbox
$lg.children('a').trigger('click');
//empty method, thought we may can use
$lg.on('onAfterOpen.lg', function(event) {
//maybe we can use this method?
});
$lg.on('onCloseAfter.lg', function(event) {
$lg.children().remove();
$lg.toggle();
$lg.data('lightGallery').destroy(true);
});
console.log('function [runLightGallery] done');
}
$('.gallery-item').each(function() {
$(this).on('click', function() {
$lg.toggle();
fetchFolderImages();
});
});
});
<html>
<head>
<link type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/css/lightgallery.css" />
</head>
<body>
<div class="gallery">
<div class="gallery-item">Gallery Item 1</div>
<div class="gallery-item">Gallery Item 2</div>
<div class="gallery-item">Gallery Item 3</div>
</div>
<div id="lightgallery" style="display: none; border: 5px solid red"></div>
<!--============== scripts ==============-->
<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.js"></script>
<!-- jQuery mouse wheel -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.js"></script>
<!-- lightGallery : a lightbox jQuery plugin -->
<script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lightgallery.js"></script>
<!-- lightGallery plugin for thumbnails -->
<script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lg-thumbnail.js"></script>
</body>
</html>
You are not destroying LightGallary the right way.
Use this for 'onCloseAfter.lg' event:
$lg.on('onCloseAfter.lg', function(event) {
$lg.children().remove();
$lg.toggle();
//$lg.lightGallery().destroy(true);
$lg.data('lightGallery').destroy(true);
});
I quickly looked through your code and saw you are loading dynamic data
Try even delegation , https://learn.jquery.com/events/event-delegation/
The problem is that at the moment of the event binding , not all the "a" elements really existing to bind event on it
Your trigger event should be something like
$(document).on('click','#someId a:first-child',function(){
})
Can anyone tell me why the touchenter event is not working in this code. The mouseenter works fine on a desktop. Should be so simple, I'm missing something though.
Example here - http://jsfiddle.net/gCEqH/6/
Full code below:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<img id="myImg" src="http://jackiehutchings.com/wp-content/uploads/2011/09/g-plus-icon-96x96.png" />
<script>
$(window).load(function() {
$('#myImg').on("touchenter mouseenter", function(event){
alert('entered!');
});
});
</script>
</body>
</html>
Maybe something like this would work?
var elementIdTouching = "";
$('body').on("touchmove", function(e){
var tList = e.touches; // get list of all touches
for (var i = 0; i < tList.length; i++) {
var thisTouch = tList[i]; // not 100% sure about this
var elementTouching = document.elementFromPoint(
thisTouch.screenX,
thisTouch.screenY
);
if (elementTouching.id != elementIdTouching) {
elementIdTouching = elementTouching.id;
if (elementTouching.id == "myImg") {
alert("entered!");
}
}
}
}).on("touchend", function(e){
elementIdTouching = "";
});
$('#myImg').on("mouseenter", function(e){
alert('entered!');
});
tList ~ https://developer.mozilla.org/en-US/docs/Web/API/TouchList
Disclaimer: I haven't tested this.
I'm trying to get this piece of code work in Chrome (latest build 10.0.648.205) and it works as expected in Firefox. Here, the e.target.result of the showImage function is empty. Can anyone tell me what Am I doing wrong?
$(function () {
var dropbox = document.getElementById("dropimage");
dropbox.addEventListener("dragenter", function (e) {
this.className = "over";
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("dragleave", function (e) {
var target = e.target;
if (e && e === dropbox) {
this.className = "";
}
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
var count = files.length;
if (count > 0) {
handleFiles(files)
}
}, false);
function handleFiles(files) {
$("#droplabel").html("Processing...");
file = files[0];
var reader = new FileReader();
reader.onloadend = showImage;
reader.readAsDataURL(file);
}
function showImage(e) {
$("#playerImage").attr("src", e.target.result);
$("#droplabel").html("Done");
}
});
HTML is straight-forward (I took the lines that include the scripts for simplicity):
<html>
<body>
<img id="playerImage"/>
<div id="dropimage">
<span id="droplabel">Drop file here...</span>
</div>
</body>
</html>
Also, if I try to change the dropbox.addEventListener for jQuery's $.bind, it doesn't do anything at all. Any thoughts?
The problem was that I was opening the html as a file. Chrome doesn't like that, so I resolved the problem by placing my html file in the wwwroot folder and opening it using a localhost/dnd.html address.