Functions



Testa kodexemplet:


Kodexempel

<input type="text" id="yourname" placeholder="Input your name"><button id="helloBtn" class="btn btn-primary">Say Hello</button>
<p id="hellomessage" class="h5"></p>
<script>
// This example demonstrates how to convert a function to an arrow function 
// and how to use it to display a message when a button is clicked
//querySelector is used to select elements in this case a button with id "helloBtn"
// and a paragraph with id "hellomessage"
const btn = document.querySelector("#helloBtn");
const para = document.querySelector("#hellomessage");

// This is a regular function that displays a message
//in a paragraph element when called
function sayHello(name) {
  //use backticks to create a template literal 
  //textContent is used to set the text of the paragraph
  // The ${name} syntax is used to insert the value of the name variable into the string 
  para.textContent = `Hello, ${name}!`;;
}

// This is an arrow function that does the same thing as sayHello
// It is a shorter syntax for writing functions in JavaScript
//Compare the two functions and you see that the keyword "function" is removed and the arrow => is added
//It is called when the button is clicked 
const sayHelloArrow = (name) => {
  para.textContent = `Hello, ${name}!`;
};

// Add an event listener for click event on the button, it is an anonymous arrow function
//  listens for click events and calls the sayHelloArrow function
btn.addEventListener("click", () => {
  //focus is used to set the focus on the input field
  document.querySelector("#yourname").focus();
  //value is used to get user input from input field
  const yourName = document.querySelector("#yourname").value;    
  //call the arrow function sayHelloArrow with the yourName as argument
  sayHelloArrow(yourName);
});

</script>