JSFiddle - React, Tailwind, and code Playground

by javadoug

HTML

Reliably position elements on page when window zooms. Note: some elements may be positioned off screen. Steps: 1. mouse around to see - you may need to click in the result frame. 2. zoom the window and observe the results. 3. add scrolling into the mix

CSS

body {
    cursor: crosshair;
}
.fixed {
    position: fixed;
}
.absolute {
    position: absolute;
}
.relative {
    position: relative;
}
div {
    width: 20px;
    height: 20px;
    border: 1px solid red;
    background: silver;
    white-space: nowrap;
}
span {
    display: block;
    width: 200px;
    font-size: 8pt;
    font-family: sans-serif;
    border-width: 4px;
    border-style: solid;
}

JavaScript

function mouseCoordinates(jqe) {
    var result = {};
    for (var key in jqe) {
        if (jqe.hasOwnProperty(key)) {
            if (/X|Y/.test(key)) {
                result[key] = jqe[key];
            }
        }
    }
    return result;
}

function getRandomNumberBetween(min, max) {
    return parseInt(Math.random() * (max - min) + min, 10);
}

function getRandomColor() {
    var rgb = [];
    rgb.push(getRandomNumberBetween(0, 255));
    rgb.push(getRandomNumberBetween(0, 255));
    rgb.push(getRandomNumberBetween(0, 255));
    return 'rgb(' + rgb.join(', ') + ')';
}

function findOrCreate(id, cp) {
    var elem = $('#' + id);
    if (elem.length === 0) {
        elem = $('<div>').attr('id', id).addClass(cp).appendTo('body');
        $('<span>').attr('class', id).appendTo('body');
    }
    return elem;
}
var mouseCoords = ['screen', 'page', 'client']; //, 'offset'];
var cssPositions = ['fixed', 'absolute']; //, 'relative'];
function moveElements(coords, addColor) {
    var m, c, mc, cp, id, i = 2,
        elem, color;
    for (c = 0; c < cssPositions.length; c++) {
        cp = cssPositions[c];
        for (m = 0; m < mouseCoords.length; m++) {
            mc = mouseCoords[m];
            x = coords[mc + 'X'];
            y = coords[mc + 'Y'];
            id = cp + '-' + mc;
            msg = 'position: ' + cp + ', mouse: ' + mc + '(' + x + ', ' + y + ')';
            color = findOrCreate(id, cp).data('color') || getRandomColor();
            findOrCreate(id, cp).css({
                top: (y + (i += 2) - 20) + 'px',
                left: (x + (i) - 20) + 'px',
                    'border-color': color,
                    'background-color': color,
            }).data('color', color);
            $('.' + id).css({
                'border-color': color
            }).text(msg);
        }
    }
}
$(document).ready(function () {
    $('body').on('mousemove', function (jqe) {
        var coords = mouseCoordinates(jqe);
        // console.log(coords)
       ...