Search code examples
javascriptjqueryhtmlcssclone

Jquery clone( ) function not working with toggleClass( ). Trying to clone image yet image moves from current location


When a user clicks an image I would like it to clone as a fixed and more larger image but when I try to use the toggleClass() function, the image moves from it's previous location which I do not want. I want to be able to click an image and get a bigger view and be able to toggle it back while only limiting one image at a time

var count = 1;
$(document).ready(function(){
    $(".img_box").click(function(){
        if(count<2){
        $(this).clone().attr({ 'class': 'img_box' + count }).appendTo(".zoom");
        $(this).toggleClass("zoom");
        count++;
        }
    });
});
.img_container {
    justify-content: center;
    display: inline-flex;
    margin: 5px;
    list-style: none;
}
.img_box {
    height: 100px;
    margin: 5px;
    cursor: pointer;
}
.img_box1 {
}
.zoom {
    position: fixed;
    max-width: 55%;
    height: 85%;
    left: -50%;
    right: -50%;
    top: 9%;
    margin: auto;
    padding: auto;
    z-index: 9999;
    border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class='img_container'>
<li><img class='img_box' src='http://3.bp.blogspot.com/-0llDSWL9Xm0/Ta0fJ3ulMDI/AAAAAAAAAAk/G5O-DfxD3PI/s1600/7.jpg' ></li>
</div>

<div class='img_container'>
<li><img class='img_box' src='https://ichef.bbci.co.uk/images/ic/1200x675/p049tgdb.jpg' ></li>
</div>

<div class='img_container'>
<li><img class='img_box' src='http://3.bp.blogspot.com/-uctFXnJjKvc/UCF-SlHorHI/AAAAAAAAAIU/Y4vtiVI1Jjk/s1600/animal+(5).jpg' ></li>
</div>

<div class='img_container'>
<li><img class='img_box' src='http://1.bp.blogspot.com/-g913BsBiiq4/UAFN4Z2XQBI/AAAAAAAADtc/EdyJQODnHBw/s1600/baby-animal-wallpapers-1.jpg' ></li>
</div>


Solution

  • Basically I was also thinking about .insertAfter(this) idea. Added a fiddle here guessing the functionality expected. Can give it a look.

    I removed the zoomed image if the count is larger and decremented the count again so that a new image can be clicked and zoomed.

    var count = 1;
    $(document).ready(function(){
        $(".img_box").click(function(){
            if(count>1)
            {
            $('.img_box1').remove();
            count--;
            }
            $(this).clone().attr({ 'class': 'img_box' + count+' zoom' }).insertAfter(this);
            //$(this).toggleClass("zoom");
            count++;
            $(".img_box1").click(function(){
                $('.img_box1').remove();
                count--;       
                });
        });
    
    });