Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magnific Popup with upload image preview

I'm using Magnific popup to display an upload form where the user can select multiple images to upload and preview them before submitting the form, I let the user preview the images plus add a from inputs underneath the image when he clicks on it to enter the caption and alt for it, here's the code that I have ...

(function() {
            if ($("a.uploadMediaImageForm").length) {
                $("a.uploadMediaImageForm").magnificPopup({
                    type: 'inline',
                    preloader: false,
                    closeOnBgClick: false,
                    enableEscapeKey: false,
                    focus: '#name',

                    removalDelay: 500, //delay removal by X to allow out-animation

                    // When elemened is focused, some mobile browsers in some cases zoom in
                    // It looks not nice, so we disable it:
                    callbacks: {
                        beforeOpen: function() {

                            if ($(window).width() < 700) {
                                this.st.focus = false;
                            } else {
                                this.st.focus = '#name';
                            }

                            this.st.mainClass = this.st.el.attr('data-effect');
                        },

                        open: function() {

                            if ($("input#imageUpload").length) {

                                $("input#imageUpload").on('change', function() {

                                    //Get count of selected files
                                    var countFiles = $(this)[0].files.length;

                                    var imgPath = $(this)[0].value;
                                    var extension = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
                                    var previewHolder = $("ul.imagePreview");
                                    previewHolder.empty();

                                    if (extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg") {
                                        if (typeof(FileReader) != "undefined") {

                                            //loop for each file selected for uploaded.
                                            for (var i = 0; i < countFiles; i++) {

                                                var reader = new FileReader();
                                                reader.onload = function(e) {

                                                    $("<li><img src='" + e.target.result +"'></li>").appendTo(previewHolder);
                                                }

                                                previewHolder.show();
                                                reader.readAsDataURL($(this)[0].files[i]);
                                            }

                                        } else {
                                            alert("This browser does not support FileReader.");
                                        }
                                    } else {
                                        alert("Please select only images");
                                    }
                                });
                            } //Image upload preview

                            if($("ul.imagePreview").length) {
                                $("ul.imagePreview").on("click", "li", function(event) {
                                    if($(this).hasClass("selected")) {
                                        $(this).removeClass("selected");
                                        $(this).find("div").remove();
                                    } else {
                                        $(this).addClass("selected");
                                        $(this).append("<div><label><span>Image Alt</span><input type='text'></label><label><span>Image Caption</span><input type='text'></label></div>");
                                    }
                                });

                                $("ul.imagePreview").on("click", "div", function(event) {
                                    event.stopPropagation();
                                });
                            }//add form when clicked on an image
                        },

                        beforeClose: function() {
                            // $("ul.imagePreview").empty();
                            var countFiles = "";
                            var imgPath = "";
                            var extension = "";
                            var previewHolder = $("ul.imagePreview");
                            previewHolder.empty();
                        }
                    },

                    midClick: true // allow opening popup on middle mouse click. Always set
                });
            }
        })(); //popup Forms and Uploads
div.uploadPopup {
    width: 80%;
    margin: auto;
    background: white;
    position: relative;
    padding: 40px;
}

label {
    width: 100%;
    margin-bottom: 20px;
    clear: both;
}

ul.imagePreview {
    width: 100%;
    clear: both;
    display: block;
}

ul.imagePreview li {
    width: 100%;
    display: block;
    margin-bottom: 20px;
    max-height: 150px;
    cursor: pointer;
}

ul.imagePreview li.selected {
    max-height: auto;
}

ul.imagePreview li img {
    max-height: 150px;
    display: block;
    margin: auto;
}
<link href="https://cdn.jsdelivr.net/jquery.magnific-popup/1.0.0/magnific-popup.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.0.1/jquery.magnific-popup.min.js"></script>
<a href="#uploadMediaImageForm" class="uploadMediaImageForm" data-effect="mfp-3d-unfold">Upload Media</a>

<div id="uploadMediaImageForm" class="uploadPopup mfp-with-anim mfp-hide">
    <form action="#">

        <label class="upload">
            <span>Upload Images</span>
            <input id="imageUpload" type="file" multiple>
        </label>

        <ul class="imagePreview">

        </ul>
    </form>
</div>

Now everything works fine the first time, but when I close the popup and re-open it again, something wrong happens in the image previewer, it duplicates the images I choose and sometimes doesn't even show the image if it were the last image I choose before closing.

I tried to set all the variables before closing the popup and clear the image preview ul element, but that didn't help.

I need your help guys, what am I doing wrong here?


EDIT

I gave the form itself an id of "fileForm" and tried to reset the whole form and empty the ul.imagePreview before closing the popup with this code ...

$("#fileForm")[0].reset();
$("ul.imagePreview").empty();

But still no luck, it still duplicated any image I upload the second time after closing the popup and opening it again !!

need help here.

like image 995
Ruby Avatar asked Jan 29 '16 09:01

Ruby


1 Answers

You are binding more and more listeners to the same event:

Your form always exists in your document even when the popup is closed, you just hide it most of the time (using the class mfp-hide).

Each time you open the popup, the callback "open" is called, which bind a function to the change event of your input, and this callback do the preview stuff.

But if you open the popup twice, it will bind again the same function to the same event on the same input. That's why you have duplicate: the code is called twice.

Move all your binding outside your callback so that they will be done once:

 (function() {

    if ($("input#imageUpload").length) {
        $("input#imageUpload").on('change', function() {

            //Get count of selected files
            var countFiles = $(this)[0].files.length;

            var imgPath = $(this)[0].value;
            var extension = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
            var previewHolder = $("ul.imagePreview");
            previewHolder.empty();

            if (extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg") {
                if (typeof(FileReader) != "undefined") {

                    //loop for each file selected for uploaded.
                    for (var i = 0; i < countFiles; i++) {

                        var reader = new FileReader();
                        reader.onload = function(e) {

                            $("<li><img src='" + e.target.result +"'></li>").appendTo(previewHolder);
                        }

                        previewHolder.show();
                        reader.readAsDataURL($(this)[0].files[i]);
                    }
                } else {
                     alert("This browser does not support FileReader.");
                }
            } else {
                alert("Please select only images");
            }
        });
    } //Image upload preview

    if($("ul.imagePreview").length) {
        $("ul.imagePreview").on("click", "li", function(event) {
            if($(this).hasClass("selected")) {
                $(this).removeClass("selected");
                $(this).find("div").remove();
            } else {
                $(this).addClass("selected");
                $(this).append("<div><label><span>Image Alt</span><input type='text'></label><label><span>Image Caption</span><input type='text'></label></div>");
            }
        });

        $("ul.imagePreview").on("click", "div", function(event) {
            event.stopPropagation();
        });
    }//add form when clicked on an image

    if ($("a.uploadMediaImageForm").length) {
        $("a.uploadMediaImageForm").magnificPopup({
            type: 'inline',
            preloader: false,
            closeOnBgClick: false,
            enableEscapeKey: false,
            focus: '#name',

            removalDelay: 500, //delay removal by X to allow out-animation

            // When elemened is focused, some mobile browsers in some cases zoom in
            // It looks not nice, so we disable it:
            callbacks: {
                beforeOpen: function() {

                    if ($(window).width() < 700) {
                        this.st.focus = false;
                    } else {
                        this.st.focus = '#name';
                    }

                    this.st.mainClass = this.st.el.attr('data-effect');
                },

                beforeClose: function() {
                    ///$("ul.imagePreview").empty();
                    var countFiles = "";
                    var imgPath = "";
                    var extension = "";
                    var previewHolder = $("ul.imagePreview");
                    previewHolder.empty();
                    $("#fileForm")[0].reset();
                }
            },

            midClick: true // allow opening popup on middle mouse click. Always set
        });
    }
})(); //popup Forms and Uploads
div.uploadPopup {
    width: 80%;
    margin: auto;
    background: white;
    position: relative;
    padding: 40px;
}

label {
    width: 100%;
    margin-bottom: 20px;
    clear: both;
}

ul.imagePreview {
    width: 100%;
    clear: both;
    display: block;
}

ul.imagePreview li {
    width: 100%;
    display: block;
    margin-bottom: 20px;
    max-height: 150px;
    cursor: pointer;
}

ul.imagePreview li.selected {
    max-height: auto;
}

ul.imagePreview li img {
    max-height: 150px;
    display: block;
    margin: auto;
}
<link href="https://cdn.jsdelivr.net/jquery.magnific-popup/1.0.0/magnific-popup.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.0.1/jquery.magnific-popup.min.js"></script>
<a href="#uploadMediaImageForm" class="uploadMediaImageForm" data-effect="mfp-3d-unfold">Upload Media</a>

<div id="uploadMediaImageForm" class="uploadPopup mfp-with-anim mfp-hide">
    <form action="#" id="fileForm">

        <label class="upload">
            <span>Upload Images</span>
            <input id="imageUpload" type="file" multiple>
        </label>

        <ul class="imagePreview">

        </ul>
    </form>
</div>
like image 118
Pandawan Avatar answered Nov 01 '22 04:11

Pandawan