How to enable a button only after another button is selected first?

I’d like the ‘start’ button not to be available/enabled until the ‘display’ button is first selected. Any help with that is appreciated. Here’s the html:

	<button id="display" onclick="display()">Camera View</button>
	<button id="start" onclick="startRecording()">Record Video</button>
	<button id="stop" onclick="endRecording()">Stop Recording</button>

Here’s the js:

        let blobs = [];
        let stream, mediaRecorder, blob;
        let video = document.getElementById("video");
        var displaying = false;
        var recording = false;
        async function display() {
            stream = await navigator.mediaDevices.getUserMedia({
                audio: true,
                video: true,
            });
            video.srcObject = stream;
            displaying = true;
        }
        async function startRecording() {
            if (displaying) {
                // Stop all tracks of current stream
                stream.getTracks().forEach((track) => {
                    track.stop();
                });
                // Create new stream in order to start the timestamp from 0:
                stream = await navigator.mediaDevices.getUserMedia({
                    audio: true,
                    video: true,
                });
                // Switch on controls:
                video.setAttribute('controls', true);
                video.srcObject = stream;
                mediaRecorder = new MediaRecorder(stream);
                mediaRecorder.ondataavailable = (event) => {
                    if (event.data) {
                        blobs.push(event.data);
                    }
                };
                mediaRecorder.onstop = doPreview;
                // Let's receive 1 second blobs
                mediaRecorder.start(1000);
                recording = true;
            }
        }
        function endRecording() {
            if (recording) {
                // Let's stop capture and recording
                mediaRecorder.stop();
                stream.getTracks().forEach((track) => track.stop());
                recording = false;
            }
        }

As disabled is the default state for the start button, use the disabled HTML attribute on the button:

<button id="start" onclick="startRecording()" disabled>Record Video</button>

The somewhere in the display() code remove that disabled attribute.

document.querySelector("#start").removeAttribute("disabled");

Thanks again for your reply, however I don’t understand this:
“The somewhere in the display() code remove that disabled attribute.”


document.querySelector("#start").removeAttribute("disabled");

any clarification is welcomed

Usually putting it at the start of the function or the end of the function is done. I would put it at the end of the function.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.