Calculating distance between two elements in JQuery

Posted By : Deepak Rawat | 08-Dec-2014

Hi guys,

 

This blog is for finding the distance between two html elements using jquery. Using this blog you can find distance between elements and do whatever you want to do with that distance, for instance you can use it for animating between two elements without worrying how far those two elements are, this method find the distance for you.

 

Here we were using jquery’s .offset() method which returns the coordinates of the selected element relative to the document. This method returns the top and left coordinates of the element in pixel.

 

     $(selector).offset();       	//returns offset coordinates
 

 

Now to find the distance between two elements from top the code is like:

 

        var first = $(selector1).offset().top;  	//first element distance from top
        var second = $(selector2).offset().top;                 //second element distance from top
        var distance = parseInt(first) – parseInt(second);	//distance between elements

 

 

Now this “distance” contains the distance between “first” and “second” elements.

 

Note: Subtract bigger distance from smaller, if you don’t want to get the distance in negative value, also don’t forgot to parse the distance before manipulating it.

 

Thanks !

 

About Author

Author Image
Deepak Rawat

Deepak is a Web and Mobile application Sr. Lead Frontend developer and good working experience with JQuery , AngularJS , Javascript and PhoneGap. His hobbies are listening to music and photography.

Request for Proposal

Name is required

Comment is required

Sending message..