Jump to content

Javascript change text every second

On my website I'm working on I have a p element with an id of "wp", I want to change the text of the p element every second:

 

example:

this_

(wait 1 sec)

this

(wait 1 sec)

this_

(wait 1 sec)

this

 

I just tried to figure it out for like 20 minutes but I don't really know javascript so I failed.

Could someone whip me up a script please? I'm lazy I know :P

Link to comment
https://linustechtips.com/topic/434243-javascript-change-text-every-second/
Share on other sites

Link to post
Share on other sites

You can use setInterval to trigger the action. Here are more examples using JavaScript timers. You can use document.getElementById to get the element you want to modify. Here are more examples of working with elements.

Link to post
Share on other sites

You can use setInterval to trigger the action. Here are more examples using JavaScript timers. You can use document.getElementById to get the element you want to modify. Here are more examples of working with elements.

After some work I got this: (I murdered all the javascript conventions, I'm sure)

var x = document.getElementsByTagName("p")[0].textContent;function swapText() {  if (x == "this") {    $("p").text("this_");  } else {    $("p").text("this");  }}setInterval(swapText, 1000)

 

But it only runs once. I put a while true loop over set interval but that just crashed my browser. Any advice?

Link to post
Share on other sites

DOH

 

I have to put the variable declaration in the method.  It works now

Your code uses jQuery, you didn't mentioned that so it won't work out of the box without including jQuery lib, there is no need to include jQuery to do such simple task, os here is tweaked version that uses native js, also I used id so you can exactly specify which element text you want to swap.

var x = document.getElementById("yourId");function swapText() {  if (x.textContent == "this") {    x.textContent = "this_";  } else {    x.textContent = "this";  }}setInterval(swapText, 1000) 

http://jsfiddle.net/pz8cwaoh/

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×