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 !
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.