resize-detector
Version:
Element resize detection, both modern way and cross browser.
154 lines (134 loc) • 2.87 kB
HTML
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Resize Detector</title>
<style>
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
font-size: 12px;
color: #999;
}
#container {
width: 600px;
}
#pusher {
float: left;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
background: #eee;
cursor: pointer;
transition: width 2s, background-color .3s;
}
#pusher:hover {
width: 300px;
}
:checked + #pusher {
width: 400px;
background: #eec;
}
#el {
position: relative;
overflow: hidden;
height: 100px;
background: #9ca;
line-height: 100px;
text-align: center;
color: #fff;
font-weight: 700;
}
#wrapper {
width: 300px;
height: 200px;
transition: width .5s;
}
#wrapper.expanded {
width: 450px;
}
#r1,
#r2 {
width: 100%;
height: 100px;
}
#r1 {
background: #acc;
}
#r2 {
background: #cca;
}
#output {
white-space: pre-wrap;
}
.log {
display: inline-block;
padding: 2px 5px;
margin: 0 1px 1px 0;
background-color: #cce;
}
</style>
</head>
<body>
<p><label id="attach"><input type="checkbox" checked> Attached</button></label></p>
<p><label id="display"><input type="checkbox"><code>display: none</code></label></p>
<div id="container">
<input id="push" type="checkbox" style="display: none">
<label id="pusher" for="push">Hover or Click</label>
<div id="el">→ Resize Detector Enabled ←</div>
</div>
<section id="wrapper">
<div id="r1"></div>
<div id="r2"></div>
</section>
<pre id="output"></pre>
<script src="../dist/index.js"></script>
<script>
var el = document.getElementById('el')
var container = document.getElementById('container')
var attach = document.getElementById('attach')
var wrapper = document.getElementById('wrapper')
var r1 = document.getElementById('r1')
var r2 = document.getElementById('r2')
var display = document.getElementById('display')
var output = document.getElementById('output')
function log (msg) {
output.innerHTML += `<span class="log">${msg}</span>`
}
resizeDetector.addListener(el, function () {
log(el.offsetWidth + '×' + el.offsetHeight)
})
attach.addEventListener('change', function () {
var input = attach.firstElementChild
if (input.checked) {
container.appendChild(el)
} else {
container.removeChild(el)
}
})
display.addEventListener('change', function () {
var input = display.firstElementChild
if (input.checked) {
el.style.display = 'none'
} else {
el.style.display = ''
}
})
wrapper.addEventListener('click', function () {
wrapper.classList.toggle('expanded')
})
resizeDetector.addListener(r1, function () {
log('r1: resize')
})
resizeDetector.addListener(r2, function () {
log('r2: resize')
})
</script>
</body>
</html>