Home > Net >  Can styles happen one by one after interval?
Can styles happen one by one after interval?

Time:11-05

I need to make my styles to occur one after another after some interval time.

JS

element.style.cssText = "width: 400px; height:400px; background-color:blue; 
border: 1px solid green; border-radius: 10px; text-align: center; color:white; "

setInterval(function () {element.innerHTML  = element.style},1000);

the styles have to be declerated in JS (not necessarily using .cssText) `

CodePudding user response:

Applying styles is most easily done using the classList API, rather than with innerHTML or cssText.

See comments inline:

// Create the CSS dynamically *****************
var style = document.createElement('style');
style.innerHTML =
  `.backColor { background-color:blue; }
   .width { width:50px; }
   .height { height:100px; }
   .foreColor { color:white; }`;
document.head.appendChild(style);
// *********************************************

const element = document.querySelector("div");

// Array of CSS selector names
const styles = ["backColor", "width", "height", "foreColor"];

let index = 0; // Keeps track of which style to add next

let timer = setInterval(function(){
  // If we've added all the styles
  if(index >= styles.length) { 
    clearInterval(timer); // Stop the timer
  }
  
  element.classList.add(styles[index]); // Add the next style
  index  ;  // Increase the index
}, 1500);
<div>Sample Text</div>

CodePudding user response:

Your example code is written incorrectly.

setting element.style.cssText applies the styles from the string given.

Adding element.style to element.innerHTML will only add text into the element - not what you are looking for.

You should research how HTMLElement#style and Element#innerHTML work.

CodePudding user response:

Most simple way is to iterate over an array containing style like this :-

const cssText = "width: 400px; height:400px; background-color:blue; 
border: 1px solid green; border-radius: 10px; text-align: center; color:white; ";
const stylesArray = cssText.split(";");
let i = 0;
let timer = setInterval(function () {
    element.style  = styleArray[i  ];
// or your
// element.innerHTML  = styleArray[i  ];
    if ( i >= stylesArray ) clearInterval(timer);
},1000);
  • Related