Skip to content

Instantly share code, notes, and snippets.

@craigiswayne craigiswayne/README.md
Last active Jun 29, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jun 28, 2019

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

@craigiswayne

This comment has been minimized.

Copy link
Owner Author

commented Jun 29, 2019

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
You can’t perform that action at this time.