I have a tricky question: I have a fullsize background over the site I\'m working on. Now I want to attach a div to a certain position on the image and also that the div sc
Ok, so I tried to use your original idea, and modified only a few bits here and there.
Instead of using percentages, I found it easier to use pixel values. So:
$(this).css({
'margin-top': yPos + 'px',
'margin-left': xPos + 'px',
'width': xSize + 'px',
'height': ySize + 'px'
});
Then, all we have to do is check the proportion of the viewport to see how we have to modify the div's properties
if (windowAspectRatio > imageAspectRatio) {
var ratio = windowWidth / imageWidth;
} else {
var ratio = windowHeight / imageHeight;
}
xPos = xPos * ratio;
yPos = yPos * ratio;
xSize = xSize * ratio;
ySize = ySize * ratio;
Working example: http://codepen.io/jaimerodas/pen/RaGQVm
Stack snippet
var imageWidth = 1920,
imageHeight = 1368,
imageAspectRatio = imageWidth / imageHeight,
$window = $(window);
var hotSpots = [{
x: -210,
y: -150,
height: 250,
width: 120
}, {
x: 240,
y: 75,
height: 85,
width: 175
}];
function appendHotSpots() {
for (var i = 0; i < hotSpots.length; i++) {
var $hotSpot = $('').addClass('hot-spot');
$('.container').append($hotSpot);
}
positionHotSpots();
}
function positionHotSpots() {
var windowWidth = $window.width(),
windowHeight = $window.height(),
windowAspectRatio = windowWidth / windowHeight,
$hotSpot = $('.hot-spot');
$hotSpot.each(function(index) {
var cambio = 1,
xPos = hotSpots[index]['x'],
yPos = hotSpots[index]['y'],
xSize = hotSpots[index]['width'],
ySize = hotSpots[index]['height'],
desiredLeft = 0,
desiredTop = 0;
if (windowAspectRatio > imageAspectRatio) {
var ratio = windowWidth / imageWidth;
} else {
var ratio = windowHeight / imageHeight;
}
xPos = xPos * ratio;
yPos = yPos * ratio;
xSize = xSize * ratio;
ySize = ySize * ratio;
$(this).css({
'margin-top': yPos + 'px',
'margin-left': xPos + 'px',
'width': xSize + 'px',
'height': ySize + 'px'
});
});
}
appendHotSpots();
$(window).resize(positionHotSpots);
html, body {
margin: 0;
width: 100%;
height: 100%;
}
.container {
width: 100%;
height: 100%;
position: relative;
background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Alexanderplatz_Stadtmodell_1.jpg/1920px-Alexanderplatz_Stadtmodell_1.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
.hot-spot {
background-color: red;
border-radius: 0;
position: absolute;
top: 50%;
left: 50%;
z-index: 1;
opacity: 0.8;
content: "";
}