• Resolved ar27111994

    (@ar27111994)


    Copied from Stackoverflow:

    I’m trying to create custom galleries for my wordpress plugin, but the jquery append method doesn’t work for the gallery div when there are already one or more elements present in that div. The gallery divs are dynamically created as there can be multiple galleries in a post. I’ve searched and tried many things including jQuery live event, but apparently wordpress media uploader doesn’t support that event. Moreover, multiple selections are working, so all of the images get appended successfully. But, that’s all good only when the gallery div is empty, so Please help!

    
      jQuery(document).ready(function() {
    
          var gallerymediaUploader;
          var gallery;
          var button;
          var design;
          var selection;
    
              jQuery(document).on('click', 'input.gallery_uploads', function(e) {
            gallery = jQuery(this).next('div.gallery_uploads');
            button = jQuery(this);
    
            // Extend the wp.media object
            gallerymediaUploader = wp.media({
                  title: '<?php _e( "Pick the images for the gallery of this entry", "textdomain" ); ?>',
                          multiple: true,
                          library: { type: 'image' }, });
    
            // When a file is selected, grab the URL and set it as the text field's value
            gallerymediaUploader.on('select', function() {
                length = gallerymediaUploader.state().get("selection").length;
                selection = gallerymediaUploader.state().get('selection');
                selection.map( function( attachment ) {
                    attachment = attachment.toJSON();
                    gallery.append('<img src="' + attachment.url + '">');
                    gallery.append('<input type="hidden" name="gallery[' + gallery.parents("div.project").data("index") + '][' + gallery.children("img").length + ']" value="' + attachment.url + '">');
            });
                gallery.show();
                if(!button.next('.remove_gallery').length){
                    jQuery('<input type="button" value="<?php _e( "Remove All Images", "textdomain" ); ?>" class="button remove_gallery" />').insertAfter(button).css("float", "right");
                    button.css("float", "right");
                }
            });
            // Open the uploader dialog
            gallerymediaUploader.open();
          });
    
        });

    Note: I’ve also tried removing wp media uploader code entirely with appending some dummy image upon every click, in which case everything works fine every time, i.e., the dummy image gets appended ever time. Hence the append problem arises only when appending images inside wp media uploader on (‘select’, function(){}); (Updated Title). Please Help!

  • The topic ‘wp media uploader on (‘select’, function(){}); – jquery append not working when’ is closed to new replies.