In my vanilla JavaScript code, I have a function that changes the text content of a span element in the DOM on page load event.
Although the DOM elements are changed as expected, there is still a slight flickering effect before the text is updated for the variables desktop
and mobile
.
Illustration of the flickering issue:
- Initially, the span tag displays "Text I want to change" briefly.
- After the content fully loads, the span tag shows the updated text as "text1 changed".
This flickering may be occurring because the DOM changes are applied only after the entire page content has loaded. I would like to hide the span elements until the changes are made, and then reveal them.
The structure of elements for desktop
and mobile
that I intend to modify looks like this:
<span class="first-headline target-span">Text I want to change</span>
Check out the concept below:
var changesObj = {
"us": {
title: "text1 changed"
},
"eu": {
title: "text2 changed"
}
};
function changes() {
var webshop = changesObj[window.location.pathname.split('/')[1]];
console.log(webshop);
var changesText;
if (!webshop) {
console.log('webshop not found');
}
changesText = webshop.title;
if (document.querySelector('.target-span').innerText.length > 0) {
var desktop = document.querySelector('.target-span');
console.log(desktop);
desktop.innerText = changesText;
console.log(desktop.innerText);
console.log("applied changes for dekstop");
}
if (document.querySelector('.target-span').innerText.lenght > 0) {
var mobile = document.querySelector('.target-span');
mobile.innerText = changesText;
console.log(mobile.innerText);
console.log("applied changes for mobile");
}
}
function invokeChanges() {
document.addEventListener("DOMContentLoaded", function () {
changes();
});
}
invokeChanges();
Is there a way to initially hide the DOM element until the change to the existing element has been applied and then show it?
I was considering using inline CSS rules like so:
Set .style.visibility='hidden'
and then reveal it with .style.visibility='visible'
once the text content is updated. However, I am unsure how to implement this solution effectively in my code.