I have an issue where I have a html 'p' tags where it should applies a javascript function. It is an animated typing script , however it doesn't seems to be working. The script only works if I put it below the html 'P' tags.
<link href="{% static 'js/animation.js' %}" rel="stylesheet"/>
<!--test active type writing animation-->
<div >
<p id="p_type">I'm <span ></span><span > </span></p>
</div>
<!-- To check , how to implement the script in js file and why it isn't working and only working-->
<script>
const typedTextSpan = document.querySelector(".typed-text");
const cursorSpan = document.querySelector(".cursor");
const textArray = ["a Data Analyst", "a Developer", "Henry Dumont"];
const typingDelay = 100;
const erasingDelay = 100;
const newTextDelay = 2000; // Delay between current and next text
let textArrayIndex = 0;
let charIndex = 0;
function type() {
if (charIndex < textArray[textArrayIndex].length) {
if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing");
typedTextSpan.textContent = textArray[textArrayIndex].charAt(charIndex);
charIndex ;
setTimeout(type, typingDelay);
}
else {
cursorSpan.classList.remove("typing");
setTimeout(erase, newTextDelay);
}
}
function erase() {
if (charIndex > 0) {
if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing");
typedTextSpan.textContent = textArray[textArrayIndex].substring(0, charIndex-1);
charIndex--;
setTimeout(erase, erasingDelay);
}
else {
cursorSpan.classList.remove("typing");
textArrayIndex ;
if(textArrayIndex>=textArray.length) textArrayIndex=0;
setTimeout(type, typingDelay 1100);
}
}
document.addEventListener("DOMContentLoaded", function() { // On DOM Load initiate the effect
if(textArray.length) setTimeout(type, newTextDelay 250);
});
</script>
why the code doesn't work if it saves in a file and call in the header script. It only works when the code is written between script html tags ??
I expect to call the script in the header and be working instead to be hard coded in the html page.
CodePudding user response:
For one thing your link is refering to a stylesheet
<link href="{% static 'js/animation.js' %}" rel="stylesheet"/>
rather than
<script src="{% static 'js/animation.js' %}" ></script>
But even assuming that is a copying error, because the script refers to elements in the page, those elements need to have been loaded before the script will work. Place the script under the <p>
tag, and they will have loaded first. But if you put the script in the header, it will run before the rest of the page has loaded, which means your queryselectors (eg, document.querySelector(".typed-text")
) won't find anything.
The way to avoid this is to use defer when you call the script in the header, eg,
<script src="{% static 'js/animation.js' %}" defer ></script>
This should prevent the script running until the page has loaded.