Reputation: 5860
I have two elements i.e. a canvas and a div as given below. I would like to know how I can find out if the div contains the canvas element (not in terms of DOM placement but in terms of position).
<canvas id="smallBall" style="position: relative; top: 52px; left: -89.0781px;"></canvas>
...
<div class="container">
<div id="hereIGo">The small ball is supposed to be contained in this DIV</div>
</div>
Is there a way I can achieve this using jQuery?
Upvotes: 3
Views: 1895
Reputation: 5648
One option is using getBoundingClientRect()
, which will retrieve the exact position of an element on the page, independent of any position relatives or absolutes. Then the comparison could be:
// Both of these are the results of calling getBoundingClientRect() on their respective elements.
var canvas;
var div;
if (div.top >= canvas.top &&
div.left >= canvas.top &&
div.right <= canvas.right &&
div.bottom <= canvas.bottom) {
//the div is inside the canvas.
}
You also have a jQuery option, which consists of calling $(selector).offset()
. This returns an object, with a similar interface to the one described above. This solution is as you can image more supported.
Upvotes: 3