pointing arrow
by RAX7
HTML
<div class="block1">
block1
</div>
<div class="block2">
block with arrow
<svg id="arrow" width="100" height="50" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50">
<line x1="86" y1="25" y2="25" fill="none" stroke="#000" stroke-width="10"/>
<polyline points="71.3 46.3 92.6 25 71.3 3.7" fill="none" stroke="#000" stroke-width="10"/>
</svg>
</div>
<div id="fixed" class="button"></div>
CSS
body {
margin: 0;
padding: 0;
}
.block1 {
margin-top: 50vh;
height: 300px;
width: 100%;
background: green;
}
.block2 {
position: relative;
height: 300px;
width: 100%;
background: lightblue;
margin-bottom: 500px;
}
.block2 svg {
position: absolute;
bottom: -40px;
left: 50%;
}
.button {
width: 50px;
height: 50px;
position: fixed;
right: 5%;
bottom: 10%;
border-radius: 100%;
background: red;
}
.hidden {
visibility: hidden;
}
JavaScript
const arrowEl = document.querySelector('#arrow');
const fixedEl = document.querySelector('#fixed');
let arrowRect = null;
let fixedRect = fixedEl.getBoundingClientRect();
function updateArrow() {
arrowRect = arrowEl.getBoundingClientRect();
if (arrowRect.y > fixedRect.y) {
arrowEl.classList.remove('hidden');
}
else {
arrowEl.classList.add('hidden');
return;
}
const dx = (fixedRect.x + fixedRect.width / 2) - (arrowRect.x + arrowRect.width / 2);
const dy = (fixedRect.y + fixedRect.height / 2) - (arrowRect.y + arrowRect.height / 2);
const angle = Math.atan2(dy, dx);
arrowEl.style.transform = `rotate(${angle}rad)`;
}
window.addEventListener('scroll', updateArrow);
window.addEventListener('resize', () => {
fixedRect = fixedEl.getBoundingClientRect();
updateArrow();
});