Get image name onclick with Javascript before upload - javascript

I upload images from one file input, but before that I display them with javascript. I want to add a function to select the primary image on click. I want to store the clicked image's name in a hidden input. My problem is I can't get the image's original name by clicking on the image itself. I found a solution but that displays every images name.
For example I select these images:
Example.jpg, Example2.png, Example3.jpg
I display them like this:
<div class="uploaded-image" data-index="1" id="image-1">
<img src="blob:http://localhost/5e75ca0e-f912-461e-98a6-9f8ad302bc84">
<button class="delete-image"><i class="iui-close"></i></button>
</div>
<div class="uploaded-image" data-index="2" id="image-2">
<img src="blob:http://localhost/5e75ca0e-f912-461e-98a6-9f831344adc84">
<button class="delete-image"><i class="iui-close"></i></button>
</div>
And when I click on image-1, I'd like to get Example.jpg to a hidden text input, instead of blob:...
The only solution I found works with a button and displays all of them.
How can modify it to select the clicked image only?
This is the code:
<input type="submit" value="Show Details" onclick="FileDetails()">
function FileDetails() {
// GET THE FILE INPUT.
var fi = document.getElementById('image-upload');
// VALIDATE OR CHECK IF ANY FILE IS SELECTED.
if (fi.files.length > 0) {
console.log(fi.files);
// RUN A LOOP TO CHECK EACH SELECTED FILE.
for (var i = 0; i <= fi.files.length - 1; i++) {
fi.files[0] = document.getElementById('image-1')
var fname = fi.files.item(i).name; // THE NAME OF THE FILE.
console.log(fname);
}
} else {
alert('Please select a file.')
}
}

Inside your plugin file there is already an event i.e : $container.on("click", function(e) { you can write your code there whenever image divs get clicked to add click image name inside input field .i.e:
$container.on("click", function(e) {
var fi = $("input[type=file]")[0];
prevent(e);
//**get files using index (0,1,2..) add value to input..**//
$("#imgs").val(fi.files.item($(this).data('index')).name)
});
Demo Code :
(function($) {
$.fn.imageUploader = function(options) {
let defaults = {
preloaded: [],
imagesInputName: 'images',
preloadedInputName: 'preloaded',
label: 'Drag & Drop files here or click to browse',
extensions: ['.jpg', '.jpeg', '.png', '.gif', '.svg'],
mimes: ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'],
maxSize: undefined,
maxFiles: undefined,
};
let plugin = this;
let dataTransfer = new DataTransfer();
// The file input
let $input;
// Set empty settings
plugin.settings = {};
// Plugin constructor
plugin.init = function() {
// Define settings
plugin.settings = $.extend(plugin.settings, defaults, options);
// Run through the elements
plugin.each(function(i, wrapper) {
// Create the container
let $container = createContainer();
// Append the container to the wrapper
$(wrapper).append($container);
// Set some bindings
$container.on("dragover", fileDragHover.bind($container));
$container.on("dragleave", fileDragHover.bind($container));
$container.on("drop", fileSelectHandler.bind($container));
// If there are preloaded images
if (plugin.settings.preloaded.length) {
// Change style
$container.addClass('has-files');
// Get the upload images container
let $uploadedContainer = $container.find('.uploaded');
// Set preloaded images preview
for (let i = 0; i < plugin.settings.preloaded.length; i++) {
$uploadedContainer.append(createImg(plugin.settings.preloaded[i].src, plugin.settings.preloaded[i].id, true));
}
}
});
};
let createContainer = function() {
// Create the image uploader container
let $container = $('<div>', {
class: 'image-uploader'
});
// Create the input type file and append it to the container
$input = $('<input>', {
type: 'file',
id: plugin.settings.imagesInputName + '-' + random(),
name: plugin.settings.imagesInputName + '[]',
accept: plugin.settings.extensions.join(','),
multiple: ''
}).appendTo($container);
// Create the uploaded images container and append it to the container
let $uploadedContainer = $('<div>', {
class: 'uploaded'
}).appendTo($container),
// Create the text container and append it to the container
$textContainer = $('<div>', {
class: 'upload-text'
}).appendTo($container),
// Create the icon and append it to the text container
$i = $('<i>', {
class: 'iui-cloud-upload'
}).appendTo($textContainer),
// Create the text and append it to the text container
$span = $('<span>', {
text: plugin.settings.label
}).appendTo($textContainer);
// Listen to container click and trigger input file click
$container.on('click', function(e) {
// Prevent browser default event and stop propagation
prevent(e);
// Trigger input click
$input.trigger('click');
});
// Stop propagation on input click
$input.on("click", function(e) {
e.stopPropagation();
});
// Listen to input files changed
$input.on('change', fileSelectHandler.bind($container));
return $container;
};
let prevent = function(e) {
// Prevent browser default event and stop propagation
e.preventDefault();
e.stopPropagation();
};
let createImg = function(src, id, preloaded) {
// Create the upladed image container
let $container = $('<div>', {
class: 'uploaded-image'
}),
// Create the img tag
$img = $('<img>', {
src: src
}).appendTo($container),
// Create the delete button
$button = $('<button>', {
class: 'delete-image'
}).appendTo($container),
// Create the delete icon
$i = $('<i>', {
class: 'iui-close'
}).appendTo($button);
// If the image is preloaded
if (preloaded) {
// Set a identifier
$container.attr('data-preloaded', true);
// Create the preloaded input and append it to the container
let $preloaded = $('<input>', {
type: 'hidden',
name: plugin.settings.preloadedInputName + '[]',
value: id
}).appendTo($container)
} else {
// Set the index
$container.attr('data-index', id);
}
//**** on click of image...***//
$container.on("click", function(e) {
var fi = $("input[type=file]")[0];
prevent(e);
console.log($(this).data('index'))
console.log(fi.files.item($(this).data('index')).name);
//**get files using index (0,1,2..) add value to input..**//
$("#imgs").val(fi.files.item($(this).data('index')).name)
});
// Set delete action
$button.on("click", function(e) {
// Prevent browser default event and stop propagation
prevent(e);
// Get the parent element
let $parent = $container.parent();
// If is not a preloaded image
if ($container.data('preloaded') === true) {
// Remove from preloaded array
plugin.settings.preloaded = plugin.settings.preloaded.filter(function(p) {
return p.id !== id;
});
} else {
// Get the image index
let index = parseInt($container.data('index'));
// Update other indexes
$parent.find('.uploaded-image[data-index]').each(function(i, cont) {
if (i > index) {
$(cont).attr('data-index', i - 1);
}
});
// Remove the file from input
dataTransfer.items.remove(index);
// Update input files
$input.prop('files', dataTransfer.files);
}
// Remove this image from the container
$container.remove();
// If there is no more uploaded files
if (!$parent.children().length) {
// Remove the 'has-files' class
$parent.parent().removeClass('has-files');
}
});
return $container;
};
let fileDragHover = function(e) {
// Prevent browser default event and stop propagation
prevent(e);
// Change the container style
if (e.type === "dragover") {
$(this).addClass('drag-over');
} else {
$(this).removeClass('drag-over');
}
};
let fileSelectHandler = function(e) {
// Prevent browser default event and stop propagation
prevent(e);
// Get the jQuery element instance
let $container = $(this);
// Get the files as an array of files
let files = Array.from(e.target.files || e.originalEvent.dataTransfer.files);
// Will keep only the valid files
let validFiles = [];
// Run through the files
$(files).each(function(i, file) {
// Run the validations
if (plugin.settings.extensions && !validateExtension(file)) {
return;
}
if (plugin.settings.mimes && !validateMIME(file)) {
return;
}
if (plugin.settings.maxSize && !validateMaxSize(file)) {
return;
}
if (plugin.settings.maxFiles && !validateMaxFiles(validFiles.length, file)) {
return;
}
validFiles.push(file);
});
// If there is at least one valid file
if (validFiles.length) {
// Change the container style
$container.removeClass('drag-over');
// Makes the upload
setPreview($container, validFiles);
} else {
// Update input files (it is now empty due to a default browser action)
$input.prop('files', dataTransfer.files);
}
};
let validateExtension = function(file) {
if (plugin.settings.extensions.indexOf(file.name.replace(new RegExp('^.*\\.'), '.')) < 0) {
alert(`The file "${file.name}" does not match with the accepted file extensions: "${plugin.settings.extensions.join('", "')}"`);
return false;
}
return true;
};
let validateMIME = function(file) {
if (plugin.settings.mimes.indexOf(file.type) < 0) {
alert(`The file "${file.name}" does not match with the accepted mime types: "${plugin.settings.mimes.join('", "')}"`);
return false;
}
return true;
};
let validateMaxSize = function(file) {
if (file.size > plugin.settings.maxSize) {
alert(`The file "${file.name}" exceeds the maximum size of ${plugin.settings.maxSize / 1024 / 1024}Mb`);
return false;
}
return true;
};
let validateMaxFiles = function(index, file) {
if ((index + dataTransfer.items.length + plugin.settings.preloaded.length) >= plugin.settings.maxFiles) {
alert(`The file "${file.name}" could not be added because the limit of ${plugin.settings.maxFiles} files was reached`);
return false;
}
return true;
};
let setPreview = function($container, files) {
// Add the 'has-files' class
$container.addClass('has-files');
// Get the upload images container
let $uploadedContainer = $container.find('.uploaded'),
// Get the files input
$input = $container.find('input[type="file"]');
// Run through the files
$(files).each(function(i, file) {
// Add it to data transfer
dataTransfer.items.add(file);
// Set preview
$uploadedContainer.append(createImg(URL.createObjectURL(file), dataTransfer.items.length - 1), false);
});
// Update input files
$input.prop('files', dataTransfer.files);
};
// Generate a random id
let random = function() {
return Date.now() + Math.floor((Math.random() * 100) + 1);
};
this.init();
// Return the instance
return this;
};
}(jQuery));
$('.input-images').imageUploader();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="imgs">
<div class="input-images"></div>

Related

check if class exists on that page javascript

I have an index page and a dashboard, on the index I'm using typewriter and particlesjs on the index only, and on the dashboard I have a sidebar.
If I have all the code as-is, I get errors as the page is still looking for typewriter and particlesjs on all pages.
So I have attempted to wrap each section around an if so the plan is if that class or id exists on that page it will only render that JS. So I've created the following code.
edited code below based on groovy_guy's answer
document.querySelector('nav .toggle').addEventListener('click', e => {
document.querySelector('nav .hidden').classList.toggle('show')
});
let checkTypewriter = document.getElementById('typewriter');
if (checkTypewriter.length > 0) {
new Typewriter('#typewriter', {
strings: ['Website Developer', 'Freelancer' , 'System Admin'],
autoStart: true,
loop: true
});
}
let checkParticlesjs = document.getElementsByClassName('particlesjs');
if (checkParticlesjs.length > 0) {
let particles = Particles.init({
selector: '.particlesjs',
color: ['#48F2E3', '#48F2E3', '#48F2E3'],
connectParticles: true,
maxParticles: 200
});
}
let checkSidebar = document.getElementsByClassName('sidebar');
if (checkSidebar.length > 0) {
user_wants_collapse = false;
// Fetch all the details element.
const details = document.querySelectorAll("details");
// Add the onclick listeners.
details.forEach((targetDetail) => {
targetDetail.addEventListener("click", () => {
// Close all the details that are not targetDetail.
details.forEach((detail) => {
if (detail !== targetDetail) {
detail.removeAttribute("open");
};
});
});
});
document.querySelector('section').addEventListener('click', (ev) => {
// close any open details elements that this click is outside of
let target = ev.target;
let detailsClickedWithin = null;
while (target && target.tagName != 'DETAILS') {
target = target.parentNode;
};
if (target && target.tagName == 'DETAILS') {
detailsClickedWithin = target;
};
Array.from(document.getElementsByTagName('details')).filter(
(details) => details.open && details != detailsClickedWithin
).forEach(details => details.open = false);
// if the sidebar collapse is true and is re-expanded by clicking a menu item then clicking on the body should re-close it
if (user_wants_collapse == true && (document.querySelectorAll('.sidebar details'))) {
document.querySelector('body').classList.add('is--expand');
};
});
// when the sidebar menu is clicked this sets the user_wants_collapse var to true or false and toggles is--expand class on body
document.querySelector('.sidebar .menu-link').addEventListener('click', () => {
document.querySelector('body').classList.toggle('is--expand');
user_wants_collapse = !user_wants_collapse
document.querySelector('.sidebar').classList.toggle('is--expand');
// show all text
document.querySelectorAll('.sidebar .title').forEach((el) => {
el.classList.toggle('hidden');
});
// changing sidebar menu items and menu collapse icons
const icon = document.querySelector('.menu-link-arrows span');
if (icon.classList.contains('fa-angle-double-left')) {
icon.classList.remove('fa-angle-double-left');
icon.classList.add('fa-angle-double-right');
} else {
icon.classList.remove('fa-angle-double-right');
icon.classList.add('fa-angle-double-left');
}
});
// making sure the sidebar menu items re-expands the sidebar on click
let x = document.querySelectorAll('.sidebar details');
let i;
for (i = 1; i < x.length; i++) {
x[i].addEventListener('click', () => {
// changing sidebar menu items and menu collapse icons
// change menu items and menu collapse icons
const icon = document.querySelector('.sidebar-drop-parent-arrow span');
if (icon.classList.contains('fa-chevron-down')) {
icon.classList.remove('fa-chevron-down');
icon.classList.add('fa-chevron-up');
} else {
icon.classList.remove('fa-chevron-up');
icon.classList.add('fa-chevron-down');
}
if (document.querySelector('body').classList.contains('is--expand')) {
document.querySelector('body').classList.remove('is--expand');
};
});
};
};
when loading the JS I'm not getting any console errors but I'm not seeing any result of the JS.
Why don't you use querySelector()? I think that's more uniform across your codebase. Besides, I see that you only care about one element and not a list of elements, so this method is ideal since it gets the first element that encounters.
const checkTypewriter = document.querySelector('#typewriter')
if (checkTypewriter) {
// Element with an ID 'typewriter' exist in the DOM.
}
const checkParticlesjs = document.querySelector('.particlesjs')
if (checkParticlesjs) {
// Element with a class named "particlesjs" exist in the DOM.
}
Also, make sure to check if an element exist before attaching an event listener:
const toggleNav = document.querySelector('nav .toggle')
if (toggleNav) {
toggleNav.addEventListener('click', (e) => {
document.querySelector('nav .hidden').classList.toggle('show')
});
}
For Javascript:
var checkTypewriter = document.getElementsByClassName('typewriter');
if (checkTypewriter.length > 0) {
// Here write your code
}
var checkParticlesjs = document.getElementsByClassName('particlesjs');
if (checkParticlesjs.length > 0) {
// Here write your specific code
}
For JQuery:
if ($("#typewriter")[0]){
// Here write your code
}
if ($(".particlesjs")[0]){
// Here write your specific code
}
This is how you can check if your classes exist,

Quill.js add a custom javascript function into the editor

I am using Quill.js to have users create custom user designed pages off the main web page. I have a custom slider that I have written in javascript that will take images and rotate through them. I have the toolbar in quill setup to be able to click on the toolbar to setup the slider in a modal window.
When the user clicks to close the modal slider setup window, I'm trying to insert an edit button in the html editor where the cursor sits so the user can edit the information that was just entered or possible delete the button by removing all the information in the slider modal window.
I have written custom blots, followed all the examples I could find and nothing worked. I did get a custom html tag to show, but not a button. When I requested the html from quill when I setup the custom html tag in the editor, all I get is "" from quill.root.innerHTML none of the custom tag or the information in it even though I see it correctly in the editor.
I would like a button in the editor to make it easy to edit the slider data, as there could be more than one. I am not going to limit the number of sliders. It is up to the user to ruin their own page.
I will not be rendering the slider in the edit html window, just trying to display a button to click on. I do give the user a preview button on the modal window to view the slider if they so choose.
I also would like to store the setup information of the slider in a data tag in json format in the button and change that html button to a tag along with the json data when rendering the html in the browser window.
Can this be done in Quill.js?
I did this by using the import blots embed. I don't register as a button but clicking on the blot I do get a link to the embedded data and trigger the edit of the carousel data on that click.
var Quill;
const BlockEmbed = Quill.import("blots/block/embed");
const Link = Quill.import('formats/link');
class Carousel extends BlockEmbed {
static create(value) {
var self = this;
const node = super.create(value);
node.dataset.carousel = JSON.stringify(value);
value.file.frames.forEach(frame => {
const frameDiv = document.createElement("div");
frameDiv.innerText = frame.title;
frameDiv.className += "previewDiv";
node.appendChild(frameDiv);
});
node.onclick = function () {
if (Carousel.onClick) {
Carousel.onClick(self, node);
}
};
return node;
}
static value(domNode) {
return JSON.parse(domNode.dataset.carousel);
}
static onClick: any;
static blotName = "carousel";
static className = "ql-carousel";
static tagName = "DIV";
}
Quill.register("formats/carousel", Carousel);
I then include this as a script on the page where quill is editing the HTML
<script src="~/js/quilljs-carousel.js"></script>
And then this is the custom javascript to handle the events of the blot displayed in a custom modal dialog in a hidden div tag
<script>
function CarouselClicked(blot, node) {
editCarousel(JSON.parse(node.dataset.carousel), node);
}
var Carousel = Quill.import("formats/carousel");
Carousel.onClick = CarouselClicked;
function carouselToolbarClickHandler() {
createCarousel();
}
var Toolbar = Quill.import("modules/toolbar");
Toolbar.DEFAULTS.handlers.carousel = carouselToolbarClickHandler;
$(document).ready(function() {
var div = $("#editor-container");
var Image = Quill.import('formats/image');
Image.className = "img-fluid";
Quill.register(Image, true);
var quill = new Quill(div.get(0),
{
modules: {
syntax: true,
toolbar: '#toolbar-container'
},
theme: 'snow'
});
div.data('quill', quill);
// Only show the toolbar when quill is ready to go
$('#toolbar-container').css('display', 'block');
div.css('display', 'block');
$('#editor-loading').css('display', 'none');
// Override the quill Image handler and create our own.
quill.getModule("toolbar").addHandler("image", imageHandler);
});
function createCarousel() {
$("#carouselModalForm").removeClass("was-validated").get(0).reset();
$("#carouselModalList").empty();
$("#carouselModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
var data = getCarouselData();
var carouselData = {};
carouselData['file'] = data;
carouselData['speed'] = $('#time').val();
carouselData['height'] = $('#height').val();
carouselData['width'] = $('#width').val();
var quill = $("#editor-container").data().quill;
var range = quill.getSelection(true);
if (range != null) {
quill.insertEmbed(
range.index,
"carousel",
carouselData,
Quill.sources.USER
);
quill.setSelection(range.index + 2, Quill.sources.USER);
}
})
.modal("show");
$('#title').get(0).outerText = "Create Carousel";
}
function editCarousel(value, node) {
$("#carouselModalForm").get(0).reset();
var elem = $("#carouselModalList").empty();
$.each(value.file.frames,
function(i, data) {
$("<option>").appendTo(elem).text(data.title).data("frame", data);
});
$('#time').val(value.speed);
$('#height').val(value.height);
$('#width').val(value.width);
var modal = $("#carouselModal");
modal.find("form").removeClass("was-validated");
modal
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselModal").data("state") !== "saved")
return;
var data = getCarouselData();
var carouselData = {};
carouselData['file'] = data;
carouselData['speed'] = $('#time').val();
carouselData['height'] = $('#height').val();
carouselData['width'] = $('#width').val();
var carousel = Quill.find(node, true);
carousel.replaceWith("carousel", carouselData);
})
.modal("show");
$('#title').get(0).outerText = "Edit Carousel";
}
function getCarouselData() {
var options = $("#carouselModalList").find("option");
var frames = $.map(options,
function(domNode) {
return $(domNode).data("frame");
});
return {
frames : frames
};
}
function getCarouselFrameFormData() {
// Get data from frame
function objectifyForm(formArray) { //serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++) {
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
return objectifyForm($("#carouselFrameModalForm").serializeArray());
}
$("#carouselModalNewFrame").click(function() {
$("#carouselFrameModalForm").removeClass("was-validated").get(0).reset();
$("#backgroundPreview").attr("src", "");
$("#mainPreview").attr("src", "");
$("#carouselFrameModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselFrameModal").data("state") == "saved") {
var data = getCarouselFrameFormData();
$("<option>").appendTo($("#carouselModalList")).text(data.title).data("frame", data);
}
})
.modal("show");
// Fetch all the forms we want to apply custom Bootstrap validation styles to
});
$("#carouselModalEditFrame").click(function () {
var form = $("#carouselFrameModalForm");
form.removeClass("was-validated").get(0).reset();
var selected = $("#carouselModalList option:selected");
var frame = selected.data("frame");
$.each(Object.keys(frame),
function (i, e) {
$("input[name=" + e + "]", form).val(frame[e]);
});
$("#backgroundPreview").attr("src", frame.backgroundImg);
$("#mainPreview").attr("src", frame.mainImg);
$("#carouselFrameModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselFrameModal").data("state") == "saved") {
var data = getCarouselFrameFormData();
selected.text(data.title).data("frame", data);
}
})
.modal("show");
});
$("#carouselModalRemoveFrame").click(function () {
$("#confirm-delete").modal("show");
});
$("#carouselFrameModalForm").find("input:file").change(function() {
var elem = $(this);
var target = elem.data("target");
var preview = elem.data("preview");
FiletoBase64(this, preview, target);
});
$("#carouselModalList").change(function() {
var selected = $("option:selected", this);
$("#carouselModalEditFrame,#carouselModalRemoveFrame").prop("disabled", !selected.length);
});
$("#carouselModalSave").click(function() {
// Validate frameset
var form = $("#carouselModalForm").get(0);
var select = $("#carouselModalList");
if (select.find("option").length == 0) {
select.get(0).setCustomValidity("Need at least one frame");
} else {
select.get(0).setCustomValidity("");
}
if (form.checkValidity()) {
$("#carouselModal").data("state", "saved");
$("#carouselModal").modal("hide");
}
else {
$("#carouselModalForm").addClass("was-validated");
}
});
$("#carouselFrameModalSave").click(function() {
// Validate frame
if ($("#carouselFrameModalForm").get(0).checkValidity()) {
$("#carouselFrameModal").data("state", "saved");
$("#carouselFrameModal").modal("hide");
}
else {
$("#carouselFrameModalForm").addClass("was-validated");
}
});
$('#confirm-delete-delete').click(function () {
$("#carouselModalList option:selected").remove();
$("#confirm-delete").modal("hide");
});
// #region Image FileExplorer Handler
function insertImageToEditor(url) {
var div = $("#editor-container");
var quill = div.data('quill');
var range = quill.getSelection();
quill.insertEmbed(range.index, 'image', url);
}
function CarouselMainimageHandler() {
$("#CarouselMainimageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#CarouselMainimageSelectModal").modal("show");
}
$("#CarouselMainimageSelectModal").on("hide.bs.modal",
function() {
$("#CarouselMainimageSelectFileExplorer").fileExplorer("destroy");
});
$("#CarouselMainimageSelectSelectButton").click(function() {
var id = $("#CarouselMainimageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
var imageName = $("#CarouselMainimageSelectFileExplorer").fileExplorer("getSelectedFileName");
var imageLink = "#Url.Action("Render", "FileTree")?id=" + id;
$("#mainImageName").val(imageName);
$("#mainImageLink").val(imageLink);
$("#mainImage").attr("src",imageLink);
$("#mainImage").show();
$("#CarouselMainimageSelectModal").modal("hide");
});
function CarouselBackgroundimageHandler() {
$("#CarouselBackgroundimageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#CarouselBackgroundimageSelectModal").modal("show");
}
$("#CarouselBackgroundimageSelectModal").on("hide.bs.modal",
function() {
$("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("destroy");
});
$("#CarouselBackgroundimageSelectSelectButton").click(function() {
var id = $("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
var imageName = $("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("getSelectedFileName");
var imageLink = "#Url.Action("Render", "FileTree")?id=" + id;
$("#backgroundImageName").val(imageName);
$("#backgroundImageLink").val(imageLink);
$("#backgroundImage").attr("src",imageLink);
$("#backgroundImage").show();
$("#CarouselBackgroundimageSelectModal").modal("hide");
});
function imageHandler() {
$("#imageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#imageSelectModal").modal("show");
}
$("#imageSelectModal").on("hide.bs.modal",
function() {
$("#imageSelectFileExplorer").fileExplorer("destroy");
});
$("#imageSelectSelectButton").click(function() {
var id = $("#imageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
insertImageToEditor("#Url.Action("Render", "FileTree")?id=" + id);
$("#imageSelectModal").modal("hide");
});
// #endregion
function Save() {
var div = $("#editor-container");
var quill = div.data('quill');
$('#alertSave').show();
$.post({
url: '#Url.Action("Save")',
data: { BodyHtml: quill.root.innerHTML, locationId: #(Model.LocationId?.ToString() ?? "null") },
headers: {
'#Xsrf.HeaderName': '#Xsrf.RequestToken'
}
}).done(function() {
$('#alertSave').hide();
$('#alertSuccess').show();
setTimeout(function() { $('#alertSuccess').hide(); }, 5000);
}).fail(function(jqXhr, error) {
var alert = $('#alertFailure');
var text = $("#alertFailureText");
text.text(error.ErrorMessage);
alert.show();
});
}
function FiletoBase64(input, imgName, Base64TextName) {
var preview = document.getElementById(imgName);
var file = input.files[0];
var reader = new FileReader();
reader.addEventListener("load",
function() {
preview.src = reader.result;
document.getElementById(Base64TextName).value = reader.result;
},
false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>

Multiple event listeners for a class

I am trying to make multiple drag and drop areas. I am trying to add listeners for a "drop-zone" class (for every element with this class).
var dropZone = document.getElementById('some_area'); // ok
// var dropZone = document.getElementByClassName('drop-zone'); // not working
dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
dropZone.addEventListener('drop', function(e) {
var target_img = $(this).find('img');
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files; // Array of all files
for (var i=0, file; file=files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function(e2) { // finished reading file data.
var img = document.createElement('img');
img.src= e2.target.result;
target_img.attr('src',e2.target.result);
target_img.addClass('full-preview');
}
reader.readAsDataURL(file); // start reading the file data.
} } });
You need to query for all elements that have the specific class.
// Returns a list of the elements within the document
// that match the specified 'drop-zone' class.
var dropZones = document.querySelectorAll('.drop-zone');
for (var i = 0; i < dropZones.length; i++) {
// Add the event listeners for each element of the list.
dropZones[i].addEventListener('dragover', function (e) {
// ...
});
dropZones[i].addEventListener('drop', function (e) {
// ...
});
}

Dropzone.js when removing a mock file created on page load, the default add files message shows

There is a previous unanswered question about this here but no code or answer was provided. I'm hoping providing some code you'll be able to help me out.
Removing any existing file from Dropzone shows dictDefaultMessage
When I load the page I'm adding mock files to the dropzone. When I click remove on one of those files, the default add image text displays in the dropzone even though there are still files present. How does dropzone keep track of the number of files in the drop zone. I've tried directly modifying the myDropzone.files.length property to match the number of mock files but it breaks the dropzone as I've said in the other question. Here is my code for dropzone.
var jsphotos = '#jsphotos';
var mockFiles = [];
Dropzone.autoDiscover = false;
var fileList = new Array;
var fileListCounter = 0;
var photoDropzone = new Dropzone('#photoDropzone', {
url: 'importphotos.cshtml',
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, // MB
method: 'post',
acceptedFiles: 'image/jpeg,image/pjpeg',
dictInvalidFileType: 'Files uploaded must be type .jpg or .jpeg',
init: function () {
this.on("addedfile", function (file) {
// remove size
file.previewElement.querySelector('.dz-size').innerHTML = '';
// add custom button
// Create the remove button
var removeButton = Dropzone.createElement('<i class="fa fa-times-circle-o fa-3x removeButton"></i>');
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
this.on("success", function (file, serverFileName) {
file.previewElement.querySelector('.dz-filename').innerHTML = '<span data-dz-name>'+serverFileName+'</span>';
});
this.on("removedfile", function (file) {
//var rmvFile = "";
//for (f = 0; f < fileList.length; f++) {
// if (fileList[f].fileName == file.name) {
// rmvFile = fileList[f].serverFileName;
// fileListCounter--;
// }
//}
//if (rmvFile) {
// $.ajax({
// url: "deletephoto.cshtml",
// type: "POST",
// data: { "fileList": rmvFile }
// });
//}
});
}
});
$('#photoDropzone').sortable({
items: '.dz-preview',
cursor: 'move',
opacity: 0.5,
containment: "parent",
distance: 10,
tolerance: 'pointer',
sort: function (event, ui) {
var $target = $(event.target);
if (!/html|body/i.test($target.offsetParent()[0].tagName)) {
var top = event.pageY - $target.offsetParent().offset().top - (ui.helper.outerHeight(true) / 2);
ui.helper.css({ 'top': top + 'px' });
}
},
update: function (e, ui) {
// do what you want
}
});
if (jsphotos.length > 0) {
var tmpSplit = jsphotos.split(',');
for (i = 0; i < tmpSplit.length; i++) {
if (tmpSplit[i].length > 0) {
mockFiles.push(tmpSplit[i]);
}
}
}
for (i = 0; i < mockFiles.length; i++) {
// Create the mock file:
var mockFile = { name: mockFiles[i]};
// Call the default addedfile event handler
photoDropzone.emit("addedfile", mockFile);
photoDropzone.emit("success", mockFile, mockFile.name);
// And optionally show the thumbnail of the file:
//photoDropzone.emit("thumbnail", mockFile, '#Globals.tempUploadFolderURL' + mockFile.name);
// Or if the file on your server is not yet in the right
// size, you can let Dropzone download and resize it
// callback and crossOrigin are optional.
photoDropzone.createThumbnailFromUrl(mockFile, '#Globals.tempUploadFolderURL' + mockFile.name);
// Make sure that there is no progress bar, etc...
photoDropzone.emit("complete", mockFile);
// If you use the maxFiles option, make sure you adjust it to the
// correct amount:
//var existingFileCount = 1; // The number of files already uploaded
//Dropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
}
//photoDropzone.files.length = mockFiles.length;
After attempting to code a solution that monitored the count manually and modified the value of the default text, I didn't want a hack to modify class names to 'fool' the dropzone into thinking there were files. So I added this
photoDropzone.files.push(mockFile);
just below
photoDropzone.emit("complete", mockFile);
and now dropzone knows how many files it has, and everything functions appropriately. Files pushed into the array do not get resubmitted, it's the same as adding the mock preview originally.

Dropzone show files exist

I have a problem I am using on my website dropzone.js, but It doesnt work good for me. I have 2 problems. JSON works fine.
In existing files I havent remove button
When I upload by drag and drop it upload file twice
var FormDropzone = function () {
$(function() {
var projectID = $("#projectID").html();
var myDropzone = new Dropzone("#my-dropzone");
$.getJSON('http://'+window.location.hostname+'/project/getFile/'+projectID, function( json ) {
for (var i = 0; i < json.length; i++) {
var mockFile = { name: json[i].name, size: json[i].size };
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, "../../upload_files/project/1/"+json[i].name);
};
})
});
return {
//main function to initiate the module
init: function () {
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, serverFileName) {
FileList = {"serverFileName" : serverFileName, "fileName" : file.name };
});
this.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-sm btn-block'>Remove file</button>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
var projectID = $("#projectID").html();
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
$.post( "http://"+window.location.hostname+"/project/deleteFile", { file_name: file.name, project_id: projectID, FileList : FileList["serverFileName"]});
// Remove the file preview.
_this.removeFile(file);
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
}
}
}
};
}();
For adding remove button you have to add delete option i.e addRemoveLinks : true to the dropzone object.
just like this one :
Dropzone.options.mysample = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
addRemoveLinks : true,
};

Categories

Resources