Francisco Romero
Francisco Romero

Reputation: 13189

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/[email protected]?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!

Upvotes: 0

Views: 62

Answers (2)

ZiNNED
ZiNNED

Reputation: 2650

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

Upvotes: 0

0x3a2d29
0x3a2d29

Reputation: 11

$("#left").promise().done(function(){
   $("#image").css({left: $("#image").position().left + 30});
});

Upvotes: 1

Related Questions