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:
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 -->
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 viadocument.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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.