Search code examples
jqueryjustify

how to keep alignment while moving elements


$('.box').on('click', function(){
$('.act').removeClass('act');
$(this).addClass('act');
});

$('button').on('click', function(){
$('.act').insertAfter($('.act').next());
});
.parent{
text-align:justify;
text-align-last:justify;
background:lightgreen;
}

.box{
display:inline-block;
width:20%;
height:25px;
background:orange;
}

.act{
background:skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
<div class='box'>1</div>
<div class='box'>1</div>
<div class='box'>1</div>
<div class='box'>1</div>
</div>
<br>
<button>CLICK</button>

Click on the first box to make it active.

Then click on the button to move it right.

You see that alignment is lost, i.e. there is no spaces between boxes.

How to prevent this?


Solution

  • Instead of using insertAfterafter, which will mess up the justify style, just switch the location between the divs:

    $('.box').on('click', function(){
    $('.act').removeClass('act');
    $(this).addClass('act');
    });
    
    $('button').on('click', function(){
    
        div1 = $('.act');
        div2 = $('.act').next();
    
        tdiv1 = div1.clone();
        tdiv2 = div2.clone();
    
        if(!div2.is(':empty')){
            div1.replaceWith(tdiv2);
            div2.replaceWith(tdiv1);
    
            $('.box').on('click', function(){
                $('.act').removeClass('act');
                $(this).addClass('act');
            });
        }
    //   $('.act').insertAfter($('.act').next());
    });
    .parent{
    text-align:justify;
    text-align-last:justify;
    background:lightgreen;
    }
    
    .box{
    display:inline-block;
    width:20%;
    height:25px;
    background:orange;
    }
    
    .act{
    background:skyblue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class='parent'>
    <div class='box'>1</div>
    <div class='box'>2</div>
    <div class='box'>3</div>
    <div class='box'>4</div>
    </div>
    <br>
    <button>CLICK</button>