the12
the12

Reputation: 2415

Positioning element relative to another not working

I'm trying to position an element relative to another using the jQuery offset() method and I am trying to figure out why the $(window).resize function is not working.

JSBIN:http://jsbin.com/lanako/7/edit?html,js,output

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<style>


div{
display:inline-block;
position:relative;
height:200px;
width:200px;
border:solid black;    
}

#somepara{
border: solid blue;
position:relative;
left:20%;
}

</style>
<body>
  <div id ="first"> FIRST</div>

  <div id = 'somepara'>  </div>


</body>
</html>

JavaScript:

var p = $( "#somepara" );
var pf =  $('#first');
var offset = p.offset();
p.html( "left: " + offset.left);

function offcss(){
pf.css({'left': offset.left + 6 + "px"});
}

$(document).ready(function(){
  offcss();
    $(window).resize(function(){
        offcss();
    });


});

I am essentially grabbing the offset().left of the second element ('#somepara') and trying to set the css of ('#first') right 6 pixels from (#somepara).Note: (#somepara) is has a fluid measurement (%), so the left position changes.

The equation initially works, but I want to upon resizing the browser, for the equation pf.css(), which calculates the css left property of (#first) to execute. Unfortunately the $(window).resize function I have set is not working, and thus the left property of (#first) is unchanged. The end goal I want is regardless the browser size, the elements will be separated by 6 pixels (#first right 6 pixels from #somepara).

Any help would be greatly appreciated!

Upvotes: 0

Views: 52

Answers (1)

Dekel
Dekel

Reputation: 62556

The position of #somepara changes when you resize, so you need to take the value of p.offset() every time you call the offcss() function (and not only on first load).

function offcss() {
    pf.css({'left': p.offset().left + 6 + "px"});
}

Regarding the resize it seems like it does exactly what you want.

Check this example:
http://jsbin.com/dewazuyuqo/1/edit?html,js,output

Upvotes: 1

Related Questions