I want to integrate this script to my website homepage and i don't know how. I tried to integrate code to function.php but it doesn't work.
The script :
(function(){
var PleaseRotate = {},
currentOrientation = null,
isMobile = /Android|iPhone|iPad|iPod|IEMobile|Opera Mini/i.test(navigator.userAgent),
init = false;
var options = {
startOnPageLoad: true,
onHide: function(){},
onShow: function(){},
forcePortrait: false,
message: "Please Rotate Your Device",
subMessage: "(or click to continue)",
allowClickBypass: true,
onlyMobile: true,
zIndex: 1000,
iconNode: null
};
var cssRules = [
"#pleaserotate-graphic { margin-left: 50px; width: 200px; animation: pleaserotateframes ease 2s; animation-iteration-count: infinite; transform-origin: 50% 50%; -webkit-animation: pleaserotateframes ease 2s; -webkit-animation-iteration-count: infinite; -webkit-transform-origin: 50% 50%; -moz-animation: pleaserotateframes ease 2s; -moz-animation-iteration-count: infinite; -moz-transform-origin: 50% 50%; -ms-animation: pleaserotateframes ease 2s; -ms-animation-iteration-count: infinite; -ms-transform-origin: 50% 50%; }",
"#pleaserotate-backdrop { background-color: white; top: 0; left: 0; position: fixed; width: 100%; height: 100%; }",
"#pleaserotate-container { width: 300px; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); }",
"#pleaserotate-message { margin-top: 20px; font-size: 1.3em; text-align: center; font-family: Verdana, Geneva, sans-serif; text-transform: uppercase }",
"#pleaserotate-message small { opacity: .5; display: block; font-size: .6em}"
];
var cssKeyframeRules = [
"pleaserotateframes{ 0% { transform: rotate(0deg) ; -moz-transform: rotate(0deg) ;-webkit-transform: rotate(0deg) ;-ms-transform: rotate(0deg) ;} 49% { transform: rotate(-90deg) ;-moz-transform: rotate(-90deg) ;-webkit-transform: rotate(-90deg) ; -ms-transform: rotate(-90deg) ; } 100% { transform: rotate(90deg) ;-moz-transform: rotate(-90deg) ;-webkit-transform: rotate(-90deg) ; -ms-transform: rotate(-90deg) ; } }",
];
/* private functions */
function overrideOptions(updates){
var prop;
for (var prop in updates){
options[prop] = updates[prop];
}
}
function setBodyClass(state){
if(document.documentElement){
document.documentElement.className = document.documentElement.className.replace( /(?:^|\s)pleaserotate-\S*/g , '' );
document.documentElement.className += " pleaserotate-" + state;
}
}
function addRules(sheet){
var i;
for(i = 0; i< cssRules.length; i++){
sheet.insertRule(cssRules[i], 0);
}
sheet.insertRule("#pleaserotate-backdrop { z-index: " + options.zIndex + "}", 0);
if(options.allowClickBypass){
sheet.insertRule("#pleaserotate-backdrop { cursor: pointer }", 0);
}
if(options.forcePortrait){
sheet.insertRule("#pleaserotate-backdrop { -webkit-transform-origin: 50% }", 0);
}
for(i = 0; i< cssKeyframeRules.length; i++){
if (CSSRule.WEBKIT_KEYFRAMES_RULE) { // WebKit
sheet.insertRule("#-webkit-keyframes " + cssKeyframeRules[i], 0);
}
else if (CSSRule.MOZ_KEYFRAMES_RULE) { // Mozilla
sheet.insertRule("#-moz-keyframes " + cssKeyframeRules[i], 0);
}
else if (CSSRule.KEYFRAMES_RULE) { // W3C
sheet.insertRule("#keyframes " + cssKeyframeRules[i], 0);
}
}
}
function createStyleSheet(){
var style = document.createElement("style");
style.appendChild(document.createTextNode("")); // I'm told we need this hack... something to do with safari but I don't feel like checking for sure
document.head.insertBefore(style, document.head.firstChild);
addRules(style.sheet);
}
function createElements(){
var backdrop = document.createElement("div"),
container = document.createElement("div"),
message = document.createElement("div"),
subMessage = document.createElement("small");
backdrop.setAttribute("id", "pleaserotate-backdrop");
container.setAttribute("id", "pleaserotate-container");
message.setAttribute("id", "pleaserotate-message");
backdrop.appendChild(container);
if(options.iconNode !== null){
container.appendChild(options.iconNode);
} else {
container.appendChild(createPhoneSVG());
}
container.appendChild(message);
message.appendChild(document.createTextNode(options.message));
subMessage.appendChild(document.createTextNode(options.subMessage));
message.appendChild(subMessage);
document.body.appendChild(backdrop);
}
function createPhoneSVG(){
var svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
svg.setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:xlink','http://www.w3.org/1999/xlink');
svg.setAttribute('id','pleaserotate-graphic');
svg.setAttribute('viewBox','0 0 250 250');
var group = document.createElementNS('http://www.w3.org/2000/svg','g');
group.setAttribute('id','pleaserotate-graphic-path');
if(options.forcePortrait){
group.setAttribute('transform','rotate(-90 125 125)');
}
var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', 'M190.5,221.3c0,8.3-6.8,15-15,15H80.2c-8.3,0-15-6.8-15-15V28.7c0-8.3,6.8-15,15-15h95.3c8.3,0,15,6.8,15,15V221.3z' +
'M74.4,33.5l-0.1,139.2c0,8.3,0,17.9,0,21.5c0,3.6,0,6.9,0,7.3c0,0.5,0.2,0.8,0.4,0.8s7.2,0,15.4,0h75.6c8.3,0,15.1,0,15.2,0' +
's0.2-6.8,0.2-15V33.5c0-2.6-1-5-2.6-6.5c-1.3-1.3-3-2.1-4.9-2.1H81.9c-2.7,0-5,1.6-6.3,4C74.9,30.2,74.4,31.8,74.4,33.5z' +
'M127.7,207c-5.4,0-9.8,5.1-9.8,11.3s4.4,11.3,9.8,11.3s9.8-5.1,9.8-11.3S133.2,207,127.7,207z');
svg.appendChild(group);
group.appendChild(path);
return svg;
}
function setVisibility(visible){
var backdropElement = document.getElementById("pleaserotate-backdrop");
if(visible){
if(backdropElement){
backdropElement.style["display"] = "block";
}
} else {
if(backdropElement){
backdropElement.style["display"] = "none";
}
}
}
function orientationChanged(){
var triggerOn = currentOrientation && !options.forcePortrait || !currentOrientation && options.forcePortrait,
propogate;
if(triggerOn){
propogate = options.onShow();
setBodyClass("showing");
} else {
propogate = options.onHide();
setBodyClass("hiding");
}
if(propogate !== undefined && !propogate){
return;
}
PleaseRotate.Showing = triggerOn;
setVisibility(triggerOn);
}
function isPortrait(){
return ( window.innerWidth < window.innerHeight);
}
function checkOrientationChange(){
if(!isMobile && options.onlyMobile){
if(!init){
init = true;
setVisibility(false);
setBodyClass("hiding");
options.onHide(); // run this exactly once if not mobile
}
return;
}
if(currentOrientation !== isPortrait()){
currentOrientation = isPortrait();
orientationChanged();
}
}
/* public functions */
PleaseRotate.start = function(opts){
if(!document.body){
window.addEventListener('load', PleaseRotate.start.bind(null, opts), false);
return;
}
if(opts){
overrideOptions(opts);
}
createStyleSheet();
createElements();
checkOrientationChange();
window.addEventListener( 'resize', checkOrientationChange, false );
if(options.allowClickBypass){
document.getElementById("pleaserotate-backdrop").addEventListener("click", function(){
var propogate = options.onHide();
setBodyClass("hiding");
PleaseRotate.Showing = false;
if(propogate === undefined || propogate){
setVisibility(false);
}
});
}
}
PleaseRotate.stop = function(){
window.removeEventListener('resize', onWindowResize, false);
}
PleaseRotate.onShow = function(fn){
options.onShow = fn;
if(init){
// if we have already been initialized, force a check
init = false;
currentOrientation = null;
checkOrientationChange();
}
};
PleaseRotate.onHide = function(fn){
options.onHide = fn;
if(init){
// if we have already been initialized, force a check so that onHide gets called
currentOrientation = null;
init = false;
checkOrientationChange();
}
};
PleaseRotate.Showing = false;
/* plumbing to support AMD, CommonJS, or Globals */
if (typeof define === 'function' && define.amd) {
setBodyClass("initialized");
define(['PleaseRotate'], function() {
return PleaseRotate;
});
} else if (typeof exports === 'object') {
setBodyClass("initialized");
module.exports = PleaseRotate;
} else {
setBodyClass("initialized");
window.PleaseRotate = PleaseRotate;
overrideOptions(window.PleaseRotateOptions);
if (options.startOnPageLoad) {
PleaseRotate.start();
}
}
})();
If you want the JavaScript to be on the homepage only, you can do this:
function wpdocs_scripts_method() {
if ( is_home() ) {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', false ) );
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );
Create a JavaScript file, and then place your code in there. Then replace the path and filename in the function above, and the script should be included on the homepage of your website. This code snippet should be placed in your functions.php file.
To read more: https://developer.wordpress.org/reference/functions/wp_enqueue_script/
Related
Looking for some help with a custom cursor. It's all working fine except for when you scroll, the custom cursor stays where it is on the page until you move the mouse again and then it catches up. So I need to make the custom cursor stick to the position of the default cursor at all times.
Thanks in advance!
const queryCursor = document.querySelector(".cursor");
var cursor = {
delay: 8,
_x: 0,
_y: 0,
endX: window.innerWidth / 2,
endY: window.innerHeight / 2,
cursorVisible: true,
cursorEnlarged: false,
$cursor: queryCursor,
init: function () {
this.outlineSize = this.$cursor.offsetWidth;
this.setupEventListeners();
this.animateDotOutline();
},
setupEventListeners: function () {
var self = this;
// On Hover Active
document.querySelectorAll("a, img, .elementor-custom-embed-image-overlay, button").forEach(function (el) {
el.addEventListener("mouseover", function () {
self.cursorEnlarged = true;
queryCursor.classList.add("active");
});
el.addEventListener("mouseout", function () {
self.cursorEnlarged = false;
queryCursor.classList.remove("active");
});
});
// On Hover Disappears
document.querySelectorAll("input, textarea, iframe, video, .footer").forEach(function (el) {
el.addEventListener("mouseover", function () {
self.cursorEnlarged = true;
queryCursor.classList.add("hidden");
});
el.addEventListener("mouseout", function () {
self.cursorEnlarged = false;
queryCursor.classList.remove("hidden");
});
});
document.addEventListener("mousemove", function (e) {
self.cursorVisible = true;
self.toggleCursorVisibility();
self.endX = e.pageX;
self.endY = e.pageY;
});
document.addEventListener("mouseenter", function (e) {
self.cursorVisible = true;
self.toggleCursorVisibility();
self.$cursor.style.opacity = 1;
});
document.addEventListener("mouseleave", function (e) {
self.cursorVisible = true;
self.toggleCursorVisibility();
self.$cursor.style.opacity = 0;
});
},
animateDotOutline: function () {
var self = this;
self._x += (self.endX - self._x) / self.delay;
self._y += (self.endY - self._y) / self.delay;
self.$cursor.style.top = self._y + "px";
self.$cursor.style.left = self._x + "px";
requestAnimationFrame(this.animateDotOutline.bind(self));
},
toggleCursorVisibility: function () {
var self = this;
if (self.cursorVisible) {
self.$cursor.style.opacity = 1;
} else {
self.$cursor.style.opacity = 0;
}
}
};
cursor.init();
.cursor {
z-index: 1000;
pointer-events: none;
position: absolute;
top: 50%;
left: 50%;
border-radius: 50%;
opacity: 0;
transform: translate(-50%, -50%);
transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out, background-color 0.3s, width 0.3s, height 0.3s;
width: 20px;
height: 20px;
background-color: #EBF602;
display: flex;
align-items: center;
justify-content: center;
}
.cursor.active {
transform: translate(-50%, -50%) scale(2);
opacity:0.7 !important;
}
.cursor.hidden {
opacity: 0 !important;
}
section{
min-height:100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor"></div>
<section></section>
<section></section>
I have a small page. Circles appear here, when you click on them they disappear.
I added here the possibility that in addition to clicking on the LMB, you can also click on a keyboard key, in my case it is "A".
But I noticed the problem that if you hold down the "A" button, then drive in circles, then the need for clicks disappears, and this is the main goal.
Can I somehow disable the ability to hold this button so that only clicking on it works?
I tried pasting this code, but all animations stopped working for me.
var down = false;
document.addEventListener('keydown', function () {
if(down) return;
down = true;
// your magic code here
}, false);
document.addEventListener('keyup', function () {
down = false;
}, false);
Get error:
"message": "Uncaught ReferenceError: mouseOverHandler is not defined"
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const keyDownHandler = (evt) => {
if(evt.keyCode === 65 && focusedEl) focusedEl.click();
}
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>
You can check the repeat property of the event, which
… is true if the given key is being held down such that it is automatically repeating.
(but notice the compatibility notes on auto-repeat handling)
const keyDownHandler = (evt) => {
if (!evt.repeat && evt.keyCode === 65) {
// ^^^^^^^^^^^
focusedEl?.click();
}
}
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>
Vision: On "mouseenter" spin the letter and change the color. On second "mouseenter" spin the letter and change color back.
Problem: When changing class, second animation is not working.
const landingEl = document.getElementById("landing");
const landingText = document.getElementById("landing-text");
// line brake on dot
const landingFraze = `Lorem ipsum dolor sit amet consectetur adipisicing elit.`;
const spans = document.getElementsByTagName('span');
let letterList = [];
let text;
// rotate leter function
function rotate(ind) {
let index = ind.path[0].id
let spiningLeter = document.getElementById(index);
if(!spiningLeter.classList.contains ('rotate') & !spiningLeter.classList.contains('unrotate')) {
spiningLeter.classList.add('rotate');
}
else if (spiningLeter.classList.contains('unrotate')) {
spiningLeter.classList.remove('unrotate');
spiningLeter.classList.add('rotate');
}
else {
spiningLeter.classList.replace('rotate', 'unrotate');
}
}
function everyLeter() {
let text = landingFraze;
// split fraze in sentences on dot
let sentenceList = text.split(".");
// adding css to every letter
sentenceList.forEach((element, i) => {
let div = document.createElement('div');
// spliting every letter
let list = element.split("");
// creating new element and adding letter to it with css
list.forEach((leter, index) => {
let span = document.createElement("span");
span.id = `${index}a${i}`;
// event listener on mouse enter
span.addEventListener('mouseenter', rotate);
let leterP = document.createElement('p');
// adding space between words
if(leter === ' ') {
leterP.style.marginLeft = '20px'
}
// add a dot at the end of the sentence
if(list.length === index + 1){
leterP.textContent = `${leter}.`;
} else {
leterP.textContent = leter;
}
// appending
span.appendChild(leterP);
div.appendChild(span);
});
// appending div to landing
landingText.appendChild(div);
});
}
// functions
everyLeter();
#import url("https://fonts.googleapis.com/css2?family=Luckiest+Guy&family=Roboto:wght#400;700&display=swap");
:root {
--font-color: rgb(243, 14, 224);
}
.landing-text {
font-family: "Luckiest Guy", cursive;
flex-wrap: wrap;
height: 100vh;
font-size: 6vw;
margin-top: 40vh;
margin-left: 4rem;
}
.landing-text div{
display: flex;
max-height: 120px;
}
.rotate {
animation: rotate 2s forwards;
}
#keyframes rotate {
100% {
transform: rotateY(720deg);
color: var(--font-color);
}
};
.unrotate {
animation: unrotate 2s forwards;
}
#keyframes unrotate {
100%{
transform: rotateY(720deg);
color: black;
};
}
<div class="landing" id='landing'>
<div class ="landing-text" id="landing-text"></div>
</div>
Vision: On "mouseenter" spin the letter and change the color. On second "mouseenter" spin the letter and change color back.
Problem: When changing class, second animation is not working.
Javscript
function rotate(ind) {
let index = ind.path[0].id;
let spiningLeter = document.getElementById(index);
if(!spiningLeter.classList.contains ('rotate') & !spiningLeter.classList.contains('unrotate')) {
spiningLeter.classList.add('rotate');
}
else if (spiningLeter.classList.contains('unrotate')) {
spiningLeter.classList.remove('unrotate');
spiningLeter.classList.add('rotate');
}
else {
spiningLeter.classList.replace('rotate', 'unrotate');
}
}
CSS
.rotate {
animation: rotate 2s forwards;
}
#keyframes rotate {
100% {
transform: rotateY(360deg);
color: rgb(26, 212, 2)}
};
.unrotate {
animation: unrotate 2s forwards;
}
#keyframes unrotate {
100%{
transform: rotateY(720deg);
color: var(--font-color);
};
}
Try and specify the start state of each animation.
const landingEl = document.getElementById('landing')
const landingText = document.getElementById('landing-text')
// line brake on dot
const landingFraze = `Lorem ipsum dolor sit amet consectetur adipisicing elit.`
const spans = document.getElementsByTagName('span')
let letterList = []
let text
// rotate leter function
function rotate(ind) {
let spiningLeter = ind.target
if (!spiningLeter.classList.contains('rotate') &
!spiningLeter.classList.contains('unrotate')
) {
spiningLeter.classList.add('rotate')
} else if (spiningLeter.classList.contains('unrotate')) {
spiningLeter.classList.remove('unrotate')
spiningLeter.classList.add('rotate')
} else {
spiningLeter.classList.replace('rotate', 'unrotate')
}
}
function everyLeter() {
let text = landingFraze
// split fraze in sentences on dot
let sentenceList = text.split('.')
// adding css to every letter
sentenceList.forEach((element, i) => {
let div = document.createElement('div')
// spliting every letter
let list = element.split('')
// creating new element and adding letter to it with css
list.forEach((leter, index) => {
let span = document.createElement('span')
span.id = `${index}a${i}`
// event listener on mouse enter
span.addEventListener('mouseenter', rotate)
let leterP = document.createElement('p')
// adding space between words
if (leter === ' ') {
leterP.style.marginLeft = '20px'
}
// add a dot at the end of the sentence
if (list.length === index + 1) {
leterP.textContent = `${leter}.`
} else {
leterP.textContent = leter
}
// appending
span.appendChild(leterP)
div.appendChild(span)
})
// appending div to landing
landingText.appendChild(div)
})
}
// functions
everyLeter()
:root {
--font-color: rgb(243, 14, 224);
}
.landing-text {
font-family: 'Luckiest Guy', cursive;
font-size: 4vw;
}
.landing-text div {
display: flex;
flex-wrap: wrap;
align-items: center;
}
.rotate {
animation: rotate 2s forwards;
}
#keyframes rotate {
0% {
color: black;
transform: rotateY(0deg);
}
100% {
transform: rotateY(720deg);
color: var(--font-color);
}
}
.unrotate {
animation: unrotate 2s forwards;
}
#keyframes unrotate {
0% {
color: var(--font-color);
transform: rotateY(720deg);
}
100% {
transform: rotateY(0deg);
color: black;
}
}
/* For demo only */
span {
margin: 4px;
padding: 0;
line-height: 0px;
}
/* ***** */
<div class="landing" id="landing">
<div class="landing-text" id="landing-text"></div>
</div>
I have a anime whose duration decreases when the black container crosses red, but this creates glitches. Can there be any method to remove the glitch in it.
I tried to delay the changes until path is completed by red but still faces the glitches.
delayInAnimeSub = ourVillanAnimeDuration * (ourVillanFigXValue / window.innerWidth)
animeDelayAmount = Math.abs(delayInAnimeSub.toFixed(2) - 0.2).toFixed(2);
I calculated the leftover distance of red from the left side and get the duration to complete that distance and added that to delay. But it still show glitches.
Here what happens in below snippet
Black box is hero which is controlled by space(to jump), <(to move left), >(to move right).
Red is villan(demon) which have animation to move from right side to left side with some duration in animation.
Whenever hero passes the red, red becomes faster(by trying to reduce animation duration), but with this red has glitches and start from anywhere(not from the place it should be next).
I want to increase speed of red but facing the glitches so tried to delay the change in animation duration until red crosses the screen but that didn't seems to work
let ourHeroFig = document.getElementById("ourHero");
let ourVillanFig = document.getElementById("obstacleBar");
let gameScoreDigits = document.getElementById("gameScoreDigits");
let valueXCoordinate = "";
let obstacleBarCrossed = true;
document.body.addEventListener('keydown', function(e) {
let ourHeroFigXValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('left'));
let ourHeroFigYValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('bottom'));
if (e.code === "ArrowRight") {
valueXCoordinate = ourHeroFigXValue + 100;
} else if (e.code === "KeyA" || e.code === "ArrowLeft") {
if (ourHeroFigXValue > ourHeroFig.offsetWidth + 90) {
valueXCoordinate = ourHeroFigXValue - 100;
} else {
valueXCoordinate = 0;
}
} else if (e.code === "Space") {
ourHeroFig.classList.add("animateHero");
setTimeout(function() {
ourHeroFig.classList.remove("animateHero");
}, 700)
}
changePosition();
})
function changePosition() {
ourHeroFig.style.left = valueXCoordinate + 'px'
}
let delayInAnimeSub = ""
setInterval(
function() {
let ourHeroFigXValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('left'));
let ourHeroFigYValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('bottom'));
let ourVillanFigXValue = parseInt(getComputedStyle(ourVillanFig).getPropertyValue('left'));
let ourVillanFigYValue = parseInt(getComputedStyle(ourVillanFig).getPropertyValue('bottom'));
let gameOverValueX = Math.abs(ourVillanFigXValue - ourHeroFigXValue);
let gameOverValueY = Math.abs(ourVillanFigYValue - ourHeroFigYValue);
if (gameOverValueX < ourVillanFig.offsetWidth && gameOverValueY < ourVillanFig.offsetHeight) {
console.log("yes touched");
ourVillanFig.classList.remove("animateVillan");
obstacleBarCrossed = false;
} else if (obstacleBarCrossed && gameOverValueX < ourVillanFig.offsetWidth) {
ourVillanAnimeDuration = parseFloat(getComputedStyle(ourVillanFig).getPropertyValue('animation-duration'));
delayInAnimeSub = ourVillanAnimeDuration * (ourVillanFigXValue / window.innerWidth)
animeDelayAmount = Math.abs(delayInAnimeSub.toFixed(2) - 0.2).toFixed(2);
console.log(animeDelayAmount, ourVillanAnimeDuration, ourVillanFigXValue)
if (ourVillanAnimeDuration <= 2) {
ourVillanAnimeDuration = 2
}
setTimeout(() => {
ourVillanFig.style.animationDuration = ourVillanAnimeDuration - 0.1 + "s";
}, animeDelayAmount);
}
// console.log(gameOverValueX,gameOverValueY)
}, 10);
#ourHero {
width: 20px;
height: 100px;
background-color: black;
position: fixed;
bottom: 0;
left: 0;
transition: 0.1s;
}
.animateHero {
animation: animateHero 0.7s linear;
}
#keyframes animateHero {
0% {
bottom: 0;
}
50% {
bottom: 350px;
}
100% {
bottom: 0;
}
}
#obstacleBar {
width: 20px;
height: 100px;
background-color: red;
position: fixed;
bottom: 0;
left: 50vw;
}
.animateVillan {
animation: animateVillan 5s linear infinite;
}
#keyframes animateVillan {
0% {
left: 110vw;
}
100% {
left: 0;
}
}
<div id="ourHero"></div>
<div id="obstacleBar" class="animateVillan"></div>
Thanks for help in advance
One way is to use Animation.playbackRate but it is still experimental.
let VillRate = 1
...
// inside the collision check
if (VillRate < 20) {
ourVillanFig.getAnimations()[0].playbackRate += 0.2
VillRate += 0.5
}
In the below snippet, red speed will increase untill a certain point everytime it touches black. You can adjust that behavior as you need.
let ourHeroFig = document.getElementById('ourHero')
let ourVillanFig = document.getElementById('obstacleBar')
let gameScoreDigits = document.getElementById('gameScoreDigits')
let valueXCoordinate = ''
let obstacleBarCrossed = true
let VillRate = 1
document.body.addEventListener('keydown', function(e) {
let ourHeroFigXValue = parseInt(
getComputedStyle(ourHeroFig).getPropertyValue('left')
)
let ourHeroFigYValue = parseInt(
getComputedStyle(ourHeroFig).getPropertyValue('bottom')
)
if (e.code === 'ArrowRight') {
valueXCoordinate = ourHeroFigXValue + 100
} else if (e.code === 'KeyA' || e.code === 'ArrowLeft') {
if (ourHeroFigXValue > ourHeroFig.offsetWidth + 90) {
valueXCoordinate = ourHeroFigXValue - 100
} else {
valueXCoordinate = 0
}
} else if (e.code === 'Space') {
ourHeroFig.classList.add('animateHero')
setTimeout(function() {
ourHeroFig.classList.remove('animateHero')
}, 700)
}
changePosition()
})
function changePosition() {
ourHeroFig.style.left = valueXCoordinate + 'px'
}
let delayInAnimeSub = ''
setInterval(function() {
let ourHeroFigXValue = parseInt(
getComputedStyle(ourHeroFig).getPropertyValue('left')
)
let ourHeroFigYValue = parseInt(
getComputedStyle(ourHeroFig).getPropertyValue('bottom')
)
let ourVillanFigXValue = parseInt(
getComputedStyle(ourVillanFig).getPropertyValue('left')
)
let ourVillanFigYValue = parseInt(
getComputedStyle(ourVillanFig).getPropertyValue('bottom')
)
let gameOverValueX = Math.abs(ourVillanFigXValue - ourHeroFigXValue)
let gameOverValueY = Math.abs(ourVillanFigYValue - ourHeroFigYValue)
if (
gameOverValueX < ourVillanFig.offsetWidth &&
gameOverValueY < ourVillanFig.offsetHeight
) {
if (VillRate < 20) {
ourVillanFig.getAnimations()[0].playbackRate += 0.2
VillRate += 0.5
}
}
}, 10)
#ourHero {
width: 20px;
height: 100px;
background-color: black;
position: fixed;
bottom: 0;
left: 0;
transition: 0.1s;
}
.animateHero {
animation: animateHero 0.7s linear;
}
#keyframes animateHero {
0% {
bottom: 0;
}
50% {
bottom: 350px;
}
100% {
bottom: 0;
}
}
#obstacleBar {
width: 20px;
height: 100px;
background-color: red;
position: fixed;
bottom: 0;
left: 50vw;
}
.animateVillan {
animation: animateVillan 5s linear infinite;
}
#keyframes animateVillan {
0% {
left: 110vw;
}
100% {
left: 0;
}
}
<div id="ourHero"></div>
<div id="obstacleBar" class="animateVillan"></div>
I tried this:
if (ourVillanFigXValue < 10) {
ourVillanFig.style.animationDuration = ourVillanAnimeDuration - 0.1 + "s";
}
It works ok but when time get reduced to 4s and after it, the red don't start from the end but start in between. Almost start from middle at 3s
let ourHeroFig = document.getElementById("ourHero");
let ourVillanFig = document.getElementById("obstacleBar");
let gameScoreDigits = document.getElementById("gameScoreDigits");
let valueXCoordinate = "";
let obstacleBarCrossed = true;
document.body.addEventListener('keydown', function(e) {
let ourHeroFigXValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('left'));
let ourHeroFigYValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('bottom'));
if (e.code === "ArrowRight") {
valueXCoordinate = ourHeroFigXValue + 100;
} else if (e.code === "KeyA" || e.code === "ArrowLeft") {
if (ourHeroFigXValue > ourHeroFig.offsetWidth + 90) {
valueXCoordinate = ourHeroFigXValue - 100;
} else {
valueXCoordinate = 0;
}
} else if (e.code === "Space") {
ourHeroFig.classList.add("animateHero");
setTimeout(function() {
ourHeroFig.classList.remove("animateHero");
}, 700)
}
changePosition();
})
function changePosition() {
ourHeroFig.style.left = valueXCoordinate + 'px'
}
let delayInAnimeSub = ""
setInterval(
function() {
let ourHeroFigXValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('left'));
let ourHeroFigYValue = parseInt(getComputedStyle(ourHeroFig).getPropertyValue('bottom'));
let ourVillanFigXValue = parseInt(getComputedStyle(ourVillanFig).getPropertyValue('left'));
let ourVillanFigYValue = parseInt(getComputedStyle(ourVillanFig).getPropertyValue('bottom'));
let gameOverValueX = Math.abs(ourVillanFigXValue - ourHeroFigXValue);
let gameOverValueY = Math.abs(ourVillanFigYValue - ourHeroFigYValue);
if (ourVillanFigXValue < 10) {
ourVillanFig.style.animationDuration = ourVillanAnimeDuration - 0.1 + "s";
}
if (gameOverValueX < ourVillanFig.offsetWidth && gameOverValueY < ourVillanFig.offsetHeight) {
console.log("yes touched");
ourVillanFig.classList.remove("animateVillan");
obstacleBarCrossed = false;
} else if (obstacleBarCrossed && gameOverValueX < ourVillanFig.offsetWidth) {
ourVillanAnimeDuration = parseFloat(getComputedStyle(ourVillanFig).getPropertyValue('animation-duration'));
console.log(ourVillanFigXValue < 0, ourVillanAnimeDuration)
if (ourVillanAnimeDuration <= 2) {
ourVillanAnimeDuration = 2
}
}
// console.log(gameOverValueX,gameOverValueY)
}, 10);
#ourHero {
width: 20px;
height: 180px;
background-color: black;
position: fixed;
bottom: 0;
left: 0;
transition: 0.1s;
}
.animateHero {
animation: animateHero 0.7s linear;
}
#keyframes animateHero {
0% {
bottom: 0;
}
50% {
bottom: 350px;
}
100% {
bottom: 0;
}
}
#obstacleBar {
width: 20px;
height: 180px;
background-color: red;
position: fixed;
bottom: 0;
left: 50vw;
}
.animateVillan {
animation: animateVillan 5s linear infinite;
}
#keyframes animateVillan {
0% {
left: 110vw;
}
100% {
left: 0;
}
}
<div id="ourHero"></div>
<div id="obstacleBar" class="animateVillan"></div>
I'm creating a small website that tells a story by using css and sprite animation.
The problem I'm encountering is that I do not know how to change the keyframes once I have set them in the css files expecially while I try to make it compatible with all of the browsers.
Here is what I have,
the main part of the css:
#ManSprite{
overflow:hidden;
width:200px;
height:200px;
position:absolute;
top:280px;
left:140px;
background-image: url("http://imageshack.com/a/img571/1710/2r1h.png");
z-index:99;
animation: play .4s steps(2) infinite;
-webkit-animation: play .4s steps(2) infinite;
-moz-animation: play .4s steps(2) infinite;
-ms-animation: play .4s steps(2) infinite;
-o-animation: play .4s steps(2) infinite;
}
#keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
#-webkit-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
#-moz-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
#-ms-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
#-o-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
Then in my javascript I would like to change the background position for every keyframe but I'm not sure how to change it. I've tried the following but it does not work.
var StoryPart = 0;
var fromArray = new Array("0px", "-200px", "-800px", "-1400px", "-2200px", "-3200px");
var toArray = new Array("0px", "-600px", "-1400px", "-2200px", "-3230px", "-4000px");
var stepsArray = new Array(0, 2, 3, 4, 5, 4);
function nextBtn() {
StoryPart++;
startChange();
}
// begin the new animation process
function startChange() {
// remove the old animation from our object
document.getElementById('ManSprite').style.webkitAnimationName = "none";
document.getElementById('ManSprite').style.animationName = "none";
document.getElementById('ManSprite').style.msAnimationName = "none";
document.getElementById('ManSprite').style.oAnimationName = "none";
document.getElementById('ManSprite').style.mozAnimationName ="none";
// call the change method, which will update the keyframe animation
setTimeout(function () { change("play", fromArray[StoryPart], toArray[StoryPart]); }, 0);
}
// search the CSSOM for a specific -webkit-keyframe rule
function findKeyframesRule(rule) {
// gather all stylesheets into an array
var ss = document.styleSheets;
// loop through the stylesheets
for (var i = 0; i < ss.length; ++i) {
// loop through all the rules
for (var j = 0; j < ss[i].cssRules.length; ++j) {
// find the -webkit-keyframe rule whose name matches our passed over parameter and return that rule
if (ss[i].cssRules[j].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE && ss[i].cssRules[j].name == rule
|| ss[i].cssRules[j].type == window.CSSRule.KEYFRAMES_RULE && ss[i].cssRules[j].name == rule
)
return ss[i].cssRules[j];
}
}
// rule not found
return null;
}
// remove old keyframes and add new ones
function change(anim, fromValue, toValue) {
// find our -webkit-keyframe rule
var keyframes = findKeyframesRule(anim);
// remove the existing 0% and 100% rules
keyframes.deleteRule("0%");
keyframes.deleteRule("100%");
// create new 0% and 100% rules with random numbers
keyframes.insertRule("0% {background-position: " + fromValue + ";}");
keyframes.insertRule("100% {background-position: " + toValue + ";}");
// assign the animation to our element (which will cause the animation to run)
document.getElementById('ManSprite').style.webkitAnimationName = anim;
document.getElementById('ManSprite').style.animationName = anim;
document.getElementById('ManSprite').style.msAnimationName = anim;
document.getElementById('ManSprite').style.oAnimationName = anim;
document.getElementById('ManSprite').style.mozAnimationName = anim;
}
For some reason in Chrome, it doesn't find any cssRule inside the findKeyframesRule method, but in firefox it does. Firefox crashes, however, on this line
keyframes.insertRule("0% {background-position: " + fromValue + ";}");
which confuses me because it was able to use deleteRule well.
Anyone ever work with these?