Display a message once (like a cookie consent) on first visit - javascript

I'm building a website and am trying to display a message at the top of the page (inside the header) so it only appears once on every visit/session. An example of this the 'Book an appointment' green bar at the top of this website:
https://www.tiffany.co.uk
My website is here: https://vitrify.tempurl.host/
I've got as far as having a message appear (orange panel at top of page) but currently it appears every time a page is loaded. I just want it to appear once, just like a cookie consent.
I've spent hours looking for a solution but, as I'm not a programmer, I'm struggling. Any help would be much appreciated.
Here's the HTML:
function myFunction() {
var x = document.getElementById("topDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.topDIV {
color: #000000;
font-weight: 300;
font-size: 15px;
}
.topDIV a:link, .topDIV a:visited {
color: #000000!important;
font-weight: 500;
letter-spacing: -0.3px;
line-height: 1.2 ;
}
span.topDIV {
}
.topDIV a:hover {
border-bottom: 1px solid rgba(0,0,0,0.50) !important;
display: inline-block;
}
.button-x {
position: relative;
float: right;
top: -5px;
background:none;
border:none;
color:rgb(0,0,0) ;
cursor: pointer;
vertical-align: 0px;
}
.button-x:before {
font-family: 'Times';
content: "X";
font-size:30px;
vertical-align:0px;
opacity:0.5;
}
.button-x:hover {
opacity:1!important;
}
<span class = "topDIV">Welcome to <em>Vitrify</em>. Following in the finest traditions of vitreous enamelled jewellery. Find out more.</span><button class = "button-x" onclick="myFunction()"></button>

As mentioned above you need to use localStorage to solve your problem.
Need to know when page is loaded
Get value from the localStorage
Add event to the button (i removed the onclick event from the html for a cleaner solution)
After click set value for localStorage and hide item
If localStorage have value, hide the element
working example
Javascript
document.addEventListener('DOMContentLoaded', function () {
const topDiv = document.querySelector('.topDIV');
const buttonX = document.querySelector('.button-x');
// Get value from localStorage when open the page
const lS = localStorage.getItem('first-visit');
// Add button 'click' event
buttonX.addEventListener('click', () => {
// Set value to the localStorage
localStorage.setItem('first-visit', false);
// hide DOM element
topDiv.style.display = 'none';
});
// This does not check on the first visit to the page
// If localStorage have value, hide DOM element
if (lS) topDiv.style.display = 'none';
});
Html
<span class="topDIV"
>Welcome to <em>Vitrify</em>.Following in the finest traditions of
vitreous enamelled jewellery.
Find out more.
</span>
<button class="button-x"></button>

You can add a flag "showTopMessage:true" in your local storage or session storage based on one time msg to user or every time he visits. respectively.
On Cross/close icon click set the flag "showTopMessage:false".
const showTopBar = "SHOW_TOP_BAR";
const[showTopBar,setShowTopBar] = useState(true);
useEffect(()=>{
const saveState = localstorage.getItems(showTopBar);
if(saveState) setShowTopBar(saveState);
else localstorage.setItem(showTopBar, true);
},[]);
const handleTopBarClose = () => {
setShowTopBar(false);
localstorage.setItem(showTopBar, false);
}
return(
<div>
{
showTopBar && <TopBarComponent onClose={handleTopBarClose}/>
}
</div>
)

Related

Darkmode cookie is not removed on other pages when you press a certain key

to get straight to the point. The darkmode button is located on the start page ( index.html), I can turn it on and off with a click, as well as with the "D" key and it works so far. The problem however is that if I want to turn off the darkmode on another page with the "D" key, then the cookie is not deleted, because it apparently does not find the darkmode button on the page.
And please forgive my bad english and I hope I was able to make it more or less understandable.
The error messages:
enter image description here
HTML-Code:
<a onclick="toggleDarkMode()" id="darkButton" class="darkButton">Darkmode: Off</a>
CSS-Code:
.darkmode {
--primary-color: -;
--secondary-color: -;
--font-color: -;
--bg-color: -;
}
.darkButton {
font-size: 18px;
background-color: rgb(0, 0, 0);
color: white;
padding: 10px 35px 10px 35px;
border-radius: 8px;
cursor: pointer;
text-decoration: none;
-ms-user-select: None;
-moz-user-select: None;
-webkit-user-select: None;
user-select: None;
text-transform: uppercase;
}
.lightButton {
background-color: rgb(255, 255, 255);
color: black;
}
JS-Code:
//* js-cookie v3.0.1 | MIT *//
!function(a,b){var d,c;"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):(d=(a=a||self).Cookies,c=a.Cookies=b(),c.noConflict=function(){return a.Cookies=d,c})}(this,function(){"use strict";function b(b){for(var a=1;a<arguments.length;a++){var c=arguments[a];for(var d in c)b[d]=c[d]}return b}function a(c,d){function e(e,h,a){if("undefined"!=typeof document){"number"==typeof(a=b({},d,a)).expires&&(a.expires=new Date(Date.now()+864e5*a.expires)),a.expires&&(a.expires=a.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var g="";for(var f in a)a[f]&&(g+="; "+f,!0!==a[f]&&(g+="="+a[f].split(";")[0]));return document.cookie=e+"="+c.write(h,e)+g}}return Object.create({set:e,get:function(a){if("undefined"!=typeof document&&(!arguments.length||a)){for(var f=document.cookie?document.cookie.split("; "):[],b={},d=0;d<f.length;d++){var g=f[d].split("="),h=g.slice(1).join("=");try{var e=decodeURIComponent(g[0]);if(b[e]=c.read(h,e),a===e)break}catch(i){}}return a?b[a]:b}},remove:function(a,c){e(a,"",b({},c,{expires:-1}))},withAttributes:function(c){return a(this.converter,b({},this.attributes,c))},withConverter:function(c){return a(b({},this.converter,c),this.attributes)}},{attributes:{value:Object.freeze(d)},converter:{value:Object.freeze(c)}})}return a({read:function(a){return'"'===a[0]&&(a=a.slice(1,-1)),a.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(a){return encodeURIComponent(a).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"})})
//* js-cookie v3.0.1 | MIT *//
//* DARKMODE *//
let DarkMode = false;
function toggleDarkMode() {
var button = document.getElementById("darkButton");
var element = document.body;
element.classList.toggle("darkmode");
DarkMode = !DarkMode;
button.classList.toggle("lightButton");
console.log("DarkMode: " + DarkMode);
if (DarkMode) {
Cookies.set("DarkMode", "On");
document.getElementById("darkButton").innerHTML = "DarkMode: On";
} else {
Cookies.remove("DarkMode");
document.getElementById("darkButton").innerHTML = "DarkMode: Off";
}
}
let keyPress = 68
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === keyPress) {
Cookies.set("DarkMode", "On");
toggleDarkMode()
}
}
var DarkCookie = Cookies.get("DarkMode")
if (DarkCookie == 'On') {
CookieDarkMode = true;
Darkmode = true;
toggleDarkMode();
}
//* DARKMODE *//
If you don't have the darkButton ID in some pages, you can check if your variable button is not null.
if (button) do.something;
and instead of repeat document.getElementById("darkButton") you can use your variable button, check inside the if (DarkMode).
let DarkMode = false;
function toggleDarkMode() {
var button = document.getElementById("darkButton");
var element = document.body;
element.classList.toggle("darkmode");
DarkMode = !DarkMode;
if (button) button.classList.toggle("lightButton");
console.log("DarkMode: " + DarkMode);
if (DarkMode) {
//Cookies.set("DarkMode", "On");
if (button) button.innerHTML = "DarkMode: On";
} else {
//Cookies.remove("DarkMode");
if (button) button.innerHTML = "DarkMode: Off";
}
}
toggleDarkMode();
Considering this code is executed on all pages, one way to workaround this is to split cookies business & button business into separate functions.
E.g.:
let DarkMode = false;
// ...
function toggleDarkModeCookies() {
if (DarkMode) {
Cookies.set("DarkMode", "On");
} else {
Cookies.remove("DarkMode");
}
}
function toggleDarkModeButton() {
var button = document.getElementById("darkButton");
// Do nothing if there's no button
if (!button) {
return;
}
// The rest of handling logic
// ...
}
Then you can use toggleDarkModeCookies & have an event listener firing it even if there's no toggle button on the page

show and hide toTopButton according the scrolling but window.onscroll not work ..i can not fix the real problem

Please I need your support as I write this code to create a button and when I press it I move to the top of page ...the button is created good and move to top of page ... But I want the button hide when the scrolling in the top of page and appear again when I scroll down ...the scroll function not work I do not know the reason … I support you with the code in JavaScript and CSS related to my question …you are genius if you can fix it.
First JavaScript code
//here i create a function to make scroll smooth...i can write it in css file but i want to show what is i lrarned:
const scrollSmoothly = function () {
const myHTML = document.querySelector("html");
myHTML.style.scrollBehavior = "smooth";
};
//create the to Top Button
//
scrollSmoothly();
function toTopButton_create() {
const toTopButton = document.createElement("botton");
const textnodeTOP = document.createTextNode("TO_Top");
toTopButton.appendChild(textnodeTOP);
//document.querySelector("footer").appendChild(toTopButton);
const rr = document.querySelector("footer");
rr.insertAdjacentElement("beforebegin", toTopButton);
toTopButton.setAttribute("id", "ourBtn");
toTopButton.addEventListener("click", test2);
}
toTopButton_create();
//below function to go to the top of sheet
function test2() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// below function to hide the (to top button) in the top and appear again when we scroll down
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
toTopButton.style.display = "block";
} else {
toTopButton.style.display = "none";
}
}
CSS code
#ourBtn {
padding: 16px;
right: 31px;
bottom: 10px;
font-size: 19px;
z-index: 98;
border-radius: 5px;
border: none;
outline: none;
display: block;
background-color: rgb(17, 199, 231);
color: rgb(29, 2, 2);
position: fixed;
cursor: pointer;
}
#ourBtn:hover {
background-color: rgb(219, 8, 8);
}
Note : when I change in CSS code and make display: none; the button hidden and when I change it to display: block; it appear again …this is not problem ...the real problem that the (to top button) not appear and hidden according to the scrolling ... I think the scroll function not work. Thanks for your support in advance.
Change this part of your code
// below function to hide the (to top button) in the top and appear again when we scroll down
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
toTopButton.style.display = "block";
} else {
toTopButton.style.display = "none";
}
}
To this
// below function to hide the (to top button) in the top and appear again when we scroll down
document.onscroll = scrollFunction;
function scrollFunction(event) {
if (event.srcElement.scrollingElement.scrollTop > 20 || document.documentElement.scrollTop > 20) {
toTopButton.style.display = "block";
} else {
toTopButton.style.display = "none";
}
}
Note:
Attach the event to the document object
Look for the scrollingElement (it might not be the body element)
The main problem in my code was the variable (toTopButton) this variable defined in the function ,so it is not declared or defined out the function ...when I create it a gain in the global area ...the function worked good

is there a way to change fixed element style when enter any section element on scroll

I have a chat or go to top svg btn with white border and some of my sections element have blue and other white background
what I want to do is when the fixed btn enter the section while scrolling check its background
and add different classes in each case .
how can I do that in javascript or jquery ?
thank you
The easiest thing to do would be to have the fixed button have a background color that looks good on all sections. That way you can just style it and leave it alone.
If you have to have the color change at different sections, there are a few ways of doing that, none are easy, and only a few would have good performance.
The best way of doing this that I can think of would be:
Have the background of the fixed button be the default color.
Add a class modifier so that when you add one class it changes the style to the new color. Example: .button becomes .button.red
On each section that has to change the background of the button, add a custom data-attribute Example: <section change-button-bg="red">
Then on load
Set up a .querySelectorAll(*[change-button-bg]) so that you can run
a check on each of the sections.
Add a global variable called currentTarget
Set up an Intersection Observer on all the sections.
Have the callback function for .isIntersecting do a few things.
Update the currentTaget variable
Update the color of the button
Add a scroll listener
In the scroll listener watch the bounds.bottom of currentTarget to see which color it should be.
Then in the Intersection Observer, if it's no longer intersecting, remove the scroll listener to prevent memory leaks.
Here is a working example.
window.addEventListener('load', (event) => {
const changeBG = document.querySelectorAll('*[change-button-bg]');
let currentTarget = null;
const Observer = new IntersectionObserver((entries, Observer) => {
for (const entry of entries) {
if (entry.isIntersecting) {
currentTarget = entry.target;
addColor(true);
window.addEventListener('scroll', watchTarget);
} else {
addColor(false);
window.removeEventListener('scroll', watchTarget)
}
}
}, {threshold: 0.15});
for (const element of changeBG) {
Observer.observe(element);
}
function watchTarget() {
const bounds = currentTarget.getBoundingClientRect();
if (bounds.bottom < window.innerHeight - 80) {
addColor(false);
} else {
addColor(true);
}
}
function addColor(add) {
const btn = document.getElementById('button');
if (add) {
btn.classList.add('red');
} else {
btn.classList.remove('red');
}
}
});
body {
margin: 0;
}
section {
width: 100vw;
height: 100vh;
background: red;
}
section:nth-child(even) {
background: blue;
}
button {
position:fixed;
right: 50px;
bottom: 50px;
padding: 15px 25px;
border: none;
color: white;
background-color: blue;
cursor: pointer;
}
button.red {
background-color: red;
}
<html>
<body>
<section></section>
<section change-button-bg="red"></section>
<section></section>
<section change-button-bg="red"></section>
<section></section>
<button id="button">Top</button>
</body>
</html>
this is the solution I was looking for I did it using Intersection Observer
document.addEventListener('DOMContentLoaded',()=>{
let options = {
root:null,
rootMargin:"-570px 0px -100px 0px",
threshold:0.05
};
let Observer= new IntersectionObserver(changColor,options);
document.querySelectorAll("section").forEach(section => {
Observer.observe(section);
});
});
function changColor(elements) {
elements.forEach(el => {
if (el.isIntersecting) {
let elbg=el.target.dataset.bg;
if (elbg=="blue") { //if section data-bg== blue
// change svg button style
document.getElementById("chatting_path_7").style.fill = "#fff";
document.getElementById("to_top_Ellipse_4").style.stroke = "#fff";
} else {
document.getElementById("chatting_path_7").style.fill = "#034ea2";
document.getElementById("to_top_Ellipse_4").style.stroke = "#034ea2";
}
}
})
}

Why don't if statments work when repeated in JavaScript?

I am trying to make a grid where the different boxes will blink based off of a binary value defined within my HTML document. I have created a grid in HTML, where the background colour is automatically green and what I'm trying to achieve is that if my value changes to from 0 to 1 for each of the grid items it will then change the colour to red and blink respectively.
I have managed to get the first one working and thought I could just repeat the code with different variables assigned, however this hasn't worked. The weird thing is, if I remove the code for the first box the second box will start working.
Do I need to add some extra code in JS to separate the if statments?
CSS'
.grid-container {
display: grid;
grid-gap: 50px;
grid-template-columns: auto auto auto;
background-color: grey;
padding: 10px;
}
.grid-item {
background-color: green;
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 50px;
font-size: 30px;
text-align: center;
}
HTML
<div class="grid-container">
<div class="grid-item" id = "blink1">A</div>
<div class="grid-item" id = "blink2">B</div>
</div>
<div class = "values">
<div id = "$box1value"> 1 </div>
<div id = "$box2value"> 1 </div>
</div>
JS
var $box1 = document.getElementById("$box1value").innerHTML;
if ($box1 > 0) {
document.getElementById("blink1").style.backgroundColor = '#ff0000';
// blink "on" state
function show() {
if (document.getElementById)
document.getElementById("blink1").style.visibility = "visible";
}
// blink "off" state
function hide() {
if (document.getElementById)
document.getElementById("blink1").style.visibility = "hidden";
}
for (var i = 900; i < 99999999999; i = i + 900) {
setTimeout("hide()", i);
setTimeout("show()", i + 450);
}
} else {
document.getElementById("blink1").style.backgroundColor = '#098700';
}
/////////////////////next box/////////////////////////////
var $box2 = document.getElementById("$box2value").innerHTML;
if ($box2 > 0) {
document.getElementById("blink2").style.backgroundColor = '#ff0000';// blink "on" state
function show() {
if (document.getElementById)
document.getElementById("blink2").style.visibility = "visible";
}
// blink "off" state
function hide() {
if (document.getElementById)
document.getElementById("blink2").style.visibility = "hidden";
}
for (var i = 900; i < 99999999999999999; i = i + 900) {
setTimeout("hide()", i);
setTimeout("show()", i + 450);
}
} else {
document.getElementById("blink2").style.backgroundColor = '#098700';
}
2 different solutions (all JS vs. mostly CSS)
Keeping the core functionality in JS
Leveraging CSS for core functionality
I see what you're trying to achieve here, and I see a couple of different ways to accomplish this. Both of the solutions below allow your code to dynamically loop through any number of box items— no need to write a separate block for each item.
The first example below is modeled more similar to yours, based on
your code but rewritten to work more dynamically. The second solution
further down greatly simplifies things by moving all initialization
scripting into CSS, leaving JS responsible for only boolean switching
if you need to make any real-time state switches.
#1. Keeping the core functionality in JS
This solution modifies your original code to dynamically read the values for however many values there are, and then looping through them. In order to perform the repeated blinking in JS, I would suggest using setInterval. You'll also need to move that outside the rest of the code when using a loop or you'll end up with a conflict between the loop's iterator and the setInterval's and setTimeout's timing. More on that here. You can see the working example below:
function blink(el) {
if (el.style) {
setInterval(function() {
el.style.visibility = "visible";
setTimeout(function() {
el.style.visibility = "hidden";
}, 450);
}, 900);
}
}
const $boxes = document.querySelectorAll('[id^="blink"]');
for (const $box of $boxes) {
var boxId = $box.id.match(/\d+/)[0]; // store the ID #
if (document.getElementById('$box' + boxId + 'value')) {
var boxValue = parseInt(document.getElementById('$box' + boxId + 'value').innerHTML);
if (boxValue) {
$box.style.backgroundColor = '#ff0000';
blink($box);
} else {
$box.style.backgroundColor = '#098700';
}
}
}
.grid-container {
display: grid;
grid-gap: 50px;
grid-template-columns: auto auto auto;
background-color: grey;
padding: 10px;
}
.grid-item {
background-color: #098700;
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 50px;
font-size: 30px;
text-align: center;
}
.values {
display: none;
}
<div class="grid-container">
<div class="grid-item" id="blink1">A</div>
<div class="grid-item" id="blink2">B</div>
<div class="grid-item" id="blink3">C</div>
</div>
<div class="values">
<div id="$box1value">1</div>
<div id="$box2value">0</div>
<div id="$box3value">1</div>
</div>
CodePen: https://codepen.io/brandonmcconnell/pen/ecc954bad5552962574c080631700932
#2. Leveraging CSS for core functionality
This solution moves all of your JS code (color and animation) to the CSS, moving the binary boolean switch 0/1 to data-attributes on the grid-items themselves instead of separate items and then trigger any boolean switches on those containers using JS by targeting them by another attribute such as ID, or as I used in my example below, another data-attribute I called data-blink-id. This is my recommended solution if you're able to move all of this logic into CSS. It'll be much easier to maintain and to manipulate in real-time, as all it requires to change state is a simple boolean switch.
.grid-container {
display: grid;
grid-gap: 50px;
grid-template-columns: auto auto auto;
background-color: grey;
padding: 10px;
}
.grid-item {
background-color: #098700;
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 50px;
font-size: 30px;
text-align: center;
}
.grid-item[data-blink-status="1"] {
background-color: #f00;
animation: blink 900ms linear infinite forwards;
}
#keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
<div class="grid-container">
<div class="grid-item" data-blink-id="1" data-blink-status="1">A</div>
<div class="grid-item" data-blink-id="2" data-blink-status="0">B</div>
<div class="grid-item" data-blink-id="3" data-blink-status="1">C</div>
</div>
CodePen: https://codepen.io/brandonmcconnell/pen/5b4f3090b3590902b11d50af43361758
To trigger the binary boolean switch on an item (turn ON/OFF), use the below JS command. I've commented this out in the CodePen example linked above. Un-comment this JS line to activate it and switch ON the block with data-blink-id=2
document.querySelector('[data-blink-id="2"]').setAttribute('data-blink-status', 1);
Even though your functions are declared inside if statements, they are still global.
So, you essentially redeclare the show and hide functions, and they stop working.
To make those functions local to the if statement, you'll have to use one of the ES6 block scope declarations, let or const, like this:
const show = function(){ ... }
const hide = function(){ ... }
To do this, you should also replace setTimeout's first argument with a reference to the function (actually, you should always do that):
setTimeout(hide, i)
setTimeout(show, i + 450)
Other improvements you can make:
Avoid that loop that sets timeouts. It's ugly, takes long to execute, and doesn't work forever. Instead, replace setTimeouts with setIntervals.
Remove the if (document.getElementById) part. You can count on it to be defined (it has been around for a loooong time...)
So, you get to:
var $box1 = document.getElementById("$box1value").innerHTML;
if ($box1 > 0) {
document.getElementById("blink1").style.backgroundColor = '#ff0000';// blink "on" state
const show = function () {
document.getElementById("blink1").style.visibility = "visible";
}
// blink "off" state
const hide = function () {
document.getElementById("blink1").style.visibility = "hidden";
}
let flag = false //This is needed to keep track if the element is visible
setInterval(function(){
if(flag = !flag)
hide()
else
show()
}, 450);
} else {
document.getElementById("blink1").style.backgroundColor = '#098700';
}
/////////////////////next box/////////////////////////////
var $box2 = document.getElementById("$box2value").innerHTML;
if ($box2 > 0) {
document.getElementById("blink2").style.backgroundColor = '#ff0000';// blink "on" state
const show = function () {
document.getElementById("blink2").style.visibility = "visible";
}
// blink "off" state
const hide = function () {
document.getElementById("blink2").style.visibility = "hidden";
}
let flag = false //This is needed to keep track if the element is visible
setInterval(function(){
if(flag = !flag)
hide()
else
show()
}, 450);
} else {
document.getElementById("blink2").style.backgroundColor = '#098700';
}

how to stop a sound when an animation ends

I have very little experience in coding in general. But I've somehow managed to get this far with this, and I'm stuck on the very last thing.
This is for a Twitch alert, I'm doing this through 'Stream Elements'
The thing I'm having issues with is stopping the sound once the typing letters have fully appeared, I have no idea how to do this. Is it even possible?
I Forgot to mention, the Typekit links are intentionally broken, as I didn't want to share the link (Since I'm assuming they're all unique and based off your adobe account)
$(document).ready(function() {
var timer, fullText, currentOffset, onComplete, hearbeat = document.getElementById('heartbeat');
heartbeat.play();
function Speak(person, text, callback) {
$("#usernamean-container").html(person);
fullText = text;
currentOffset = 0;
onComplete = callback;
timer = setInterval(onTick, 120
);
}
function onTick() {
currentOffset++;
if (currentOffset == fullText.length) {
complete();
return;
}
var text = fullText.substring(0, currentOffset);
$("#message").html(text);
}
function complete() {
clearInterval(timer);
timer = null;
$("#message").html(fullText);
onComplete()
;
}
$(".box").click(function () {
complete();
});
Speak("{{name}}",
"{{name}} Is now a Witness",
)
//get data from the 🤟 StreamElements 🤟 data injection
const name = '{{name}}';
// vanilla es6 query selection (can use libraries and frameworks too)
const userNameContainer = document.querySelector('#username-container');
// change the inner html to animate it 🤪
userNameContainer.innerHTML = stringToAnimatedHTML(name, animation);
/**
* return an html, with animation
* #param s: the text
* #param anim: the animation to use on the text
* #returns {string}
*/
function stringToAnimatedHTML(s, anim) {
let stringAsArray = s.split('');
stringAsArray = stringAsArray.map((letter) => {
return `<span class="animated-letter ${anim}">${letter}</span>`
});
return stringAsArray.join('');
}
heartbeat.pause();
heartbeat.currentTime = 0;
});
#import url(#import url("https://use.typekit.net/.css");
.awsome-text-container {
font-family: typeka, sans-serif;
font-size: 42px;
font-weight: 400;
}
.image-container {
margin: auto;
display: table;
}
.text-container {
font-family: typeka, sans-serif;
font-size: 26px;
color: rgb(204, 10, 33);
text-align: center;
margin: auto;
text-shadow: rgba(0, 0, 0, 0.5) 1px 1px 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="heart" class="heart">
<audio id="heartbeat" src="https://cdn.discordapp.com/attachments/135995830279733248/733547597305741332/typewriters.mp3" preload="auto"></audio>
<link rel="stylesheet" href="https://use.typekit.net/.css">
<div class="text-container">
<div class="image-container">
<img src="https://media.tenor.com/images/83d6a5ed40a24164dfe1e4e19fad23d9/tenor.gif">
</div>
<div>
<div class="awsome-text-container">
<span id="message"></span>
<br>
</div>
</div>
</div>
Hello and welcome to Stack Overflow!
I have seen messier code and was therefor disappointed ;-). Regarding your question:
Main problem would be that you have a typo in your code and you call the heartbeat.pause(); in the complete method and not at the end of script (as this would be called independently of the completion of the animation).
Typo:
hearbeat = document.getElementById('heartbeat');
Changed method:
function complete() {
clearInterval(timer);
timer = null;
$("#message").html(fullText);
heartbeat.pause();
heartbeat.currentTime = 0;
}
and remove the lines from the bottom of your script.

Categories

Resources