Find out how many pixels are between the beginning 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 JavaScriptor jQuerythat I can find out the number of pixels between the start of an element #membersand the start of an element .members-head?

+4
source share
3 answers

Try

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

Jquery offset

If you have several elements .members-headinside #members(as I suspect), you can try $('.members-head:first')or skip them through .each and$(this).offset().top - $('#members').offset().top

+1
source

offset().top gives you the top position of the 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>
Run codeHide result
+2
source

try it you get.

$('#members').offset().top - $('.members-head').offset().top
+1
source

Source: https://habr.com/ru/post/1608187/


All Articles