Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the previous text after an onclick JS function?

My code is:

    function changeText()
{
 document.getElementById('button').innerHTML = 'Downloading...';
}

The button:

<button id = "button" onclick='changeText()' value='Change Text'>Download file as CSV</button>

I want the button to change to "Downloading..." then return to "Download as CSV" a few seconds after, is this possible in JS?

like image 249
Sean9113 Avatar asked Sep 08 '15 14:09

Sean9113


People also ask

How do you go one step back in JavaScript?

The History. back() method causes the browser to move back one page in the session history.

How onclick function works in JavaScript?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.

How do I change the click text on a link?

Change an existing hyperlinkRight-click anywhere on the link and, on the shortcut menu, click Edit Hyperlink. In the Edit Hyperlink dialog, select the text in the Text to display box. Type the text you want to use for the link, and then click OK.

What does return do in JavaScript?

The return statement ends function execution and specifies a value to be returned to the function caller.


3 Answers

You can use setTimeout or on success of your asynchronous call:

function changeText() {
  document.getElementById('button').innerHTML = 'Downloading...';
  setTimeout(previousText, 1000);
}

function previousText() {
  document.getElementById('button').innerHTML = 'Download file as CSV';
}
<button id="button" onclick='changeText()' value='Change Text'>Download file as CSV</button>
like image 92
Alex Char Avatar answered Sep 21 '22 04:09

Alex Char


document.getElementById("your-button").value="Downloading...";
setTimeout(function () { 
    document.getElementById("your-button").value="Download as CSV"; 
}, 3000);

The above code sets the button's text, and then waits 3 seconds and after that sets the button text to another string.

like image 34
Thomas Stringer Avatar answered Sep 20 '22 04:09

Thomas Stringer


This code will restore the old text after 2000ms, but you can customize the timeout.

function changeText() {
    var button = document.getElementById('button');

    var oldText = button.innerHTML;
    button.innerHTML = 'Downloading...';
    setTimeout(function(){
        button.innerHTML = oldText;
    }, 2000);
}
like image 42
Lorenzo Zottar Avatar answered Sep 22 '22 04:09

Lorenzo Zottar