This is the snippet I use for immediately previewing an image loaded with gravity forms post type
You can add this snippet to the bottom of your javascript file or enqueue it using wp_enqueue_script
var fileInputImageUploader = fileInputImageUploader || {}; | |
Object.assign( fileInputImageUploader, { | |
options: { | |
inputSelector: 'form input[type=file]', | |
placeholderSelector: 'label[for="{{inputID}}"]' | |
}, | |
removeStyles: function(){ | |
document.querySelectorAll('style.post-image-upload-preview').forEach( e => { | |
e.parentNode.removeChild(e); | |
}); | |
}, | |
addStyles: function(inputID, imageURL ){ | |
let styleID = `post-image-upload-preview-${inputID}` | |
let styles = document.querySelector(`style#${styleID}`); | |
if( styles ){ | |
styles.parentNode.removeChild(styles); | |
} | |
styles = document.body.appendChild(document.createElement('style')); | |
styles.setAttribute('id', styleID); | |
styles.setAttribute('class','post-image-upload-preview'); | |
styles.innerHTML = ` | |
label[for=${inputID}].gfield_label:after { | |
content: ""; | |
display:block; | |
width: 100px; | |
height:100px; | |
background-size: contain; | |
background-repeat: no-repeat; | |
background-position: center; | |
border: 1px solid #0c0c0c; | |
background-image: url(${imageURL}); | |
}`; | |
}, | |
preview: function(){ | |
if( !(this instanceof HTMLInputElement) || 'file' !== this.type ){ | |
alert( 'Invalid input received...' ); | |
fileInputImageUploader.removeStyles() | |
return; | |
} | |
if( !this.files || this.files.length < 1 ){ | |
alert( 'No files received' ); | |
fileInputImageUploader.removeStyles() | |
return; | |
} | |
let reader = new FileReader(); | |
reader.inputElement = this; | |
reader.onload = function (e) { | |
fileInputImageUploader.addStyles(`${this.inputElement.id}`, e.target.result); | |
}; | |
reader.readAsDataURL(this.files[0]); | |
}, | |
init: function(){ | |
jQuery(fileInputImageUploader.options.inputSelector).each(function(i){ | |
jQuery(this).on('change', fileInputImageUploader.preview.bind(this) ); | |
}) | |
} | |
}); | |
jQuery(document).ready(fileInputImageUploader.init); |
You can add this snippet to the bottom of your javascript file
or enqueue it using wp_enqueue_script
....I've updated the script so that its a little more dynamic.
Hello, can you please tell me where I should load this code?