简体   繁体   中英

Javascript InnerHTML display for two seconds

Okay so I've looked over previous similar questions and I'm not quite getting the answer. I have the below function that will display nicely but I want the display to end after two seconds. The second function was aa little experiment but delays the response for two seconds rather than displaying for two seconds. Any help would be great.

var j = 0;
function buttonClick() {
    text = ++j + " added to cart"
    document.getElementById('rope111').innerHTML = text;
}



var j = 0;
function buttonClick() {
    text = ++j + " added to cart"
    setTimeout(function(){document.getElementById('rope111').innerHTML = text}, 2000);
}

This should work:

var j = 0;
function buttonClick() {
    text = ++j + " added to cart";
    // First, we display the text with the statement below.
    document.getElementById('rope111').innerHTML = text;
    setTimeout(function() {
        // Then we remove the text after 2 seconds.
        document.getElementById('rope111').innerHTML = "";
    }, 2000);
}

You can also replace the statement in setTimeout function with:

document.getElementById('rope111').style.display = "none";

You are almost there. As you found that

var j = 0; function buttonClick() { text = ++j + " added to cart"; document.getElementById('rope111').innerHTML = text; }

does what you want at the beginning ( text appears, immediately), instead of reorganizing it randomly, you should just leave it in place nad add the new functionality to its end, without breaking what you already have:

var j = 0;
function buttonClick() {
    text = ++j + " added to cart";
    document.getElementById('rope111').innerHTML = text;

    setTimeout(function(){document.getElementById('rope111').innerHTML = ""}, 2000);
}

(as you want text to disappear, you'll need an empty string "" , but otherwise the new line comes from your snippets too)

let j = 0;
function buttonClick() {
    text = ++j + " added to cart";
    const elem = document.getElementById('rope111');
    elem.innerHTML = text;

    setTimeout(() => {
        elem.innerHTML = "";
    }, 2000);
}

 const emptyString = "" const timeShown = 2000 // 2s const addedToCartText = "added to cart" let j = 0; function buttonClick() { document.getElementById('rope111').innerHTML = `${++j} ${addedToCartText}`; setTimeout(() => { document.getElementById('rope111').innerHTML = emptyString }, timeShown) }
 <button onclick="buttonClick()">Button</button> <div id="rope111" />

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM