Home > Net >  Element that automatically toggles with javascript
Element that automatically toggles with javascript

Time:12-02

I'm trying to make an element that toggles by itself. For a example, I want <p>Text1</p> to switch to <p>Text2</p> in 1 second. Is there any javascript code I can use?

Here's an example of what i'm trying to do:

Text-toggling

CodePudding user response:

You could use the setTimeout(//function,n*1000) function in order for it to be done automatically after n seconds

With your example lets say you have:

let s = 1000; // second in milliseconds
let n = 3; //let's say you want it to change after 3 seconds

function changeText() {
  document.getElementById('text').innerText = 'Text2'
}

setTimeout(() => {
  changeText()
}, n * s); // you could also use setTimeout(function () { changeText() }, n * s);
<p id="text">Text1</p>
<!-- give the element an id ("text") in this example -->
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You need to assign a class or an ID to element, eg. <p id="el">...</p>, so that you can query it later on. Then, get it via document.getElementById or document.getElementByClassName: document.getElementById('el').

Now you got the element, time to change the text inside it, so access it via the innerText property, then assign a new value.

Alright, you want it to do it in one second, so set a timeout:

setTimeout(() => { /** ... */ }, 1000);

Note: 1000 is 1 second.

CodePudding user response:

An easy way would be to assign each element an id. Then in javascript, call setInterval or setTimeout. Every second, get the documents by id and toggle their CSS visibility style.

  • Related