Huseyin
Huseyin

Reputation: 1527

Div coordinates change when Jquery show function be used

I have two divs that clicking to first dive cause toggle of second div.

#a{ border:1px solid red;width:400px;margin:50px;}
#b{position:absolute;border:1px green solid; width:400px;top:150px;}

and

<div id="a">AAAAAAAAAAAA</div><div id="b">BBBBBB</div><div id="test" >Write Cordinates here</div>
$("#a").click(function(){
    var burasi = $(this).offset();
    var tepe=burasi.top + $(this).outerHeight(true);
    var ici = $("#b");
    ici.offset({top: tepe, left: burasi.left}); 
    window.console.log({top: tepe, left: burasi.left} );
    $("#test").html("top: "+tepe+", left: "+burasi.left);
    ici.fadeToggle("slow");       
})

As here. When A would be clicked toggle is executed so good but when div B going to shown its coordinates be changed. How can I prevent it and make div B at same place?

Upvotes: 1

Views: 85

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

Read This http://gabrieleromanato.name/jquery-bug-with-offsets-positioning-and-hidden-elements/


you can avoid that by run toggle before offset

$("#a").click(function(){
  var burasi = $(this).offset();
  var tepe=burasi.top + $(this).outerHeight(true);
  var ici = $("#b");
  ici.fadeToggle("slow");
  ici.offset({top: tepe, left: burasi.left}); 
  $("#test").html("top: "+tepe+", left: "+burasi.left);   
});

See DEMO

Upvotes: 0

You can just remove ici.offset({top: tepe, left: burasi.left}); as that's the line that's changing positions. Position your element when the document's ready and then it won't move at all. The reason why it's moving when you use your actual code is because you're trying to set the offset of a hidden element. Check out this answer here in StackOverflow which talks about it: jquery: get the offset of hidden element

As I mention, though, I used $(document).ready() to fix it. Here's my code:

    $("#a").click(function(){
    var burasi = $(this).offset();
    var tepe=burasi.top + $(this).outerHeight(true);
    var ici = $("#b");
    ici.offset({top: tepe, left: burasi.left}); 
    window.console.log({top: tepe, left: burasi.left} );
    $("#test").html("top: "+tepe+", left: "+burasi.left);
    ici.fadeToggle("slow");

});

Feel free to check it working here: http://jsfiddle.net/lrojas94/7hLypdnr/2/

Upvotes: 1

Related Questions