Error404 Error404 - 7 months ago 17
Javascript Question

How can I modify left property after hide an element using JQuery?

What I am trying to achieve it is to move an elemement (an image) with

left
property after I hide a div.

To do that, I use
.promise()
function of JQuery. Here is my code:

HTML code:

<div id="outerContainer">
<div id="left"></div>
<div id="container">
<div id="div1" class="square red"></div>
<div id="div2" class="square green">
<img id="image" src="http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&a">
</div>
<div id="div3" class="square blue"></div>
</div>
<div id="right"></div>
</div>


CSS code:

#outerContainer{
display: flex;
height: 100vh;
}

#left{
display: block;
width: 20%;
border: solid 1px;
border-color: #e0e0d1;
}

#container{
display: flex;
position: relative;
flex-flow: row wrap;
width: 100%;
flex: 2;
}

#right{
flex: 1;
padding: 20px;
width: 20%;
background-color: #354551;
}
.red{
background-color: red;
}

.green{
background-color: green;
}

.blue{
background-color: blue;
}

.square{
flex: 1 0 10%;
height: 50px;
}

#image{
position: absolute;
z-index: 1;
width:50px;
height:50px;
left: 30px;
}

#div2{
position: relative;
}


JQuery code:

$('#left').click(function() {
$(this).hide();
});

$("#left").promise().done(function(){
$("#image").css({left: "+=" + 30});
//$("#image").css({left: "+=" + 30 + "px"}); Same behaviour as before

});


JSFiddle in which you can prove it.

After removing the
left
element, I would like to move the image
30px
more to the right (so I will have to add pixels to the left) but I need to wait until the left element have been removed totally (it is the reason why I use
.promise()
function).

It seems that
.promise()
function it is blocking the browser because the
left
property never changes.

How can I modify left property of an element after that the element that I had removed have been hidden totally?

Thanks in advance!

Answer

Not sure if you insist on using the promise() function, but if not, you could also use a callback in the hide() function, which is called after hiding completes, like this:

$('#left').click(function() {
    $(this).hide(0, function()
    {
        $("#image").css({left: "+=" + 30}); 
    });
});

FIDDLE