JSFiddle - React, Tailwind, and code Playground
by robert_schutt
HTML
<select id="items" onchange="doScroll(this.value)">
<option> - select item</option>
</select>
<button onclick="addItem()">add random item</button>
<div id="calendar" class="calendar">
<div id="bg" class="bg">
</div>
</div>
CSS
.calendar {
position: relative;
left: 100px;
top: 50px;
width: 600px;
height: 400px;
border: 1px solid red;
overflow: scroll;
}
.bg {
position: absolute;
left: 0px;
top: 0px;
width: 1500px;
height: 1500px;
background-color: #ffe;
}
.item {
position: absolute;
width: 150px;
height: 50px;
border: 1px solid green;
}
JavaScript
function addItem() {
var itms = document.getElementById('items');
var cal = document.getElementById('calendar');
var calbg = document.getElementById('bg');
var calbgstl = window.getComputedStyle(calbg);
var newitm = document.createElement('DIV');
newitm.id = 'item' + itms.length;
var itmtxt = 'item ' + itms.length;
newitm.appendChild(document.createTextNode(itmtxt));
newitm.className = 'item';
var x = Math.floor(Math.random() * (getNumProp(calbgstl, 'width') - 152));
var y = Math.floor(Math.random() * (getNumProp(calbgstl, 'height') - 52));
newitm.style.top = y + 'px';
newitm.style.left = x + 'px';
cal.appendChild(newitm);
itms.options.add(new Option(itmtxt, newitm.id));
}
function doScroll(itmid) { //alert(itmid);
var cal = document.getElementById('calendar');
var calstl = window.getComputedStyle(cal);
var itm = document.getElementById(itmid);
var itmstl = window.getComputedStyle(itm);
cal.scrollLeft = getNumProp(itmstl, 'left') - (getNumProp(calstl, 'width') - getNumProp(itmstl, 'width')) / 2;
cal.scrollTop = getNumProp(itmstl, 'top') - (getNumProp(calstl, 'height') - getNumProp(itmstl, 'height')) / 2;
}
function getNumProp(stl, prp) {
return Number(stl[prp].replace('px',''));
}