Skip to content

Instantly share code, notes, and snippets.

@craigiswayne
Last active June 29, 2019 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigiswayne/0c3f1481811cbce3d39499ea4d7c5884 to your computer and use it in GitHub Desktop.
Save craigiswayne/0c3f1481811cbce3d39499ea4d7c5884 to your computer and use it in GitHub Desktop.
Gravity Forms Post Image Upload Preview

Gravity Forms Post Image Upload Preview

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);
@ITFGouws
Copy link

Hello, can you please tell me where I should load this code?

@craigiswayne
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment