sun
sun

Reputation: 1678

how to make a div left position according to another div?

I have div called first which width can be dynamic and horizontally centered according margin left right to auto

.first
{
    width:70%;
    background-color:#5b9a68;
    position:relative;
    margin:0 auto;
}

Another div second with position fixed

.second
{
    position:fixed;
    background-color:black;
    color:white;
    left:input;
}

Html

<div class="first">content</div>
<div class="second">Left Value</div>

i want this second div to position according to first div.The Problem here is second div position is fixed so it is positioning according to screen width so i tried this script to position it according to first div.

$(document).ready(function(){
    var input=0;

    var first_width = $(".first").width() / $('.first').parent().width() * 100;  
    var pos = (100-first_width)/2;//getting the empty part
    var ex_pos=pos+input;

    $('.second').css("left",ex_pos+"%");

});

Here when the input is zero it should start at the start of first div this is fine but when we changed the input value am not getting accurate percentage positioning according to first div.

Let say for example if i give 50 as input then i'll place it on 65 but this way am not perfectly positioning in 50 of first div.Also if i give 100% as input this will go outside.

How to do this if input is 100 then the second div should be at the end of first div. if the input is 50 it should be at middle of first like that.

Output With 0% left position

Output With 50% left position

Output With 100% left position

NOTE-I don't want to change or edit the css. i would like to do it in script alone. Check Fiddle

Upvotes: 2

Views: 1219

Answers (2)

Nikhil Patel
Nikhil Patel

Reputation: 1781

Here you go :

$(document).ready(function () {
    var input = 0,
        firstWidth = $('.first').width(),                    // width of first div
        secondWidth = $('.second').width(),                  // width of second div
        offset = (input * (firstWidth - secondWidth)) / 100, // % to shift
        leftPos = $('.first').offset().left;                 // left position of first div

    $('.second').css("left", leftPos + offset);
});

JSFiddle

From jQuery API Documentation : Link

The .offset() method allows us to retrieve the current position of an element relative to the document.
It returns an object containing the properties top and left.

So :

leftPos = $('.first').offset().left;

This gives us the left co-ordinates for the .first div i.e the point where it starts.

Upvotes: 4

The Dark Knight
The Dark Knight

Reputation: 5585

I guess, you are looking for scenarios for 50% and 100% .

This should do it :

JS :

if(input===100){
    ex_pos = ex_pos - 43;
}else if(input===50){
    ex_pos = ex_pos - 13;
}

FIDDLE

Upvotes: 0

Related Questions