If / Else-sats



Testa kodexemplet:

The engine is stopped.

Kodexempel

<button id="machineBtn" class="btn btn-primary mr-2">Start engine</button>
<span id="machineStatus" class="h5">The engine is stopped.</span>
<script>
// This example demonstrates how to toggle the state of a machine using a button
// The button text changes between "Start machine" and "Stop machine"

// Get DOM elements
const btn = document.querySelector("#machineBtn");
const txt = document.querySelector("#machineStatus");

// create my own eventhandler function updateBtn
// This function toggles the button text and status message
function updateBtn() {
    if (btn.textContent === "Start engine") {
        btn.textContent = "Stop engine";
        txt.textContent = "The engine has started!";
    } else {
        btn.textContent = "Start engine";
        txt.textContent = "The engine is stopped.";
    }
}

// Add an event listener to the button
// This listens for click events and calls the eventhandler, updateBtn, when clicked
btn.addEventListener("click", updateBtn);
</script>