Create a time bound animation using CSS and javascript - javascript

Im trying to create an animation for a landing page. Since the animation runs every time the user refreshes the page or click on the home button, Im trying to limiting the animation to once every one hour. I wrote a javascript for the same, but there seems to be an error. Will be helpful if anyone can point out the mistake I've done.
let animationInterval;
let animationCompleted = false;
function animateOncePerHour() {
// Check if animation has already been completed
if (animationCompleted) return;
// Get the current time
const currentTime = new Date();
// Set the next animation time to be 1 hour later
const nextAnimationTime = new Date(currentTime.getTime() + 60 * 60 * 1000);
// Start the animation
document.querySelector('.text').style.animation = 'herot 1s';
// Set an interval to check the current time and stop the animation when the next animation time is reached
animationInterval = setInterval(() => {
const currentTime = new Date();
if (currentTime >= nextAnimationTime) {
clearInterval(animationInterval);
document.querySelector('.text').style.animation = 'none';
animationCompleted = true;
}
}, 1000);
}
// Call the animateOncePerHour function when the page loads
window.onload = animateOncePerHour;
.text {
width: 100%;
position: absolute;
left: 50%;
top: 45%;
transform: translate(-50%, -50%);
color: black;
text-align: center;
animation-name: herot;
animation-duration: 1s;
z-index: 1000;
}
#keyframes herot {
0% {
font-size: 16rem;
}
45% {
font-size: 10rem;
}
50% {
font-size: 10rem;
}
75% {
font-size: 10rem;
}
90% {
font-size: 10rem;
}
100% {
font-size: 0px;
}
}
.text {
font-size: 0px;
}
<div class="text">
<h1>NEN</h1>
</div>

The JS loads with the refresh of the page every time, so the variables
let animationInterval;
let animationCompleted = false;
and
new Date();
are all generated anew.
You will need some back-end to handle the timers and allow or block the animation.

Related

Smooth animation CSS and Javascript

I'm having a problem to keep an animation running "smooth" each time a new line of text is added.
The main problem here is that I want the speed of the animation to be constant, no matter how many lines are added. In order to do so the code is recalculating the speed each time a new line is added.
The problem is that when this happens the whole block of text "Jumps".
I was thinking that maybe the whole method I'm using wont give me the result I'm looking for so the question is.
Is there a fix or better alternative to achieve this?
I have a codepen with the example (Each time you press any key a new line will be added so we can simulate the behavior)
https://codepen.io/MrAmericanMike/pen/GeyZJg
Thanks a lot.
let marqueeContainer = document.getElementById("marqueeContainer");
let marqueeText = document.createElement("p");
marqueeContainer.appendChild(marqueeText);
document.addEventListener("keydown", addText);
let wordCount = 1;
function addText(){
let things = ['Rock', 'Paper', 'Scissor'];
let thing = wordCount + " - " + things[Math.floor(Math.random()*things.length)];
marqueeText.innerHTML += thing + "<br/>";
calcSpeed(50);
wordCount++;
}
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelector('#marqueeContainer p');
var spanLength = spanSelector.offsetHeight;
var timeTaken = spanLength / speed;
spanSelector.style.animationDuration = timeTaken + "s";
}
#marqueeContainer {
position: fixed;
top: 0px;
left: 0px;
width: 800px;
height: 200px;
z-index: 999;
background-color: rgba(0, 0, 33, 0.5);
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
text-align: center;
}
#marqueeContainer p {
display: inline-block;
padding-top: 200px;
animation: marqueeContainer linear infinite;
color: #FFFFFF;
}
#keyframes marqueeContainer {
0% { transform: translate(0, 0); }
100% { transform: translate(0, -105%); }
}
<div id="marqueeContainer"></div>

Javascript - How to change animation's duration onclick

How can I change the animation duration onclick? This is what I've done, I created two buttons, one with an animationduration of 10s while the other has an animationduration of 20s. The duration regardless of which button I click is the same, 10 seconds, as it is in the class section. How can I get depending on the button I click two different durations? Please use normal Javascript, no Jquery. Thank you! I also need to use the document.GetElementById().classname =""; as it is in the code.
function tenseconds() {
animation();
var sd = document.getElementById('ghost').className = 'earth';
sd.style.animationDuration = "10s";
}
function twentyseconds() {
animation();
var sd = document.getElementById('ghost').className = 'earth';
sd.style.animationDuration = "20s";
}
function animation() {
document.getElementById('ghost').className = 'earth';
}
<!DOCTYPE html>
<html>
<head>
<style>
.earth {
position: relative;
animation: move 10s linear;
background: red;
height: 20px;
width: 20px;
}
#-webkit-keyframes move {
from {
left: 0%;
}
to {
left: 100%;
}
}
</style>
</head>
<body>
<div id="ghost"> </div>
<button onclick="tenseconds();">10 seconds </button>
<button onclick="twentyseconds()"> 20 seconds </button>
</body>
</html>
Updated to use an animation, data attributes etc. Customize as needed. NOT supported in Edge, IE perhaps others. Leave to you to investigate possible ways to fix that. Review OLD edit for the original "fix"
I added another element and button so you could see how it might be used.
var myAnimation = {
keyframes: [
// keyframes
{
transform: 'translateX(0px)'
},
{
transform: 'translateX(300px)'
}
],
options: {
// timing options
// ms of duration default 1 second
duration: 1000,
iterations: 1, //forever would be Infinity
easing: "linear"
}
};
function animation(target, duration, visual) {
let sd = document.getElementById(target);
sd.className = visual;
myAnimation.options.duration = duration * 1000;
sd.animate(myAnimation.keyframes, myAnimation.options,visual);
}
function setup() {
let classThings = document.getElementsByClassName("animate-button");
let myFunction = function() {
let duration = this.dataset.duration;
let visual = this.dataset.visual;
let target = this.dataset.target;
animation(target, duration, visual);
};
for (var i = 0; i < classThings.length; i++) {
classThings[i].addEventListener('click', myFunction, false);
}
}
(function() {
setup();
})();
<!DOCTYPE html>
<html>
<head>
<style>
.fire {
position: relative;
background: red;
height: 20px;
width: 20px;
}
.water {
position: relative;
background: blue;
height: 20px;
width: 20px;
}
</style>
</head>
<body>
<div id="ghost"></div>
<div id="billy"></div>
<button class="animate-button" data-duration="10" data-target="ghost" data-visual="fire">10 seconds</button>
<button class="animate-button" data-duration="20" data-target="ghost" data-visual="fire">20 seconds</button>
<button class="animate-button" data-duration="5" data-target="billy" data-visual="water">5 seconds billy</button>
</body>
</html>
I created a little function that takes the animation time in seconds as an argument. Read the comments in the code for explanation.
function animation(duration) {
// select whatever element you are trying to animate
let target = document.getElementById('ghost');
// change the animationduration before starting to animate
target.style.animationDuration = `${duration}s`;
// add the animating class and start the animation
target.classList.add('animating');
// create a timeout to remove the animating class from your animated element
setTimeout(() => {
target.classList.remove('animating');
}, `${duration*1000}`);
}
#ghost{
position: relative;
background: red;
height: 20px;
width: 20px;
}
.animating {
animation: move 10s linear;
}
#-webkit-keyframes move {
from {
left: 0%;
}
to {
left: 100%;
}
}
<!DOCTYPE html>
<div id="ghost"> </div>
<button onclick="animation(10);">10 seconds </button>
<button onclick="animation(20);"> 20 seconds </button>

how to get soundcloud follower count using JavaScript

Does anyone know how to put the amount of followers from soundcloud into a JavaScript variable so I can have it ring a notification when I hit 1K follows I have code that I have got from code pen by another user that I have forked
my code is -> here
and if you do not want to go to see it I have included it below
HTML
' <head>
<meta http-equiv="refresh" content="5">
</head>
<div class="card">
<div class="icon">
<i class="fa fa-soundcloud fa-3x"></i>
</div>
<div class="count"></div>
<span>followers</span>
</div>
<audio id="myAudio">
<source src="file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/echoed-ding.mp3" type="audio/mpeg">
</audio>
<p id="demo"></p>
<button onclick="wright()" type="button">wright</button>
<!--
<button onclick="pauseAudio()" type="button">Pause Audio</button>
!-->'
css
#import url(https://fonts.googleapis.com/css?family=Montserrat:400,700|Open+Sans+Condensed:300);
$primary-font: "Montserrat";
$secondary-font: "Open Sans Condensed";
body {
background-color: #1F282D;
.card {
width: 145px;
height: 187px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
opacity: 0;
transition: .1s opacity;
/*border: 1px solid #fff;
border-radius: 6px;*/
&.visible {
opacity: 1;
}
.icon {
position: relative;
top: .85em;
}
.count {
font-family: $primary-font;
font-size: 4em;
line-height: 1em;
bottom: 0.9em;
}
span {
font-family: $secondary-font;
text-transform: uppercase;
font-size: 1.1em;
letter-spacing: 2px;
bottom: 1.1em;
}
.count, span, .icon i.fa {
position: absolute;
left: 50%;
transform: translateX(-50%);
color: #fff;
}
}
}
javascript
var abbrev = {
1e3: "K",
1e6: "M"
};
aja()
.method("GET")
.url('https://api.soundcloud.com/users/awesomesauce105?consumer_key=8bcccc3476eaa137a084c9f0c041915f')
.on('200', function(res) {
var followersCount = res.followers_count;
Object.keys(abbrev).map(function(k) {
k = +k;
if (followersCount > k) {
var a = followersCount / k,
short = a.toString().length > 3 ? Math.round(a * 10) / 10 : a;
followersCount = short + abbrev[k];
}
});
if (followersCount !== undefined) {
$(".card .count").text(followersCount);
$(".card").addClass("visible");
}
})
.go();
var audio = new Audio('file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/html%205%20up/echoed-ding.mp3');
function playMyAudio() {
audio.play()
}
var x = document.getElementById("myAudio");
function playAudio() {
x.play();
}
function pauseAudio() {
x.pause();
}
function wright(){
document.getElementById("demo").innerHTML = ;
}
My goal is to ring a notification when I hit 1K follows I have a mp3 located on my chromebook at file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/html%205%20up/echoed-ding.mp3
and I am trying to get it to play a couple of times so I can celebrate. I do not know how to check the amount of followers I have so I used code from someone else but since I did not make it I do not know what is happening in the JavaScript department and thus I cannot just figure it out on my own because I normally would just look up how to run a function when a variable hits a certain variable... and in turn would activate the x.play() to play the sound... if you have any suggestions please let me know thanks!
You can use Soundcloud's Javascript SDK to tap into their API from the client. So add this to your HTML:
<script src="https://connect.soundcloud.com/sdk/sdk-3.1.2.js"></script>
<script>
SC.initialize({
client_id: 'YOUR_CLIENT_ID' // edit this with your API credential
})
</script>
Unfortunately, there's no way to receive a "notification" from Soundcloud's API when your followers hit a certain number. Instead, you can write a function that looks up the user periodically, and do something special when the follower count is where you want it. So in your Javascript, something like:
function pollSoundcloud (interval) {
var timer = setInterval(function () {
SC.get('/user/YOUR_USER_ID').then(function (user) {
if (user.followers_count >= 1000) {
clearInterval(timer)
alert('You just reached 1000 followers!') // or do something else
}
})
}, interval)
}
pollSoundcloud(10000) // will check every 10 seconds

Countdown with setInterval going too fast

could someone help me, I would like to know how to make it so the countdown doesn't go faster every time I click? I assume clear interval but not sure what I need to put. Thanks
var cD = 100;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(cD +"s");
}
}
$(".countdown-trigger").click(function(){
cD = 100;
setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
</div>
<div class="countdown-trigger">
</div>
The issue is because you never clear the previous timeout on each successive click, hence after 3 clicks you have three timers all decrementing the value every 10ms.
To fix this call clearTimeout() when cD hits 0. Also note that you would need a mechanism to prevent starting multiple intervals while the previous one is still running, or else you'll have the same issue. To do that you can use a boolean flag. Try this:
var cD = 100, interval, running = false;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(('00' + cD).slice(-2) + "s");
} else {
clearInterval(interval);
running = false;
}
}
$(".countdown-trigger").click(function() {
if (running)
return;
cD = 100;
running = true;
interval = setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>
<div class="countdown-trigger"></div>
var cD = 100;
var myOtherVar;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(cD +"s");
} else {
clearInterval(myOtherVar);
}
}
$(".countdown-trigger").click(function(){
cD = 100;
myOtherVar = setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
</div>
<div class="countdown-trigger">
</div>
You're right. You just need to clear your interval. Every time you click the area it sets up another set of events that occur every 10ms & that is why it continues to get faster & faster.

Make an ad appear every 5 minutes?

Below is code I'm using to make an ad appear once a day. I want to switch it to appear once every 5 minutes. I thought changing the value of 1 in the script to 0.004 (if 1 = a day, .004 = about 5 minutes), but it doesn't seem to be working properly. Does anyone have any ideas? Thanks!
<style>
#donationad {
position: fixed;
bottom: 0;
left: 40px;
width: 250px;
height: 150px;
z-index: 999;
display: none;
}
#donationad.hide {
display: none;
}
.closebutton {
position: relative;
top: 20px;
left: 230px;
cursor: pointer;
}
.closebutton img {
width: 30px;
height: auto;
opacity: 1.0;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('.closebutton').click(function() {
$("#donationad").toggleClass("hide");
});
});
</script>
<div id="donationad">
<div class="closebutton"> <img src="http://www.dbknews.com/pb/resources/assets/img/modal_close_button.png"> </div>
<img src="https://s3.amazonaws.com/wapopartners.com/dbknews-wp/wp-content/uploads/2016/12/24020402/DBK-Donate250x150.jpg">
</div>
<script type="text/javascript">
var cookie = document.cookie;
if (cookie.indexOf('visited=', 0) == -1) {
var expiration = new Date();
expiration.setDate(expiration.getDate() + 1);
document.cookie = 'visited=1;expires=' + expiration + ';path=/';
var element = document.getElementById('donationad');
element.style.display = 'block';
}
</script>
Date.setDate sets the day of the month, not the "date". Confusing? Yes.
What you want is something different entirely.
document.cookie = 'visited=1;max-age=300;path=/';
// 300 is 5 minutes in seconds
This creates a cookie that can only live 5 minutes and you don't need to deal with date at all. You will lose old versions of IE, which will treat the cookie as temporary.

Categories

Resources