Reputation: 743
I'm attempting to position an image onto a larger image. So far I am doing this according to the padding left and padding top. More specifically, I am using the following method to get the padding left and padding top:
function getOffsetRect(elem) {
// (1)
var box = elem.getBoundingClientRect()
var body = document.body
var docElem = document.documentElement
// (2)
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
// (3)
var clientTop = docElem.clientTop || body.clientTop || 0
var clientLeft = docElem.clientLeft || body.clientLeft || 0
// (4)
var top = box.top + scrollTop - clientTop
var left = box.left + scrollLeft - clientLeft
return { top: Math.round(top), left: Math.round(left) }
}
This works fine. I am getting the exact position of the top left corner of my image and when I position a div on it, such as
$("#testDiv").css({top: element.top, left: element.left, position: 'absolute'});
it is positioned in the exact location. My problem is that when I use a larger monitor, or resize the window, then the larger image that im positioning the smaller image on becomes smaller or bigger and therefore, the original padding top and padding bottom of where the smaller images should be positioned becomes misleading. How could I adjust the position for different monitor sizes/window resizing to get it in the location it belongs?
Upvotes: 0
Views: 149
Reputation: 111
You'll need to call this method again (and then apply the new values to your top-level image's location) when the window is resized.
You can do this by adding an event listener (although you would want the second argument to be a method that calls getOffsetRect, then applies the returned value to your existing image):
window.addEventListener('resize', getOffsetRect(elem));
Upvotes: 0
Reputation: 17
This is easiest to do using CSS Media Queries. W3 Schools has a good page on them so that you can get a hang of them really easily. I'd recommend checking them out and responsive design will become a breeze.
Upvotes: 1