Brett
Brett

Reputation: 20049

Find out how many pixels between the start of two elements?

Consider the following HTML:

<div id="members" class="main">     
    <section class="top">
        <!-- Other Content -->
    </section>
    <section class="listing">
        <div class="holder container">
            <div class="row">
                <div class="members-main col-sm-12">
                    <div class="members-head row">

                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

Is there a way in JavaScript or jQuery that I can find out the amount of pixels between the start of the #members element and the start of the .members-head element?

Upvotes: 4

Views: 1039

Answers (3)

George Irimiciuc
George Irimiciuc

Reputation: 4633

Try

$('.members-head').offset().top - $('#members').offset().top

Jquery offset

If you have multiple .members-head elements inside the #members one (as I suspect), you could try $('.members-head:first'), or loop through them with .each and do $(this).offset().top - $('#members').offset().top

Upvotes: 1

rrk
rrk

Reputation: 15846

offset().top gives you the top position of elements.

var distance = $('.members-head').offset().top - $('#members').offset().top;

alert("Distance is : " + distance)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="members" class="main">     
    <section class="top">
        Other Content 
    </section>
    <section class="listing">
        <div class="holder container">
            <div class="row">
                <div class="members-main col-sm-12">
                    <div class="members-head row">
                        fdgfdgfdgdfgdfs
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

Upvotes: 2

Andi AR
Andi AR

Reputation: 2908

try this you will get.

$('#members').offset().top - $('.members-head').offset().top

Upvotes: 1

Related Questions