Files
wearwell/static/js/add_product.js
2026-01-30 14:02:35 +03:30

89 lines
2.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
document.addEventListener('DOMContentLoaded', function () {
const imageInput = document.getElementById('image-input');
const imagePreview = document.getElementById('image-preview');
const uploadArea = document.getElementById('image-upload-area');
imageInput.addEventListener('change', function (e) {
updatePreview();
});
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
uploadArea.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
['dragenter', 'dragover'].forEach(eventName => {
uploadArea.addEventListener(eventName, highlight, false);
});
['dragleave', 'drop'].forEach(eventName => {
uploadArea.addEventListener(eventName, unhighlight, false);
});
function highlight() {
uploadArea.style.borderColor = '#007bff';
uploadArea.style.background = '#f8f9fa';
}
function unhighlight() {
uploadArea.style.borderColor = '#ccc';
uploadArea.style.background = '';
}
uploadArea.addEventListener('drop', handleDrop, false);
function handleDrop(e) {
const dt = e.dataTransfer;
const files = dt.files;
imageInput.files = files;
updatePreview();
}
function updatePreview() {
imagePreview.innerHTML = '';
const files = imageInput.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.match('image.*')) continue;
const reader = new FileReader();
reader.onload = function (e) {
const previewItem = document.createElement('div');
previewItem.className = 'preview-item';
const img = document.createElement('img');
img.src = e.target.result;
const removeBtn = document.createElement('button');
removeBtn.className = 'remove-image';
removeBtn.innerHTML = '×';
removeBtn.onclick = function () {
previewItem.remove();
const dt = new DataTransfer();
const inputFiles = imageInput.files;
for (let j = 0; j < inputFiles.length; j++) {
if (j !== i) {
dt.items.add(inputFiles[j]);
}
}
imageInput.files = dt.files;
};
previewItem.appendChild(img);
previewItem.appendChild(removeBtn);
imagePreview.appendChild(previewItem);
};
reader.readAsDataURL(file);
}
}
});