简体   繁体   中英

How to display elements after button has been clicked?

I am creating a timer app, and when I click the start button I have the timer starting, but I want it to display the pause and play buttons. Pretty much I'm trying to do the reverse of what I did with the start button.

I have already tried setting it to

middlebuttons.style.display= "block"

but that doesn't work.

Javascript

var startButton = document.getElementById("start");
var startSound = document.getElementById("audio"); 
var timerSound = document.getElementById("timer");
var counter = document.getElementById("counter");
var middlebuttons = document.getElementsByClassName("middlebuttons");
function playAudio(){
    startSound.play();
}

// Start button will disappear after click and countDown method will begin
function startTimer(){
    startButton.style.display="none"; 
    middlebuttons.style.display = "block";
    countDown(1);    
}

startButton.addEventListener('click', startTimer, playAudio);

HTML

 <div class="container">
        <div class="buttons">
                <button id ="start" type="button" onclick="playAudio()">Start</button>
                <audio id="audio">
                    <source src="clicksound.wav" type="audio/ogg "> 
                </audio>
                <audio id="timer">
                    <source src="gong.mp3" type="audio/ogg "> 
                </audio>
        </div>
        <div id="counter">

        </div>
        <div class="middlebuttons" style="display: none">
            <div class="row mr-3">
                <button id="pause" >
                    <i class="fas fa-pause" style="font-size: 40px"></i>
                </button>
                <button id="play">
                    <i class="fas fa-play" style="font-size: 40px"></i>
                </button>

            </div>
        </div>

    </div>

middlebuttons is a HTMLCollection (like an array) so you need to loop through it and apply the styles to each element:

[...middlebuttons].forEach(button => button.style.display = "block");

Older browsers:

Array.prototype.slice.call(middlebuttons).forEach(function(button) {
    button.style.display = "block";
});

Also on older browsers (thanks connexo):

Array.prototype.forEach.call(middlebuttons, function(button) {
    button.style.display = "block";
});

You should iterate over the buttons and update the display property for each button :

for (var i = 0; i < middlebuttons.length; i++) {
  middlebuttons[i].style.display = "block";
}

// or

middlebuttons.forEach(function(btn) {
  btn.style.display = "block";
});

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