CSS 360 rotating progress radial using JS - javascript

var ele = document.getElementById("filler");
var deg = 0;
var myInterval = setInterval(function() {
deg = deg + 10;
if (deg > 360) {
clearInterval(myInterval);
}
ele.style.transform = `rotate(${deg}deg)`;
}, 500);
.filler-wrapper {
height: 100px;
width: 100px;
position: relative;
border-radius: 50%;
overflow: hidden;
background: linear-gradient(to left, red 50%, green 50%);
}
.filler {
border-radius: 0 100% 100% 0 / 50%;
display: block;
height: 100%;
margin-left: 50%;
transform-origin: left;
background: green;
transform: rotate(0deg)
}
<div class="filler-wrapper">
<div id="filler" class="filler"></div>
</div>
I have created this radial progress but this works for only 180. How can I make it to rotate 360 deg.

Here is an idea based on this previous answer where you can do this with only background:
var ele = document.getElementById("box");
var deg = -90;
var s = 1;
var myInterval = setInterval(function() {
if(deg >= 90 && s) {
ele.style.setProperty("--s", --s);
deg = -90;
}
deg = deg + 10;
ele.style.setProperty("--v", deg+'deg');
if(deg >= 90 && !s) {
clearInterval(myInterval);
}
}, 500);
#box {
width:100px;
height:100px;
border-radius:50%;
background:
linear-gradient(var(--v), green 50%,transparent 0) center/calc(var(--s)*100%),
linear-gradient(var(--v), red 50%, transparent 0) center/calc(100% - var(--s)*100%),
linear-gradient(to right, green 50%,red 0);
}
<div id="box" style="--v:-90eg;--s:1"></div>
<!-- first cycle : from -90deg to 90deg with s=1 -->
<!-- second cycle : from -90deg to 90deg with s=0 -->
Shortly this will be something trivial with conic-gradient():
var ele = document.getElementById("box");
var deg = 0;
var myInterval = setInterval(function() {
deg = deg + 10;
ele.style.setProperty("--v", deg+'deg');
if(deg >= 360 ) {
clearInterval(myInterval);
}
}, 500);
#box {
width:100px;
height:100px;
border-radius:50%;
background:
conic-gradient(red var(--v,0deg),green var(--v,0deg),green 360deg);
}
<div id="box" ></div>
The above should work only on Chrome

For JS
isCompleted = false;
progressCount = 10;
function updateProgress() {
progressCount = progressCount + 10;
const _count = progressCount * 1.8;
console.log(_count)
if (_count > 180) {
isCompleted = true;
}
if (this.isCompleted) {
return;
}
_rotateSpinner(_count);
}
var elCircleFullFill = document.getElementById("circleFullFill");
var elCircleHalfFill = document.getElementById("circleHalfFill");
var elCircleMaskFull = document.getElementById("circleMaskFull");
var elCircleFillFix = document.getElementById("circleFillFix");
function _rotateSpinner(__progressCount) {
const fillRotation = __progressCount;
const fixRotation = __progressCount * 2;
elCircleFullFill.style = `transform:rotate(${fillRotation}deg)`;
elCircleHalfFill.style = `transform:rotate(${fillRotation}deg)`;
elCircleMaskFull.style = `transform:rotate(${fillRotation}deg)`;
elCircleFillFix.style = `transform:rotate(${fixRotation}deg)`;
}
SCSS
.progress-radial {
width: 50px;
height: 50px;
background-color: #fff;
border-radius: 50%;
.circle {
.circle-mask,
.circle-fill {
width: 50px;
height: 50px;
position: absolute;
border-radius: 50%;
transition: -webkit-transform 1s;
transition: -ms-transform 1s;
transition: transform 1s;
-webkit-backface-visibility: hidden;
}
.circle-mask {
clip: rect(0px, 50px, 50px, 50px/2);
.circle-fill {
clip: rect(0px, 50px/2, 50px, 0px);
background-color: #0096FF;
}
}
}
}
HTML
<div class="progress-radial">
<div class="circle">
<div class="circle-mask" id="circleMaskFull">
<div class="circle-fill" id="circleFullFill"></div>
</div>
<div class="circle-mask">
<div class="circle-fill" id="circleHalfFill"></div>
<div class="circle-fill" id="circleFillFix"></div>
</div>
</div>
</div>
<button onclick="updateProgress()">Update Spinner</button>

Related

In my code there is an event listener for running every animation iteration but it keep getting the error reading properties of null. Can I fix it?

I am trying to make a traffic game using javascript though every time I try to use this line of code:
carAnimation.addEventListener('animationiteration', () => {
var random = Math.floor(Math.random() * 5);
left = random * 90 + 15;
carAnimation.style.left = left + "px";
counter++;
console.log(counter)
});
I am getting the error
Uncaught TypeError: Cannot read properties of null (reading
'addEventListener')
at HTMLButtonElement. (script.js:40:18)
but I can't seem to find the error in the line. Also, I am trying to run the same code for 3 different elements but it just doesn't seem to work either.
Here is the rest of the code if needed to solve this mystery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="game">
<div class="car"></div>
<div class="npcCar"></div>
<div class="npcCar npcCar2"></div>
<div class="npcCar npcCar3"></div>
</div>
<button class="start">Start!</button>
<div class="controlContainer">
<button class="btn pause"></button>
<button class="btn play"></button>
<button class="btn restart"></button>
<button class="btn help"></button>
</div>
<div class="helpModal hidd">
<div class="modal hidden">
<button class="close-modal">×</button>
<h1>Help</h1>
<p>
HOW TO PLAY:
Use WASD to the arrow keys to move the red car around.
You need to avoid hitting the blue cars.
When you hit a car you will automatically lose
The longer you last the more points you get
Good luck racer!
</p>
</div>
</div>
<style>
#import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap');
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
display: flex;
min-height: 100vh;
width: 100%;
background-color: rgb(69, 169, 240);
font-family: 'Oswald', sans-serif;
}
.game{
position: absolute;
left: calc(50% - 450px/2);;
height: 600px;
width: 450px;
border: 3px solid black;
border-radius: 5%;
background: url('road.png');
overflow: hidden;
}
.start{
position: absolute;
height: 30px;
width: 150px;
background-color: rgb(1, 255, 1);
border: 3px solid black;
border-radius: 5%;
font-size: 15px;
font-weight: bold;
top: 600px;
left : calc(50% - 150px/2);
transition: 0.5s;
}
.start:hover{
background: red;
}
.controlContainer{
padding: 5px;
width: 120px;
height: 120px;
border: 3px solid black;
border-radius: 5%;
background-color: lawngreen;
}
.btn{
height: 50px;
width: 50px;
border: 2px solid black;
border-radius: 50%;
}
.play{
background-image: url('play.png');
}
.pause{
background-image: url('pause.png');
}
.help{
background-image: url('help.png');
}
.restart{
background-image: url('restart.png');
}
.animate{
animation: road linear infinite 0.5s;
}
.hidden{
display: none;
}
#keyframes road{
0%{
background-position-y: 0px;
}
100%{
background-position-y: 600px;
}
}
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 45%;
background-color: white;
padding: 6rem;
border-radius: 5px;
box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.3);
z-index: 100000000;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 5rem;
color: #333;
cursor: pointer;
border: none;
background: none;
}
.car{
position: relative;;
height: 120px;
width: 60px;
border-radius: 5%;
top: 435px;
background: url('Player (1).png');
transform: rotate(180deg);
z-index: 100000;
}
.npcCar{
width: 60px;
height: 120px;
background: url('obsacle.png');
position: relative;
left: 15px;
top: -300px;
}
.npcCar2{
top: -420px;
left: 195px;;
}
.npcCar3{
top: -540px;
left: 375px
}
.carAnimate{
animation: vroom 0.8s linear infinite;
}
.carAnimate2{
animation: vroom 0.8s linear infinite;
}
.carAnimate3{
animation: vroom 0.8s linear infinite;
}
#keyframes vroom{
0%{
top: -120px;
}
100%{
top: 600px;
}
}
</style>
<script>
'use strict'
const startBtn = document.querySelector('.start')
const pauseBtn = document.querySelector('.pause')
const playBtn = document.querySelector('.play')
const restartBtn = document.querySelector('.restart')
const helpBtn = document.querySelector('.help')
const modal = document.querySelector('.modal');
const closeModal = document.querySelector('.close-modal');
const game = document.querySelector('.game');
const player = document.querySelector('.car');
const npcPlayer = document.querySelector('.npcCar');
const npcPlayer2 = document.querySelector('.npcCar2');
const npcPlayer3 = document.querySelector('.npcCar3');
const carAnimation = document.querySelector('.carAnimate');
const carAnimation2 = document.querySelector('.carAnimate2');
const carAnimation3 = document.querySelector('.carAnimate3');
let click = 0;
let interval;
let both = 0;
let counter = 0;
//onLoad
window.addEventListener("load", () => {
player.style.position = "relative";
player.style.left = '195px';
player.style.top = '485px';
});
// Start the Game
startBtn.addEventListener('click', function(){
console.log('button clicked');
game.classList.add('animate');
click+=2;
npcPlayer.classList.add('carAnimate')
npcPlayer2.classList.add('carAnimate2')
npcPlayer3.classList.add('carAnimate3')
carAnimation.addEventListener('animationiteration', () => {
var random = Math.floor(Math.random() * 5);
left = random * 90 + 15;
carAnimation.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation2.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation2.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation3.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation3.style.left = left + "px";
counter++;
});
});
//Pausing the Game
pauseBtn.addEventListener('click', function(){
console.log('button clicked');
if(click>1){
game.classList.remove('animate');
click--
}
console.log(click)
});
//Resuming the Game
playBtn.addEventListener('click', function(){
console.log('button clicked');
if(click===1){
game.classList.add('animate');
click++;
console.log(click);
}
});
//Opening the Help Model
helpBtn.addEventListener('click', function(){
console.log('modal clicked')
modal.classList.remove('hidden')
});
//closing the help modal
closeModal.addEventListener('click', function(){
console.log('button clicked')
modal.classList.add('hidden')
});
//Moving Functions
function moveLeft() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
var transform = parseInt(window.getComputedStyle(player).getPropertyValue("transform"));
if (left > -0) {
player.style.left = left - 2 + "px";
player.style.transform = 'rotate(-' + 215 + 'deg)'
}
}
function moveRight() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
if (left < 385) {
player.style.left = left + 2 + "px";
player.style.transform = 'rotate(' + 215 + 'deg)'
}
}
function moveUp() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top > 0) {
player.style.top = top - 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
function moveDown() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top < 490) {
player.style.top = top + 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
//Make the pLayer move
document.addEventListener("keydown", (event) => {
if (both == 0) {
both++;
if (event.key === "ArrowLeft") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "ArrowRight") {
interval = setInterval(moveRight, 1);
}
if (event.key === "ArrowUp") {
interval = setInterval(moveUp, 1);
}
if (event.key === "ArrowDown") {
interval = setInterval(moveDown, 1);
}
if (event.key === "a") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "d") {
interval = setInterval(moveRight, 1);
}
if (event.key === "w") {
interval = setInterval(moveUp, 1);
}
if (event.key === "s") {
interval = setInterval(moveDown, 1);
}
}
});
document.addEventListener("keyup", (event) => {
clearInterval(interval);
both = 0;
player.style.transform = 'rotate(' + 180 + 'deg)'
});
</script>
</body>
</html>
Thanks!
Try wrapping all of your code inside the below document-content-ready function
document.addEventListener("DOMContentLoaded", () => {
//your entire js code here
});
make sure your code will run after the document's load is complete. you can do that by checking readyState like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="game">
<div class="car"></div>
<div class="npcCar"></div>
<div class="npcCar npcCar2"></div>
<div class="npcCar npcCar3"></div>
</div>
<button class="start">Start!</button>
<div class="controlContainer">
<button class="btn pause"></button>
<button class="btn play"></button>
<button class="btn restart"></button>
<button class="btn help"></button>
</div>
<div class="helpModal hidd">
<div class="modal hidden">
<button class="close-modal">×</button>
<h1>Help</h1>
<p>
HOW TO PLAY:
Use WASD to the arrow keys to move the red car around.
You need to avoid hitting the blue cars.
When you hit a car you will automatically lose
The longer you last the more points you get
Good luck racer!
</p>
</div>
</div>
<style>
#import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap');
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
display: flex;
min-height: 100vh;
width: 100%;
background-color: rgb(69, 169, 240);
font-family: 'Oswald', sans-serif;
}
.game{
position: absolute;
left: calc(50% - 450px/2);;
height: 600px;
width: 450px;
border: 3px solid black;
border-radius: 5%;
background: url('road.png');
overflow: hidden;
}
.start{
position: absolute;
height: 30px;
width: 150px;
background-color: rgb(1, 255, 1);
border: 3px solid black;
border-radius: 5%;
font-size: 15px;
font-weight: bold;
top: 600px;
left : calc(50% - 150px/2);
transition: 0.5s;
}
.start:hover{
background: red;
}
.controlContainer{
padding: 5px;
width: 120px;
height: 120px;
border: 3px solid black;
border-radius: 5%;
background-color: lawngreen;
}
.btn{
height: 50px;
width: 50px;
border: 2px solid black;
border-radius: 50%;
}
.play{
background-image: url('play.png');
}
.pause{
background-image: url('pause.png');
}
.help{
background-image: url('help.png');
}
.restart{
background-image: url('restart.png');
}
.animate{
animation: road linear infinite 0.5s;
}
.hidden{
display: none;
}
#keyframes road{
0%{
background-position-y: 0px;
}
100%{
background-position-y: 600px;
}
}
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 45%;
background-color: white;
padding: 6rem;
border-radius: 5px;
box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.3);
z-index: 100000000;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 5rem;
color: #333;
cursor: pointer;
border: none;
background: none;
}
.car{
position: relative;;
height: 120px;
width: 60px;
border-radius: 5%;
top: 435px;
background: url('Player (1).png');
transform: rotate(180deg);
z-index: 100000;
}
.npcCar{
width: 60px;
height: 120px;
background: url('obsacle.png');
position: relative;
left: 15px;
top: -300px;
}
.npcCar2{
top: -420px;
left: 195px;;
}
.npcCar3{
top: -540px;
left: 375px
}
.carAnimate{
animation: vroom 0.8s linear infinite;
}
.carAnimate2{
animation: vroom 0.8s linear infinite;
}
.carAnimate3{
animation: vroom 0.8s linear infinite;
}
#keyframes vroom{
0%{
top: -120px;
}
100%{
top: 600px;
}
}
</style>
<script>
'use strict'
if (document.readyState === "complete") {
const startBtn = document.querySelector('.start')
const pauseBtn = document.querySelector('.pause')
const playBtn = document.querySelector('.play')
const restartBtn = document.querySelector('.restart')
const helpBtn = document.querySelector('.help')
const modal = document.querySelector('.modal');
const closeModal = document.querySelector('.close-modal');
const game = document.querySelector('.game');
const player = document.querySelector('.car');
const npcPlayer = document.querySelector('.npcCar');
const npcPlayer2 = document.querySelector('.npcCar2');
const npcPlayer3 = document.querySelector('.npcCar3');
const carAnimation = document.querySelector('.carAnimate');
const carAnimation2 = document.querySelector('.carAnimate2');
const carAnimation3 = document.querySelector('.carAnimate3');
let click = 0;
let interval;
let both = 0;
let counter = 0;
//onLoad
window.addEventListener("load", () => {
player.style.position = "relative";
player.style.left = '195px';
player.style.top = '485px';
});
// Start the Game
startBtn.addEventListener('click', function(){
console.log('button clicked');
game.classList.add('animate');
click+=2;
npcPlayer.classList.add('carAnimate')
npcPlayer2.classList.add('carAnimate2')
npcPlayer3.classList.add('carAnimate3')
carAnimation.addEventListener('animationiteration', () => {
var random = Math.floor(Math.random() * 5);
left = random * 90 + 15;
carAnimation.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation2.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation2.style.left = left + "px";
counter++;
console.log(counter)
});
carAnimation3.addEventListener('animationiteration', () => {
var random1 = Math.floor(Math.random() * 5);
left = random1 * 90 + 15;
carAnimation3.style.left = left + "px";
counter++;
});
});
//Pausing the Game
pauseBtn.addEventListener('click', function(){
console.log('button clicked');
if(click>1){
game.classList.remove('animate');
click--
}
console.log(click)
});
//Resuming the Game
playBtn.addEventListener('click', function(){
console.log('button clicked');
if(click===1){
game.classList.add('animate');
click++;
console.log(click);
}
});
//Opening the Help Model
helpBtn.addEventListener('click', function(){
console.log('modal clicked')
modal.classList.remove('hidden')
});
//closing the help modal
closeModal.addEventListener('click', function(){
console.log('button clicked')
modal.classList.add('hidden')
});
//Moving Functions
function moveLeft() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
var transform = parseInt(window.getComputedStyle(player).getPropertyValue("transform"));
if (left > -0) {
player.style.left = left - 2 + "px";
player.style.transform = 'rotate(-' + 215 + 'deg)'
}
}
function moveRight() {
var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
if (left < 385) {
player.style.left = left + 2 + "px";
player.style.transform = 'rotate(' + 215 + 'deg)'
}
}
function moveUp() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top > 0) {
player.style.top = top - 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
function moveDown() {
var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
if (top < 490) {
player.style.top = top + 2 + "px";
player.style.transform = 'rotate(' + 180 + 'deg)'
}
}
//Make the pLayer move
document.addEventListener("keydown", (event) => {
if (both == 0) {
both++;
if (event.key === "ArrowLeft") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "ArrowRight") {
interval = setInterval(moveRight, 1);
}
if (event.key === "ArrowUp") {
interval = setInterval(moveUp, 1);
}
if (event.key === "ArrowDown") {
interval = setInterval(moveDown, 1);
}
if (event.key === "a") {
interval = setInterval(moveLeft, 1);
}
if (event.key === "d") {
interval = setInterval(moveRight, 1);
}
if (event.key === "w") {
interval = setInterval(moveUp, 1);
}
if (event.key === "s") {
interval = setInterval(moveDown, 1);
}
}
});
document.addEventListener("keyup", (event) => {
clearInterval(interval);
both = 0;
player.style.transform = 'rotate(' + 180 + 'deg)'
});
}
</script>

How to conform top glare to all child elements

Goal
Make the glare layer on all visible children like a clip-path
––––––––––––
Heads Up
Child elements can be any shape with any animation
Child elements can be any svg shape with any kind of animation attached to it
So glare must be automatically dynamic and conforming
––––––––––––
What I've Done
I create an apple TV effect…
But the glare only works as a box on top of other boxes.
The glare does not conform to other shapes
Example Below
––––––––––––
What I Can't Use
Canvas - No Canvas Please - I'm not familiar with it
Clip-Path - Because child elements can be anything overflowing outside of the glare
––––––––––––
What I'm looking for
Some kind of magical CSS line of code that makes the glare layer conform to all elements under it… like a normal glare would work.
Is this possible?
Is there some way Javascript can glare it automatically?
Is there some kind of mix-blend-mode I can use to make the glare just work?
Or is this something that is just impossible?
Glare should not look like a box
––––––––––––
What I tried
I tried to scale the glare layer to scale(1.1) and use some mix-blend-mode
But I couldn't figure out how to make it work.
appleTV();
function appleTV(){
appleTVComponents = 0;
function rotateX(n) {return ' rotateX('+n+'deg)'}
function rotateY(n) {return ' rotateY('+n+'deg)'}
function translateX(n) {return ' translateX('+n+'px)'}
function translateY(n) {return ' translateY('+n+'px)'}
function perspective(n) {return 'perspective('+n+'px)'}
function scale(n) {return ' scale3d('+n+','+n+','+n+')'}
function section(s='',e) {e=document.createElement('section');e.className='appletv_'+s;return e;}
function getWidth(e) {return e.clientWidth || e.offsetWidth || e.scrollWidth}
function setPerspective(e) {e.style.transform = perspective(getWidth(e)*3);}
function preventScroll(state) {if(supportsTouch){win.preventScroll=state||false;}}
function preventDefault(e) {if (supportsTouch&&win.preventScroll){e.preventDefault();}}
function isTouchScreen() {return 'ontouchstart' in window || navigator.msMaxTouchPoints}
function child(e) {return e.firstChild;}
function children(e) {return [...e.children]}
let body = document.body,
win = window,
imgs = document.querySelectorAll('.appletv'),
totalImgs = imgs.length,
supportsTouch = isTouchScreen(),
move = 'mousemove',
start = 'mouseenter',
end = 'mouseleave';
if(supportsTouch){move='touchmove'; start='touchstart'; end='touchend';}
if(totalImgs <= 0){return;}
for(var l=0;l<totalImgs;l++){
var thisImg = imgs[l],
layerElems = [...thisImg.querySelectorAll('.appletv_layer')];
if(!layerElems.length){continue;}
while(thisImg.firstChild) {thisImg.removeChild(thisImg.firstChild);}
var containerHTML = section(''),
shineHTML = section('gloss'),
shadowHTML = section('shadow'),
layersHTML = section('layer'),
layers = [];
thisImg.id = 'appletv_'+(++appleTVComponents);
layerElems.forEach((e,i)=>{
let layer_ = section('rendered_layer')
layer = section(''),
img = e.getAttribute('data-img');
layer_.setAttribute('data-layer',i);
[...e.children].forEach(c=>{layer.appendChild(c)})
if (img) {layer.style.backgroundImage = 'url('+img+')';}
layer_.appendChild(layer);
layersHTML.appendChild(layer_);
layers.push(layer);
});
[shadowHTML,layersHTML,shineHTML].forEach(e=>{containerHTML.appendChild(e)});
thisImg.appendChild(containerHTML);
var w = getWidth(thisImg);
setPerspective(thisImg)
preventScroll();
(function enableMovements(_thisImg,_layers,_totalLayers,_shine) {
thisImg.addEventListener(move, e=>{processMovement(e,supportsTouch,_thisImg,_layers,_totalLayers,_shine);});
thisImg.addEventListener(start, e=>{processEnter(_thisImg);});
thisImg.addEventListener(end, e=>{processExit(_thisImg,_layers,_totalLayers,_shine);});
})(thisImg,layers,layerElems.length,shineHTML);
};
function processMovement(e, touchEnabled, elem, layers, totalLayers, shine){
preventDefault(e)
let bdst = body.scrollTop,
bdsl = body.scrollLeft,
pageX = (touchEnabled)? e.touches[0].pageX : e.pageX,
pageY = (touchEnabled)? e.touches[0].pageY : e.pageY,
offsets = elem.getBoundingClientRect(),
w = elem.clientWidth || elem.offsetWidth || elem.scrollWidth, // width
h = elem.clientHeight || elem.offsetHeight || elem.scrollHeight, // height
wMultiple = 320/w,
offsetX = 0.52 - (pageX - offsets.left - bdsl)/w, //cursor position X
offsetY = 0.52 - (pageY - offsets.top - bdst)/h, //cursor position Y
dy = (pageY - offsets.top - bdst) - h / 2, //#h/2 = center of container
dx = (pageX - offsets.left - bdsl) - w / 2, //#w/2 = center of container
yRotate = (offsetX - dx)*(0.07 * wMultiple), //rotation for container Y
xRotate = (dy - offsetY)*(0.1 * wMultiple), //rotation for container X
imgCSS = rotateX(xRotate)+rotateY(yRotate), //img transform
arad = Math.atan2(dy, dx), //angle between cursor and center of container in RAD
angle = arad * 180 / Math.PI - 90; //convert rad in degrees
if (angle < 0) {angle = angle + 360;}
if(elem.firstChild.className.indexOf(' over') != -1){imgCSS += scale(1.07);}
elem.firstChild.style.transform = imgCSS;
shine.style.background = 'linear-gradient(' + angle + 'deg, rgba(255,255,255,' + (pageY - offsets.top - bdst)/h * 0.4 + ') 0%,rgba(255,255,255,0) 80%)';
shine.style.transform = translateX((offsetX * totalLayers) - 0.1)+translateY((offsetY * totalLayers) - 0.1);
var revNum = totalLayers;
for(var ly=0;ly<totalLayers;ly++){
layers[ly].style.transform = translateX((offsetX * revNum) * ((ly * 2.5) / wMultiple))+translateX((offsetY * totalLayers) * ((ly * 2.5) / wMultiple));
revNum--;
}
}
function processEnter(e){preventScroll(true);setPerspective(e);child(e)&&child(e).classList.add('over');}
function processExit(elem, layers, totalLayers, shine){preventScroll();
child(elem).classList.remove('over')
child(elem).style.transform = '';
shine.style = '';
layers.forEach(e=>{e.style.transform = ''})
}
}
body,
html {
height: 100%;
min-height: 100%;
}
body {background: linear-gradient(to bottom, #f6f7fc 0%, #d5e1e8 40%);}
.center{
position: absolute;
left: 50%;
margin: 10px auto;
transform: translateX(-50%);
}
.appletv {
position: relative !important;
margin: 0 auto !important;
display: inline-block;
width: 300px;
height: 150px;
border-radius: 5px;
transform-style: preserve-3d;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
cursor: pointer;
backface-visibility: hidden;
}
.appletv.depressed {
margin-top: 25px;
box-shadow: 0 5px 30px rgba(0, 0, 0, 0.4);
}
.appletv_ {
position: relative;
width: 100%;
height: 100%;
border-radius: 5px;
transition: all 0.2s ease-out;
background: teal;
}
.appletv_container.over {z-index: 1;}
.appletv_container.over .appletv_shadow {box-shadow: 0 45px 100px rgba(14, 21, 47, 0.4), 0 16px 40px rgba(14, 21, 47, 0.4);}
.appletv_layer {
position: relative;
width: 100%;
height: 100%;
border-radius: 5px;
/*overflow: hidden;*/
transform-style: preserve-3d;
}
.appletv_rendered_layer {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
overflow: hidden;
border-radius: 5px;
transition: all 0.1s ease-out;
transform-style: preserve-3d;
}
.appletv_rendered_layer > :first-child {
position: absolute;
width: 104%;
height: 104%;
top: -2%;
left: -2%;
background-repeat: no-repeat;
background-position: center;
background-color: transparent;
background-size: cover;
transition: all 0.1s ease-out;
}
.appletv_shadow {
position: absolute;
top: 5%;
left: 5%;
width: 90%;
height: 90%;
transition: all 0.2s ease-out;
box-shadow: 0 8px 30px rgba(14, 21, 47, 0.6);
}
.appletv_gloss {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 5px;
/*display: none !important;*/
background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0) 40%);
}
[data-layer="1"] {overflow: visible !important;}
[data-layer="1"] > section > section {
position: absolute;
background: rgb(50, 141, 210);
width: 60px;
height: 60px;
border-radius: 10px;
}
[data-layer="1"] > section > section:first-child {
left: -30px;
top: -10px;
}
[data-layer="1"] > section > section:last-child {
right: -20px;
top: 50px;
}
#keyframes rotate {
0% {transform: rotate(0);}
100% {transform: rotate(359deg);}
}
.appletv_gloss {
/*display: none;*/
background-blend-mode: multiply;
}
.appletv [data-layer="1"] {
transform: scale(0.5);
transition: .3s ease-in-out 0s;
}
.appletv:hover [data-layer="1"] {
transform: scale(1);
}
.appletv:hover [data-layer="1"] > section > section {
animation: rotate 10s linear 0s infinite;
}
.appletv:hover [data-layer="1"] > section > section:last-child {
animation: rotate 25s linear 0s infinite;
}
#hover {
font-size: 30px;
position: absolute;
top: 37%;
text-align: center;
width: 100%;
color: white;
text-shadow: 0 2px 2px rgba(0,0,0,0.3) ;
}
<html>
<body>
<section class="center">
<section class="appletv">
<section class="appletv appletv_layer" data-img="https://source.unsplash.com/random">
<section id="hover">Hover Corners</section>
</section>
<section class="appletv appletv_layer">
<section></section>
<section></section>
</section>
</section>
</section>
</body>
</html>

Animating with Javascript

In this code, I was trying to move the yellow box (the small box) to the right, bottom, left, and top respectively in the red box (the big box) and I have wanted to move the yellow box unendly. I have moved the yellow box to the right and bottom but couldn't move to the left and top. I couldn't understand what the problem is. How should I write this code in Javascript? Could you help me, please? I have used Visual Studio Code.
window.onload = function(){
var posX = 0,posY =0, posZ=0;
var smallbox = document.getElementById("smallbox");
var time = setInterval(move,10);
function move(){
if(posX>=150){
if(posY>=150){
if(posZ>=150){
clearInterval(time);
}
else{
posZ++;
smallbox.style.right = posZ + "px";
}
}
else{
posY++;
smallbox.style.top = posY + "px";
}
}
else{
posX = posX+1;
smallbox.style.left = posX + "px";
}
}
}
#bigbox{
height: 200px;
width: 200px;
background-color: red;
position: relative;
}
#smallbox{
height: 50px;
width: 50px;
background-color: yellow;
position: absolute;
}
<div id="bigbox">
<div id="smallbox">
</div>
</div>
The reason that your animation is not working is that CSS alignments for objects must use "top" or "bottom" and "left" or "right" to align themselves. What you are doing is aligning horizontally using "left" and then trying to align horizontally using "right", or the same thing but around the other way.
What I would instead suggest is using code that essentially reads:
if at top-left, move right.
if at top-right, move down.
if at bottom-right, move left.
if at bottom-left, move up.
An example of this in action:
window.onload = function() {
var posX = 0,
posY = 0,
boxW = 200,
boxH = 200,
smallboxW = 50,
smallboxH = 50;
var smallbox = document.getElementById("smallbox");
var time = setInterval(move, 10);
function move() {
if (posY <= 0 && posX < boxW) {
// go right
posX++;
smallbox.style.left = posX + "px";
}
if (posX >= boxW - smallboxW && posY < boxH) {
// go down
posY++;
smallbox.style.top = posY + "px";
}
if (posY >= boxH - smallboxH && posX > 0) {
// go left
posX--;
smallbox.style.left = posX + "px";
}
if (posX <= 0 && posY > 0) {
// go up
posY--;
smallbox.style.top = posY + "px";
}
}
}
#bigbox {
height: 200px;
width: 200px;
background-color: red;
position: relative;
}
#smallbox {
height: 50px;
width: 50px;
background-color: yellow;
position: absolute;
}
<body>
<div id="bigbox">
<div id="smallbox">
</div>
</div>
</body>
Instead of managing all calculations yourself, use the power of CSS in javascript with Element.animate().
This will also allow you to pause and play whenever needed.
const smallbox = document.querySelector('#smallbox');
smallbox.animate([
// keyframes
{
transform: 'translate(150px, 0px)'
},
{
transform: 'translate(150px, 150px)'
},
{
transform: 'translate(0px, 150px)'
},
{
transform: 'translate(0px, 0px)'
},
{
transform: 'translate(150px, 0px)'
},
], {
// timing options
duration: 2000,
iterations: Infinity
});
#bigbox {
height: 200px;
width: 200px;
background-color: red;
position: relative;
}
#smallbox {
height: 50px;
width: 50px;
background-color: yellow;
position: absolute;
}
<div id="bigbox">
<div id="smallbox">
</div>
</div>
One alternative option is to use the CSS keyframes to animate.
#bigbox {
height: 200px;
width: 200px;
background-color: red;
position: relative;
}
#smallbox {
height: 50px;
width: 50px;
background-color: yellow;
position: relative;
animation: move-around 4s infinite linear;
}
#keyframes move-around {
0% {
left: 0;
top: 0;
transform: translate(0%, 0%);
}
25% {
left: 100%;
top: 0;
transform: translate(-100%, 0%);
}
50% {
left: 100%;
top: 100%;
transform: translate(-100%, -100%);
}
75% {
left: 0;
top: 100%;
transform: translate(0%, -100%);
}
100% {
left: 0;
top: 0;
transform: translate(0%, 0%);
}
}
<body>
<div id="bigbox">
<div id="smallbox">
</div>
</div>
</body>

Javascript - Get an arm to point at elements being hovered over

I'm trying to get a pivoted forearm to point at the links that are being hovered over.
It works on the actual website I'm making it on but the pointing isn't quite accurate (it's nearly there) - I think it's perhaps because the code is designed to pivot using the center of the image (ie an arrow) and I'm using CSS transform-origin: center left; to force it otherwise?
I've done a fair bit of research but I can't get past this last hurdle - How do I adjust the JS to make the pointing rotation accurate?
Here is the setup I'm using:
$(function() {
var img = $('.arrow');
// Store clock wise degrees of all elements
var clockwiseElemDegrees = {};
var currentArrowAngle = 0;
// Treat initial position of arrow as element 0
var prevElem = '0';
clockwiseElemDegrees['0'] = 0;
if (img.length > 0) {
var offset = img.offset();
var imgX = offset.left + (img.width() / 2);
var imgY = offset.top + (img.height() / 2);
// Get element degrees
$('.animation-trigger').each(function() {
var element = $(this);
var elementPosition = element.offset();
var elementX = elementPosition.left + (element.width() / 2);
var elementY = elementPosition.top + (element.height() / 2);
var radians = Math.atan2(elementY - imgY, elementX - imgX);
var degrees = radians * (180 / Math.PI);
clockwiseElemDegrees[element.attr('elem')] = (degrees < 0) ? (degrees + 360) : degrees;
});
$('.animation-trigger').mouseenter(function(event) {
// Check if arrow should be rotated clockwise
var clockwiseDegreesForNextElem = clockwiseElemDegrees[$(this).attr('elem')];
var clockwiseDegreesForPrevElem = clockwiseElemDegrees[prevElem];
if (clockwiseDegreesForNextElem < clockwiseDegreesForPrevElem)
clockwiseDegreesForNextElem += 360;
var clockwiseRotationRequired = clockwiseDegreesForNextElem - clockwiseDegreesForPrevElem;
if (clockwiseRotationRequired <= 180) {
// Do clockwise rotation
currentArrowAngle += clockwiseRotationRequired;
} else {
// Do anticlockwise rotation
currentArrowAngle -= (360 - clockwiseRotationRequired);
}
prevElem = $(this).attr('elem');
img.css('-moz-transform', 'rotate(' + currentArrowAngle + 'deg)')
.css('-webkit-transform', 'rotate(' + currentArrowAngle + 'deg)')
.css('-o-transform', 'rotate(' + currentArrowAngle + 'deg)')
.css('-ms-transform', 'rotate(' + currentArrowAngle + 'deg)');
});
}
});
.scriptybits {
width: 44%;
box-sizing: border-box;
display: inline-block;
}
.wholepage {
width: 100%;
height: 95vh;
position: relative;
}
.scriptcontainer {
margin-left: 5% !important;
}
.arrow {
position: absolute;
margin-top: 20vh;
margin-left: 4px;
width: 20vh;
z-index: 5;
-webkit-transition: all 400ms cubic-bezier(0.455, 0.03, 0.515, 0.955);
-moz-transition: all 400ms cubic-bezier(0.455, 0.03, 0.515, 0.955);
-o-transition: all 400ms cubic-bezier(0.455, 0.03, 0.515, 0.955);
transition: all 400ms cubic-bezier(0.455, 0.03, 0.515, 0.955);
transform-origin: center left;
}
.pageleft {
display: inline-block;
}
.pageright {
text-align: center;
width: 100%;
display: block;
position: relative;
height: 90vh;
}
.menucontainer {
display: block;
margin: auto;
text-align: center;
width: 60%;
position: absolute;
left: 43%;
top: 9vh;
}
.leaningman {
height: 86vh;
display: block;
position: absolute;
top: -5vh;
}
.animation-trigger {
border: 3px solid black;
border-radius: 10px;
padding: 10px 30px 10px 30px;
color: black;
font-size: 30px;
background-color: white;
display: block;
margin-bottom: 20px;
text-align: center;
width: fit-content;
margin-left: auto;
margin-right: auto;
}
<div class="wholepage">
<div class="scriptybits">
<div class="pageleft" style="float:left; width:100%;">
<div class="scriptcontainer" style="position:relative;">
<img src="https://i.imgur.com/qxhaZOc.png" class="arrow">
<img class="leaningman" src="https://i.imgur.com/L9zVucE.jpg">
</div>
</div>
<div class="pageright">
<div class="menucontainer">
Link 1
Link 2
Link 3
Link 4
Link 5
Link 6
Link 7
</div>
</div>
</div>
</div>
You are rotating the image from the center left, but you are calculating the rotation angle based on the position from the center both horizontally and vertically. Changing to
var imgX = offset.left
seems to improve it for me.

JavaScript slider not working properly

I am trying to make a slider, but i have run in to a problem: slideWidth variable (which is the width of the slide) is always the same, so when it gets to the second slide it doesn't want to go further, similar with the previous slide it slides to the empty space because of the fixed variable value. + It doesn't want to animate.
How to fix this?
Please check out the code:
// Slider
const slider_wrapp = document.querySelector('.tract-slider');
const slider = document.querySelector('.tract-slider-wrapp');
var slide = document.getElementsByClassName('tract-slide');
const leftBtn = document.querySelector('.slide-left');
const rightBtn = document.querySelector('.slide-right');
let swWidth = slider_wrapp.clientWidth;
let sliderWidth = swWidth * slide.length;
let slideWidth = swWidth;
slider.style.width = sliderWidth + "px";
for (var i = 0; i < slide.length; i++) {
slide.item(i).style.width = " " + swWidth + "px";
}
function moveRight() {
slider.style.transform = "translateX(" + (-slideWidth) + "px)";
}
function moveLeft() {
slider.style.transform = "translateX(" + (slideWidth) + "px)";
}
rightBtn.addEventListener("click", function() {
moveRight()
});
leftBtn.addEventListener("click", function() {
moveLeft();
});
.tract-slider {
width: 100%;
height: 75vh;
position: relative;
overflow: hidden;
}
.tract-slider-wrapp {
height: 100%;
position: relative;
-webkit-transition: translate 350ms cubic-bezier(.08, .13, 0, .81);
-o-transition: translate 350ms cubic-bezier(.08, .13, 0, .81);
transition: translate 350ms cubic-bezier(.08, .13, 0, .81);
}
.tract-slide {
height: 100%;
float: left;
position: relative;
display: block;
background-position: center;
-webkit-background-size: cover;
background-size: cover;
}
.tract-slide:nth-child(1) {
background-image: url("https://static.pexels.com/photos/126282/pexels-photo-126282.jpeg");
}
.tract-slide:nth-child(2) {
background-image: url("https://static.pexels.com/photos/29017/pexels-photo-29017.jpg");
}
.tract-slide:nth-child(3) {
background-image: url("https://static.pexels.com/photos/70760/dandelion-dandelion-seeds-taraxacum-fluffy-70760.jpeg");
}
.tract-slider-control {
position: absolute;
left: 0;
bottom: 0;
background: #ffffff;
padding: 1em;
}
.tract-slider-btn {
display: inline-block;
cursor: pointer;
margin-left: 1em;
}
.tract-slider-btn:nth-child(1) {
margin-left: 0;
}
<div class="tract-slider">
<div class="tract-slider-wrapp">
<div class="tract-slide"></div>
<div class="tract-slide"></div>
<div class="tract-slide"></div>
</div>
<div class="tract-slider-control">
<div class="tract-slider-btn slide-left">Prev</div>
<div class="tract-slider-btn slide-right">Next</div>
</div>
</div>
P.S. If you know the solution please write it in JavaScript not JQuery
Your problem is that you missed to calculate the translateX position of your slideWrapper : (the slideWidth var )
to fix it you have to check and assign a new calculated value instead of setting it always to the slider width .
Note that I've added calculation in both moveRight() and moveLeft()
See below working snippet : (using only js)
// Slider
const slider_wrapp = document.querySelector('.tract-slider');
const slider = document.querySelector('.tract-slider-wrapp');
var slide = document.getElementsByClassName('tract-slide');
const leftBtn = document.querySelector('.slide-left');
const rightBtn = document.querySelector('.slide-right');
let swWidth = slider_wrapp.clientWidth;
let sliderWidth = swWidth * slide.length;
let slideWidth = 0;
slider.style.width = sliderWidth + "px";
for (var i = 0; i < slide.length; i++) {
slide.item(i).style.width = " " + swWidth + "px";
}
function moveRight() {
slideWidth === sliderWidth - swWidth ? slideWidth = 0 : slideWidth += swWidth;
slider.style.transform = "translateX(" + (-slideWidth) + "px)";
}
function moveLeft() {
slideWidth === 0 ? slideWidth = sliderWidth-swWidth : slideWidth -= swWidth;
slider.style.transform = "translateX(" + (-slideWidth) + "px)";
}
rightBtn.addEventListener("click", function() {
moveRight()
});
leftBtn.addEventListener("click", function() {
moveLeft();
});
.tract-slider {
width: 100%;
height: 75vh;
position: relative;
overflow: hidden;
}
.tract-slider-wrapp {
height: 100%;
position: relative;
-webkit-transition: all 350ms cubic-bezier(.08, .13, 0, .81);
-o-transition: all 350ms cubic-bezier(.08, .13, 0, .81);
transition: all 350ms cubic-bezier(.08, .13, 0, .81);
}
.tract-slide {
height: 100%;
float: left;
position: relative;
display: block;
background-position: center;
-webkit-background-size: cover;
background-size: cover;
}
.tract-slide:nth-child(1) {
background-image: url("https://static.pexels.com/photos/126282/pexels-photo-126282.jpeg");
}
.tract-slide:nth-child(2) {
background-image: url("https://static.pexels.com/photos/29017/pexels-photo-29017.jpg");
}
.tract-slide:nth-child(3) {
background-image: url("https://static.pexels.com/photos/70760/dandelion-dandelion-seeds-taraxacum-fluffy-70760.jpeg");
}
.tract-slider-control {
position: absolute;
left: 0;
bottom: 0;
background: #ffffff;
padding: 1em;
}
.tract-slider-btn {
display: inline-block;
cursor: pointer;
margin-left: 1em;
}
.tract-slider-btn:nth-child(1) {
margin-left: 0;
}
<div class="tract-slider">
<div class="tract-slider-wrapp">
<div class="tract-slide"></div>
<div class="tract-slide"></div>
<div class="tract-slide"></div>
</div>
<div class="tract-slider-control">
<div class="tract-slider-btn slide-left">Prev</div>
<div class="tract-slider-btn slide-right">Next</div>
</div>
</div>

Categories

Resources