0

First of all, I know there are many questions related to this question. But what the problem is that they are all related somehow to jquery.

But my question implements the vanilla javascript.

Basically, everything works fine except the onselect(). I am unable to get the URL of the attachment.

Here is the code.

var custom_uploader;

var uploadButton = document.getElementById('upload_logo_button');

uploadButton.addEventListener("click", function(e) {
    e.preventDefault();

    if ( custom_uploader ) {
        custom_uploader.open();
        return;
    }

    custom_uploader  = wp.media.frames.file_frame = wp.media({
        frame: 'select',
        title: 'Choose Image',
        button: {
            text: 'Select Image'
        },
        multiple: false
    });

    custom_uploader.onselect = function() {
        var attachment = custom_uploader.state().get('selection').first().toJSON();
        console.log(attachment);
        var uploadLogoImage = document.getElementById("upload_image").innerHTML(attachment.url);
    }

    //Open the uploader dialog
       custom_uploader.open();
});

Will please someone tell me why I am unable to get the URL of the image even the image gets successfully uploaded to the WP media. Thanks in advance. If anyone needs further info, please don't hesitate to ask. Once again thanks.

1 Answer 1

1

custom_uploader is actually an instance of wp.media() and not an HTML element, so the variable does not have a onselect property, but it does have a on() method/function which you can use to listen to the select event which is triggered after an attachment is selected.

Secondly, an HTML element does not have a innerHTML() method, only a property of the same name that we can use to change the inner HTML of the element like so: <Element>.innerHTML = 'foo <b>bar bold</b> baz'. Please check the MDN web docs for more details.

So to fix the issues, change this:

custom_uploader.onselect = function() {
    var attachment = custom_uploader.state().get('selection').first().toJSON();
    console.log(attachment);
    var uploadLogoImage = document.getElementById("upload_image").innerHTML(attachment.url);
}

to:

custom_uploader.on( 'select', function() {
    var attachment = custom_uploader.state().get('selection').first().toJSON();
    console.log(attachment);
    var uploadLogoImage = document.getElementById("upload_image").innerHTML = attachment.url;
} );

Also, if #upload_image is actually an <input /> or textarea field, then use the value property to change the input/textarea value, or you could instead use setAttribute().

1
  • 1
    Thanks, its working now. Jun 16, 2021 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.