Skip to content

Instantly share code, notes, and snippets.

@samilkorkmaz
Created March 3, 2024 19:44
Show Gist options
  • Save samilkorkmaz/e978f23e2742bff7c8c0137332ea9136 to your computer and use it in GitHub Desktop.
Save samilkorkmaz/e978f23e2742bff7c8c0137332ea9136 to your computer and use it in GitHub Desktop.
dropify.js does not support preview of WebP images, this JS fixes it
function displayPreviewsOfExistingWebPImages () { // Call this function when page is ready, i.e. $(document).ready(displayPreviewsOfExistingWebPImages);
// Initialize Dropify on all elements with the class .dropify
var dropifyInstances = $('.dropify').dropify();
// Iterate over each Dropify instance
dropifyInstances.each(function() {
// Get the current instance's element and defaultFile data attribute
var element = $(this);
var defaultFile = element.data('default-file');
// Check if the defaultFile exists and ends with '.webp'
if (defaultFile && defaultFile.endsWith('.webp')) {
// Find the Dropify preview container for the current instance
var previewContainer = element.closest('.dropify-wrapper').find('.dropify-render');
var previewImg = $('<img />').attr('src', defaultFile).css({"max-height": "100%", "max-width": "100%"});
// Clear any existing content in the preview container
previewContainer.empty();
// Append the WebP image as the preview for the current instance
previewContainer.append(previewImg);
// Show the clear button for the current instance
element.closest('.dropify-wrapper').find('.dropify-clear').show();
// Optionally, hide the message that prompts users to "Drag and drop a file here or click"
element.closest('.dropify-wrapper').find('.dropify-message').hide();
}
});
}
function showPreviewIncludingWebPFiles() { // Call this function whenever you add a new image
var dropifyElements = document.querySelectorAll('.dropify');
// Iterate over each element
dropifyElements.forEach(function(dropifyInput) {
dropifyInput.addEventListener('change', function(e) {
var file = e.target.files[0];
if (file && file.type === 'image/webp') {
var reader = new FileReader();
reader.onload = function(e) {
// Find the Dropify preview element relative to the current Dropify input
var previewContainer = dropifyInput.closest('.dropify-wrapper').querySelector('.dropify-render');
var previewImage = previewContainer.querySelector('img');
if (!previewImage) {
// If the <img> tag doesn't exist, create it
previewImage = document.createElement('img');
previewContainer.appendChild(previewImage);
}
// Set the src of the <img> to the read file for preview
previewImage.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment