Mathias
Mathias

Reputation: 171

How to change button text over time in Javascript?

I have a button on my page. And I would like that button to change language every 2/4 seconds with Javascript. e.g. When the page loads the text of the button will be search, and after 2 or 4 seconds it will change to other languages. It doesn't need to be an infinite loop, just the most simple.

HTML:

<button id="search" name="q">search</button>` 

Javascript:

var x = document.getElementById('search');
//after 2 seconds:
x.innerHTML="Suchen";
//And so on

Upvotes: 1

Views: 1984

Answers (4)

Ed Manet
Ed Manet

Reputation: 3178

You could also change the button to an input and use the value property instead of the innerHTML property. Here's the Javascript:

function changeButton() {
    var btn = document.getElementById('myButton');
    if (btn.value == "Search")
        btn.value = "Suchen";
    else
        btn.value = "Search";
}
setInterval(changeButton, 2000);

And the HTML

<input type="button" id="myButton" value="Search" />

Upvotes: 0

Pank
Pank

Reputation: 14268

> Demo : http://jsfiddle.net/JtHa5/

HTML

<button id="search" name="q">Search</button>` 

Javascript:

setInterval(changeButtonText, 2000);

function changeButtonText()
{
 var btnTxt = document.getElementById('search');
    if (btnTxt.innerHTML == "Search"){
         btnTxt.innerHTML = "Suchen";
    }
    else{
         btnTxt.innerHTML = "Search";
    }
}

Upvotes: 2

Jay Harris
Jay Harris

Reputation: 4271

This is the most robust and simple solution for your problem. JSFIDDLE. Loop through a predefined language dictionary using setInterval()

var x = document.getElementById('search'),
    // dictionary of all the languages
    lan = ['Search',  'Suchen', 'other'],
    // hold the spot in the dictionary
    i = 1;  

setInterval(function (){
  // change the text using the dictionary
  // i++ go to the next language
  x.innerHTML = lan[i++];
  // start over if i === dictionary length
  i = lan.length === i ? 0 : i;
}, 2000);

Upvotes: 2

fred02138
fred02138

Reputation: 3361

Use setInterval.

setInterval(function() {
    var btn = document.getElementById('search');
    if (btn.innerHTML == "search")
         btn.innerHTML = "Suchen";
    else
         btn.innerHTML = "search";
   }, 2000);

Upvotes: 1

Related Questions