Variables



Testa kodexemplet:


Kodexempel

<button id="button_A" class="btn btn-success mr-2">Like this BMW <span id="heading_A" class="badge bg-primary"></span></button>

<script>
// This example demonstrates how to create a button that counts the number of likes
// and updates the text of a heading element with the number of likes
        
// querySelector is used to select elements
// in this case a button with id "button_A" and a span with id "heading_A"
const buttonA = document.querySelector("#button_A");
const headingA = document.querySelector("#heading_A");

// countLikes is a variable that keeps track of the number of likes
// It is initialized to 1 and show "Number of likes 1" the first time user clicks the button.
let countLikes = 1;

//onclick has an event handler, an ananomuos function that is triggered when the button is clicked
buttonA.addEventListener("click", function() {    
    //The textContent property is used to set the text of the heading element
    //backticks are used to create a template literal
    // The ${countLikes} syntax is used to insert the value of the countLikes variable into the string
    headingA.textContent = `Number of likes ${countLikes}`;
    //countLikes is incremented by 1 each time the button is clicked
    countLikes += 1;
});

</script>