I have a code that works just fine to check if element is outside of bottom viewport, as follows:
function posY(elm) {
let test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
let de = document.documentElement;
if(!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible (elm) {
let vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
if (hasActivity && isHidden) {
isVisibleCSS = <div className='onscreen'>More activity below ↓</div>;
} else if (hasActivity && !isHidden) {
//technically, there's no need for this here, but since I'm paranoid, let's leave it here please.
}
My question is, how can I adapt this code or create a new one similar to this one that identifies when element is outside of top viewport?
Cheers.
For an element to be completely off the view top then the sum of the element's top offset and it's height, like in this JS Fiddle
var $test = document.getElementById('test'),
$tOffset = $test.offsetTop,
$tHeight = $test.clientHeight,
$winH = window.innerHeight,
$scrollY;
window.addEventListener('scroll', function() {
$scrollY = window.scrollY;
if ($scrollY > ($tOffset + $tHeight)) {
console.log('out of the top');
}
});
body {
margin: 0;
padding: 0;
padding-top: 200px;
height: 1500px;
}
#test {
width: 100px;
height: 150px;
background-color: orange;
margin: 0 auto;
}
<div id="test"></div>
Related
I have a large background image and some much smaller images for the user to drag around on the background. I need this to be efficient in terms of performance, so i'm trying to avoid libraries. I'm fine with drag 'n' drop if it work's well, but im trying to get drag.
Im pretty much trying to do this. But after 8 years there must be a cleaner way to do this right?
I currently have a drag 'n' drop system that almost works, but when i drop the smaller images, they are just a little off and it's very annoying. Is there a way to fix my code, or do i need to take a whole different approach?
This is my code so far:
var draggedPoint;
function dragStart(event) {
draggedPoint = event.target; // my global var
}
function drop(event) {
event.preventDefault();
let xDiff = draggedPoint.x - event.pageX;
let yDiff = draggedPoint.y - event.pageY;
let left = draggedPoint.style.marginLeft; // get margins
let top = draggedPoint.style.marginTop;
let leftNum = Number(left.substring(0, left.length - 2)); // cut off px from the end
let topNum = Number(top.substring(0, top.length - 2));
let newLeft = leftNum - xDiff + "px" // count new margins and put px back to the end
let newTop = topNum - yDiff + "px"
draggedPoint.style.marginLeft = newLeft;
draggedPoint.style.marginTop = newTop;
}
function allowDrop(event) {
event.preventDefault();
}
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.style.marginLeft = `${Math.floor(Math.random() * 900)}px`
sensor.style.marginTop = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = function() {
sensorClick(logs[i].id)
};
sensor.addEventListener("dragstart", dragStart, null);
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
<!-- my html: -->
<style>
.map {
width: 900px;
height: 500px;
align-content: center;
margin: 150px auto 150px auto;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
position: absolute;
width: 50px;
height: 50px;
}
</style>
<div class="map" onDrop="drop(event)" ondragover="allowDrop(event)">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false">
<div>
With the answers from here and some time i was able to get a smooth drag and click with pure js.
Here is a JSFiddle to see it in action.
let maxLeft;
let maxTop;
const minLeft = 0;
const minTop = 0;
let timeDelta;
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
var originalX;
var originalY;
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function sensorClick () {
if (Date.now() - timeDelta < 150) { // check that we didn't drag
createPopup(this);
}
}
// create a popup when we click
function createPopup(parent) {
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
let popup = document.createElement("div");
popup.id = "popup";
popup.className = "popup";
popup.style.top = parent.y - 110 + "px";
popup.style.left = parent.x - 75 + "px";
let text = document.createElement("span");
text.textContent = parent.id;
popup.appendChild(text);
var map = document.getElementsByClassName("map")[0];
map.appendChild(popup);
}
// when our base is loaded
function baseOnLoad() {
var map = document.getElementsByClassName("map")[0];
let base = document.getElementsByClassName("base")[0];
maxLeft = base.width - 50;
maxTop = base.height - 50;
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.id = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.classList.add("dragme");
sensor.style.left = `${Math.floor(Math.random() * 900)}px`
sensor.style.top = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = sensorClick;
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
}
function startDrag(e) {
timeDelta = Date.now(); // get current millis
// determine event object
if (!e) var e = window.event;
// prevent default event
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
originalX = targ.style.left;
originalY = targ.style.top;
// check that this is a draggable element
if (!targ.classList.contains('dragme')) return;
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// calculate integer values for top and left properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
document.onmousemove = dragDiv; // move div element
return false; // prevent default event
}
function dragDiv(e) {
if (!drag) return;
if (!e) var e = window.event;
// move div element and check for borders
let newLeft = coordX + e.clientX - offsetX;
if (newLeft < maxLeft && newLeft > minLeft) targ.style.left = newLeft + 'px'
let newTop = coordY + e.clientY - offsetY;
if (newTop < maxTop && newTop > minTop) targ.style.top = newTop + 'px'
return false; // prevent default event
}
function stopDrag() {
if (typeof drag == "undefined") return;
if (drag) {
if (Date.now() - timeDelta > 150) { // we dragged
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
} else {
targ.style.left = originalX;
targ.style.top = originalY;
}
}
drag = false;
}
.map {
width: 900px;
height: 500px;
margin: 50px
position: relative;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
}
.dragme {
cursor: move;
left: 0px;
top: 0px;
}
.popup {
position: absolute;
display: inline-block;
width: 200px;
height: 100px;
background-color: #9FC990;
border-radius: 10%;
}
.popup::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: #9FC990 transparent transparent transparent;
}
.popup span {
width: 90%;
margin: 10px;
display: inline-block;
text-align: center;
}
<div class="map" width="950px" height="500px">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false" onload="baseOnLoad()">
<div>
based on this this tutorial on w3 schools I wrote a function(move) that animates an element(div) using the setInterval() method, my problem is when I try to call the function move() several times the div does an unexpected behavior, I tried to use async/await but it didn't work.
async function moveArray(destination) {
//move through array of addresses
for (let i = 0; i < destination.length - 1; i++) {
await move(destination[i], destination[i + 1]);
}
}
async function move(pos, add) {
//moves element from position to address
var elem = document.getElementById("object");
var id = setInterval(frame, 15);
function frame() {
if (pos.x == add.x && pos.y == add.y) {
clearInterval(id);
return;
} else {
//if element haven't reached its target
// we add/substract 1 from the address and update styling
if (pos.x != add.x) {
pos.x += add.x > pos.x ? 1 : -1;
elem.style.left = pos.x + "px";
}
if (pos.y != add.y) {
pos.y += add.y > pos.y ? 1 : -1;
elem.style.top = pos.y + "px";
}
}
}
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#object {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
<button onclick="moveArray( [{x:0,y:0}, {x:140, y:150}, {x:130, y:110}, {x:70, y:65}] )">
move
</button>
<div id="container">
<div id="object"></div>
//object to be animated
</div>
The weird behavior is caused because the move function is being called multiple times simultaneously in the for loop. This happens because your async functions do not know when they are done.
Instead of making move async, which it doesn't have to if it is not awaiting anything, return a Promise from the start and call you animation code inside of it. When the point is reached when animation has to end, resolve the promise.
Doing it like this will make your await statement in the for loop wait for the move function to reach the resolve call before continuing with the next animation.
async function moveArray(destination) {
//move through array of addresses
for (let i = 0; i < destination.length - 1; i++) {
await move(destination[i], destination[i + 1]);
}
}
function move(pos, add) {
return new Promise(resolve => {
var elem = document.getElementById("object");
var id = setInterval(frame, 15);
function frame() {
if (pos.x == add.x && pos.y == add.y) {
clearInterval(id);
// Fulfill promise when position is reached.
resolve();
} else {
if (pos.x != add.x) {
pos.x += add.x > pos.x ? 1 : -1;
elem.style.left = pos.x + "px";
}
if (pos.y != add.y) {
pos.y += add.y > pos.y ? 1 : -1;
elem.style.top = pos.y + "px";
}
}
}
});
}
<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#object {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
</head>
<body>
<button onclick="moveArray( [{x:0,y:0}, {x:140, y:150}, {x:130, y:110}, {x:70, y:65}] )">
move
</button>
<div id="container">
<div id="object"></div>
//object to be animated
</div>
<script src="animation.js"></script>
</body>
</html>
I'm trying to change the color of a fixed element (.logo) when scrolling on top of a dark image (.image). I came across this solution:
Detect when static element overlaps fixed element position on scroll
Which only works for a single image. But what if I want to change the color of the fixed element when scrolling passed all the images with the image class by using querySelectorAll?
I tried to solve this with a forEach but the fixed element only changes color on the last image. Can somebody explain this behaviour, in my mind this should work?
https://codepen.io/bosbode/pen/GaJNKr
HTML
<p class="logo">Logo</p>
<div class="image"></div>
<div class="image"></div>
CSS
body {
text-align: center;
height: 100%;
font-size: 1.5rem;
}
.image {
width: 800px;
height: 600px;
background: blue;
margin: 100px auto;
}
.logo {
position: fixed;
top: 0;
left: 50%;
transform: translate(-50%, 0)
}
JavaScript
const logo = document.querySelector('.logo');
const images = document.querySelectorAll('.image');
window.addEventListener('scroll', function () {
const a = logo.getBoundingClientRect();
images.forEach((item, index) => {
const b = item.getBoundingClientRect();
if (a.top <= (b.top + b.height) && (a.top + a.height) > b.top) {
logo.style.color = 'white';
} else {
logo.style.color = 'black';
}
})
});
for (var i = 0; i < images.length; i++) {
var item = images[i]
let b = item.getBoundingClientRect();
if (a.top <= (b.top + b.height) && (a.top + a.height) > b.top) {
logo.style.color = 'white';
break;
} else {
logo.style.color = 'black';
}
};
Updated content:
1. For this solution, I need using break statement in loop, so I am using for instead of foreach
2. We need break if logo is inside in every image.
WHY?:
If logo is inside image1, then its' color can be white, but next step, its' color can be black, because logo is not inside image2.
Below code is more readable for this solution:
const logo = document.querySelector('.logo');
const images = document.querySelectorAll('.image');
function isInsideInImages(images, logoPos) {
for (var i = 0; i < images.length; i++) {
let imagePos = images[i].getBoundingClientRect();
if (logoPos.top <= (imagePos.top + imagePos.height) && (logoPos.top + logoPos.height) > imagePos.top) {
return true;
}
};
return false;
}
window.addEventListener('scroll', function () {
const a = logo.getBoundingClientRect();
if (isInsideInImages(images, a)) {
logo.style.color = 'white';
} else {
logo.style.color = 'black';
}
});
So, I have an event listener keydown on arrow right, when you push the square moving on xPX but my parent element this w and h
set a 100px for example, and I would like to stop moving and I can't, I try with element.offsetWidth > 0 so them you can move.
Please look this fiddle : FIDDLE
Few errors in your code. I've commented fixes. Here is how i made it for the right arrow - you can apply same logic to the rest of the moves...
Code:
const carre = document.querySelector('.carre');
const main = document.querySelector('.main');
const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code
carre.style.left="0px"; // set start position
document.addEventListener('keyup', (event) => {
const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)
if(event.keyCode == '39') {
if (positionLeft < w) { // this was fixed too
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
})
DEmo:
const carre = document.querySelector('.carre');
const main = document.querySelector('.main');
const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code
carre.style.left="0px"; // set start position
document.addEventListener('keyup', (event) => {
const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)
if(event.keyCode == '39') {
if (positionLeft < w) { // this was fixed too
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
})
* {
box-sizing:border-box;
}
.carre {
position:absolute;
left: 0;
width: 50px;
height: 50px;
background-color: red;
}
.main {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #000;
}
<main class="main">
<div class="carre"></div>
</main>
I rebuild your code:
document.addEventListener('keydown', (event) => {
const w = main.getBoundingClientRect().right - carre.getBoundingClientRect().right;
const positionLeft = carre.getBoundingClientRect().left;
if(event.keyCode == '39') {
if (w >= 0) {
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
if (event.keyCode == '37') {
if (w >= 0) {
carre.style.left = (positionLeft) - 10 + 'px';
}else {
carre.style.left = '0'
}
}
})
I've been trying to use a function to detect if an element is in the viewport:
function isElementInViewport (el) {
var rect = el[0].getBoundingClientRect();
return (rect.top>-1 && rect.bottom <= $(window).height());
}
var s= $('.special'),
y = $('.status');
$(window).on('scroll resize', function(){
if(isElementInViewport(s))
{
setTimeout(function(){
if(isElementInViewport(s))
{
var offer_id = s.data("offer-id");
alert(offer_id);
y.text('Yes');
}
}, 3000);
}
else
{
y.text('No');
}
});
Unfortunately this only seems to work for the first instance of the class 'special'. How do I get it to apply to all instances of that class?
Note that I've added a 3 second delay, to prevent fast scrolling from triggering it.
Here's the jsfiddle of my progress: http://jsfiddle.net/azjbrork/6/
using jquery each we can run the function on each instance of the .special class and report back accordingly (snippet below) :
function isElementInViewport(el) {
var rect = el[0].getBoundingClientRect();
return (rect.top > -1 && rect.bottom <= $(window).height());
}
var s = $('.special'),
y = $('.status');
$(window).on('scroll resize', function() {
s.each(function() {
var $this = $(this);
if (isElementInViewport($this)) {
setTimeout(function() {
if (isElementInViewport($this)) {
var offer_id = $this.data("offer_id");
// advise using an underscore instead of a hyphen in data attributes
// alert(offer_id); // reported in text below
y.text('Yes : ' + offer_id);
}
}, 200);
} else {
// y.text('No'); // omit this line otherwise it will always report no (subsequent out of screen divs will overwrite the response)
}
});
});
.special {
width: 80px;
height: 20px;
border: 1px solid #f90;
margin-top: 200px;
}
.status {
position: fixed;
right: 2em;
top: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='special' data-offer_id='a'></div>
<div class='special' data-offer_id='b'></div>
<div class='special' data-offer_id='c'></div>
<div class='special' data-offer_id='d'></div>
<div class='special' data-offer_id='e'></div>
<div class='special' data-offer_id='f'></div>
<div class='status'></div>