Float fixed element over cover background
Make element scale with background and position over background
by AsciiSmoke
HTML
<div id="pointer"></div>
CSS
body {
background: url(http://cdn.home-designing.com/wp-content/uploads/2016/05/Luxury-Apartment-Recontruction-Ultra-Modern.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
padding: 0;
margin: 0;
}
#pointer {
background-color: rgba(255, 0, 0, 0.5);
position: fixed;
box-sizing: border-box;
padding-top: 8vh;
font-family: sans-serif;
font-weight: bold;
font-size: 3vh;
text-align: center;
color: white;
}
JavaScript
window.onload = function() {
// var image = { width: 2000, height: 1125 };
// var target = { x: 740, y: 280 };
var floater = $('#pointer');
$(document).ready(updatePointer);
$(window).resize(updatePointer);
function updatePointer() {
var winWidth = $(window).innerWidth();
var winHeight = $(window).innerHeight();
var winRatio = winWidth / winHeight;
// Size of bg image (before scaling, used to get ratio)
var bgBaseWidth = 1150;
var bgBaseHeight = 766;
var bgBaseRatio = bgBaseWidth / bgBaseHeight;
// Size of floating element when bg image is at 100%
var floatBaseWidth = 240;
var floatBaseHeight = 140;
// Offset multiplier from center of the screen
var floatBaseOffsetX = -160;
var floatBaseOffsetY = -3;
// Work out if the bg image is filling the available width or height (based on how 'cover' works)
var fillingByHeight = bgBaseRatio > winRatio;
// Get work out how much the background has been scaled
var currentWidthRatio = winWidth / bgBaseWidth;
var currentHeightRatio = winHeight / bgBaseHeight;
scaleMultiplier1 = (fillingByHeight) ? currentHeightRatio : currentWidthRatio;
// Set up dimensions and coordinates to place the floater in the center of the screen
var floatWidth = (floatBaseWidth * scaleMultiplier1);
var floatHeight = (floatBaseHeight * scaleMultiplier1);
var floatCenterX = (winWidth / 2) - (floatWidth / 2);
var floatCenterY = (winHeight / 2) - (floatHeight / 2);
// Lastly, calculate the offset from the screen center to the desired location
var floatOffsetX = floatCenterX - (scaleMultiplier1 * floatBaseOffsetX);
var floatOffsetY = floatCenterY - (scaleMultiplier1 * floatBaseOffsetY);
// Set the css on the element
floater.css({
'left':...