Zo kan de gebruiken interactief JavaScript gedrag laten uitvoeren!
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
functionsayHello(){
alert("Hello world");
}
function sayHello() {
alert("Hello world");
}
function sayHello() {
alert("Hello world");
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<buttononclick="sayHello()">Click to Say Hello</button>
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<button onclick="sayHello()">Click to Say Hello</button>
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<button onclick="sayHello()">Click to Say Hello</button>
👩💻 Hands-on Demo: Hello World functie met Knopje
In jouw hello-js project, in jouw my-script.js bestand, verwijder wat er al stond en schrijf een functie die “Hello world” als alert melding toont aan de gebruiker.
Hint:
functionsayHello()
function sayHello()
In het index.html bestand, maak een knop aan die reageert op een klik van de gebruiker en die de
sayHello()
sayHello() functie uitvoert.
Hint:
onclick="sayHello"
onclick="sayHello"
Probeer het uit door op de knop te klikken.
Maak jouw knopje mooier aan de hand van Bootstrap zoals in het voorbeeld (je mag het altijd zelf aanpassen met jouw eigen CSS als je wil).
Wat gebeurt er als je
console.log()
console.log() gebruikt in plaats van
alert()
alert()?
Oplossingen
🕵️♂️ Klik hier om de oplossingen te tonen
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<buttonclass="btn btn-primary"onclick="sayHello()">Click to Say Hello</button>
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<button class="btn btn-primary" onclick="sayHello()">Click to Say Hello</button>
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<button class="btn btn-primary" onclick="sayHello()">Click to Say Hello</button>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
functionsayHello(){
alert("Hello world");
}
function sayHello() {
alert("Hello world");
}
function sayHello() {
alert("Hello world");
}
Variabelen
Je kan waarden tijdelijk opslaan in variabelen om verder en meermaals doorheen jouw code te hergebruiken
Dit doe je met sleutelwoord
let
let, gevolgd door een naam die je verzint, en vervolgens ken je een waarde toe.
Je kan ook
const
const gebruiken als wilt dat de waarde nooit mag overschreven worden.
Online vind je af en toe
var
var maar dit is al een tijdje volledig verouderd en niet meer good practice (want hoisting is een nachtmerrie).
PS: Net zoals je de functie
alert()
alert() hebt om een bericht naar de gebruiker te sturen, kan je ook met de functie
prompt()
prompt() input van de gebruiker aanvaarden (zie voorbeeld).
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let a = 2;
let b = 3;
let result = a + b;
console.log(result);
let a = 2;
let b = 3;
let result = a + b;
console.log(result);
let a = 2;
let b = 3;
let result = a + b;
console.log(result);
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let firstName = "James";
let lastName = "Barnes";
let fullName = firstName + " " + lastName;
console.log(fullName);
let firstName = "James";
let lastName = "Barnes";
let fullName = firstName + " " + lastName;
console.log(fullName);
let firstName = "James";
let lastName = "Barnes";
let fullName = firstName + " " + lastName;
console.log(fullName);
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let firstName = prompt("Enter your first name:");
let lastName = prompt("Enter your first name:");
let fullName = firstName + " " + lastName;
console.log(fullName);
let firstName = prompt("Enter your first name:");
let lastName = prompt("Enter your first name:");
let fullName = firstName + " " + lastName;
console.log(fullName);
let firstName = prompt("Enter your first name:");
let lastName = prompt("Enter your first name:");
let fullName = firstName + " " + lastName;
console.log(fullName);
👩💻 Hands-on Demo: Interactiviteit met prompt() en Variabelen!
Say Hello
In jouw hello-js project, in jouw my-script.js bestand, pas jouw
sayHello()
sayHello() functie aan zodanig dat je de gebruiker achter een voornaam en achternaam vraagt, en vervolgens antwoordt met een gepersonaliseerde begroeting via een alert melding.
Probeer het uit door op de knop te klikken.
BMI Score
Schrijf een
calcBmi()
calcBmi() functie aan die de gebruiker vraagt achter een gewicht (kg) en lengte (m) en vervolgens een BMI score weergeeft in een alert melding.
Hoe bereken je BMI? Wat is de formule? Google-Fu!
Maak een nieuw knopje aan die, eens op geklikt, de
calcBmi()
calcBmi() functie uitvoert (zie voorbeeld).
Probeer het uit door op de knop te klikken.
(Extra) Zoek een manier om de BMI score af te ronden naar 1 cijfer na de komma.
Oplossingen
🕵️♂️ Klik hier om de oplossingen te tonen
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<h2>Say Hello</h2>
<buttonclass="btn btn-primary"onclick="sayHello()">Click to Say Hello</button>
<h2>BMI Score</h2>
<buttonclass="btn btn-secondary"onclick="calcBmi()">Calculate Your BMI</button>
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<h2>Say Hello</h2>
<button class="btn btn-primary" onclick="sayHello()">Click to Say Hello</button>
<h2>BMI Score</h2>
<button class="btn btn-secondary" onclick="calcBmi()">Calculate Your BMI</button>
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<h2>Say Hello</h2>
<button class="btn btn-primary" onclick="sayHello()">Click to Say Hello</button>
<h2>BMI Score</h2>
<button class="btn btn-secondary" onclick="calcBmi()">Calculate Your BMI</button>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
functionsayHello(){
let firstName = prompt("Enter first name:");
let lastName = prompt("Enter last name:");
let fullName = firstName + " " + lastName;
alert("Hello " + fullName);
}
functioncalcBmi(){
let weight = prompt("Enter weight (kg):");
let height = prompt("Enter weight (m):");
let bmi = weight / (height * height);
alert("Your BMI score is: " + bmi);
}
function sayHello() {
let firstName = prompt("Enter first name:");
let lastName = prompt("Enter last name:");
let fullName = firstName + " " + lastName;
alert("Hello " + fullName);
}
function calcBmi() {
let weight = prompt("Enter weight (kg):");
let height = prompt("Enter weight (m):");
let bmi = weight / (height * height);
alert("Your BMI score is: " + bmi);
}
function sayHello() {
let firstName = prompt("Enter first name:");
let lastName = prompt("Enter last name:");
let fullName = firstName + " " + lastName;
alert("Hello " + fullName);
}
function calcBmi() {
let weight = prompt("Enter weight (kg):");
let height = prompt("Enter weight (m):");
let bmi = weight / (height * height);
alert("Your BMI score is: " + bmi);
}
If-else
Voorwaardelijke statement.
Sleutelwoord if met de vraag (of voorwaarde) tussen ronde haakjes
bv.
if(isAllergic)
if(isAllergic)
Enkel als het antwoord op de vraag “Ja” (true) is wordt iets uitgevoerd.
Met else kan je ook en “Zoniet, doe dan dat” tak definieren.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let age = 17;
if(age >= 18){
console.log('Adult');
}else{
console.log('Child');
}
let age = 17;
if (age >= 18) {
console.log('Adult');
} else {
console.log('Child');
}
let age = 17;
if (age >= 18) {
console.log('Adult');
} else {
console.log('Child');
}
👩💻 Hands-on Demo: Voorwaardelijke statements met If-else
Age Checker
In jouw hello-js project, in jouw my-script.js bestand, maak een
checkAge()
checkAge() functie aan zodanig dat je de gebruiker achter een leeftijd vraagt, en vervolgens antwoordt met een geschikte bericht als ze volwassen zijn of niet (zie voorbeeld) via een alert melding.
Als de leeftijd groter dan of gelijk aan 18 is, doe je een alert over bier drinken.
Anders bereken je het verschil (aantal jaren te gaan voor de gebruiker 18 is) en doe je een alert over melk drinken met het verschil geprint.
Probeer het uit door op de knop te klikken.
Favoritisme
Pas jouw
sayHello()
sayHello() functie aan zodanig dat als de gebruiker jouw naam intypt dat die een speciale, leuke begroeting krijgt, maar al de rest krijgt de gewone begroeting.
Als de naam gelijk is aan de favoriete naam (hint: gebruik
==
== om gelijkenis te vergelijken) dan wordt er een super speciale begroeting via een alert getoond.
Anders wordt de gewone begroeting van daarvoor via een alert getoond.
Probeer het uit door op de knop te klikken.
BMI Score met Medisch Advies
Pas jouw
calcBmi()
calcBmi() functie zodanig dat je, afhankelijk van BMI score, de gebruiker een diagnose/categorie kan geven.
Als de BMI score kleiner dan 18.5 is, dan is de categorie “underweight”.
Anders als de BMI score kleiner dan 25 is, dan is de categorie “normal weight”.
Anders als de BMI score kleiner dan 30 is, dan is de categorie “overweight”.
Anders is de categorie “obese”.
Pas de alert-melding zodanig dat deze niet alleen de BMI score maar ook de categorie meegeeft (zie voorbeeld).
Probeer het uit door op de knop te klikken.
Rock Paper Scissors
Maak een nieuwe
playRps(userChoice)
playRps(userChoice) functie aan die, aan de hand van if-else-if-else, bepaalt of de gebruiker wint of verliest volgens de steen, papier, schaar regels.
Om te beginnen gaan we ervan uit dat de computer altijd voor steen kiest, zo houden we het voorlopig simpel.
Als de gebruiker keuze identiek is aan de computer keuze dan is het resultaat “It’s a tie!”.
Anders als de gebruiker steen kiest en de computer keuze schaar is, OF de gebruiker papier kiest en de computer keuze steen is, OF de gebruiker schaar kiest en de computer papier kiest, dan is het resultaat “You win!”.
Anders is het resultaat “You lose!”.
Toon telkens eerst wat de keuzes waren, vooraleer je een resultaat bepaalt (zie voorbeeld).
Probeer het uit door op de knop te klikken.
(Extra) Maak het dynamischer door de computer een willekeurige keuze tussen “rock”, “paper” en “scissors” te maken.
Oplossingen
🕵️♂️ Klik hier om de oplossingen te tonen
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<h1>Hello JavaScript</h1>
<p>Showcasing some basic JavaScript functionality</p>
<h2>Say Hello</h2>
<buttonclass="btn btn-primary"onclick="sayHello()">Click to Say Hello</button>
<h2>BMI Score</h2>
<buttonclass="btn btn-secondary"onclick="calcBmi()">Calculate Your BMI</button>
<h2>Age checker</h2>
<buttonclass="btn btn-success"onclick="checkAge()">Have a Drink</button>
function sayHello() {
let firstName = prompt("Enter first name:");
let lastName = prompt("Enter last name:");
let fullName = firstName + " " + lastName;
if (fullName == "James Barnes") {
alert("Welcome back, master " + lastName + "😎 Lookin' good today!");
} else {
alert("Hello " + fullName);
}
}
function calcBmi() {
let weight = prompt("Enter weight (kg):");
let height = prompt("Enter height (m):");
let bmi = weight / (height * height);
let category;
if (bmi < 18.5) {
category = "underweight";
} else if (bmi < 25) {
category = "normal weight";
} else if (bmi < 30) {
category = "overweight";
} else {
category = "obese";
}
alert("You are " + category + " (BMI score: " + bmi + ")");
}
function checkAge() {
let age = prompt("Enter age: ");
if (age >= 18) {
alert("Have a beer on us 🍺")
} else {
let difference = 18 - age;
alert("You're too young. Still " + difference + " years to go! Have a glass of milk 🥛!")
}
}
function playRps(userChoice) {
let computerChoice = "rock";
alert("You: " + userChoice + " vs. Computer: " + computerChoice);
if (userChoice == computerChoice) {
alert("It's a tie!");
} else if (
(userChoice == "rock" && computerChoice == "scissors") ||
(userChoice == "paper" && computerChoice == "rock") ||
(userChoice == "scissors" && computerChoice == "paper")
) {
alert("You win!");
} else {
alert("You lose!")
}
}
function sayHello() {
let firstName = prompt("Enter first name:");
let lastName = prompt("Enter last name:");
let fullName = firstName + " " + lastName;
if (fullName == "James Barnes") {
alert("Welcome back, master " + lastName + "😎 Lookin' good today!");
} else {
alert("Hello " + fullName);
}
}
function calcBmi() {
let weight = prompt("Enter weight (kg):");
let height = prompt("Enter height (m):");
let bmi = weight / (height * height);
let category;
if (bmi < 18.5) {
category = "underweight";
} else if (bmi < 25) {
category = "normal weight";
} else if (bmi < 30) {
category = "overweight";
} else {
category = "obese";
}
alert("You are " + category + " (BMI score: " + bmi + ")");
}
function checkAge() {
let age = prompt("Enter age: ");
if (age >= 18) {
alert("Have a beer on us 🍺")
} else {
let difference = 18 - age;
alert("You're too young. Still " + difference + " years to go! Have a glass of milk 🥛!")
}
}
function playRps(userChoice) {
let computerChoice = "rock";
alert("You: " + userChoice + " vs. Computer: " + computerChoice);
if (userChoice == computerChoice) {
alert("It's a tie!");
} else if (
(userChoice == "rock" && computerChoice == "scissors") ||
(userChoice == "paper" && computerChoice == "rock") ||
(userChoice == "scissors" && computerChoice == "paper")
) {
alert("You win!");
} else {
alert("You lose!")
}
}
While
Herhalende statement
Loops.
Je springt terug naar boven.
Codeblok blijft herhalen zolang conditie waar is.
Lijkt op “if” (condition, voorwaarde, vraag), maar dan met herhaling.
Handig voor dingen te herhalen.
Handig om gebruiker in limbo te houden zolang invoer ongeldig is.
Handig voor optellingen.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let password = "123";
let input = prompt("Enter password:");
while(input != password){
alert("🚫Wrong password! Try again...");
input = prompt("Enter password:");
}
alert("✅ Success! Welcome! Here are your e-mails...");
let password = "123";
let input = prompt("Enter password:");
while (input != password) {
alert("🚫Wrong password! Try again...");
input = prompt("Enter password:");
}
alert("✅ Success! Welcome! Here are your e-mails...");
let password = "123";
let input = prompt("Enter password:");
while (input != password) {
alert("🚫Wrong password! Try again...");
input = prompt("Enter password:");
}
alert("✅ Success! Welcome! Here are your e-mails...");
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Say "Hello world" 42 times
count = 1;
while(count <= 42){
console.log("Hello world");
count++;
}
// Say "Hello world" 42 times
count = 1;
while (count <= 42) {
console.log("Hello world");
count++;
}
// Say "Hello world" 42 times
count = 1;
while (count <= 42) {
console.log("Hello world");
count++;
}
👩💻 Hands-on Demo: Herhalende statements met while
Password-protected e-mails
Schrijf een
checkEmail()
checkEmail() functie die een wachtwoord opslaat in een variabele, en die de gebruiker vraagt om een wachtwoord in te voeren.
Sla eerst het wachtwoord op in een variabele.
Vraag vervolgens aan de gebruiker om een wachtwoord in te typen.
Zolang dat deze niet overeenkomt met het wachtwoord, wordt er een foutmelding getoond en wordt de vraag opnieuw gesteld (gebruik een while-lus).
Eens we uit de while-lus ontsnappen, wordt er een succes-bericht getoond via alert (zie voorbeeld).
Maak een nieuw knopje aan die, eens op geklikt, de
checkEmail()
checkEmail() functie uitvoert (zie voorbeeld).
Probeer het uit door op de knop te klikken.
Push Ups
Schrijf een
doPushUps(amount)
doPushUps(amount) functie die een telt vanaf 1 tot en met de hoeveelheid die is meegegeven, en print telkens in de console over push-ups (zie voorbeeld).
Maak eerst een teller aan.
Deze dient om bij te houden de hoeveelste lus het is telkens met 1 te verhogen na elke lus.
Concreet: maak een variabele aan (bv. met naam count) en steek daar de waarde 1 in, en zorg straks in de while-lus dat je deze teller met 1 verhoogt.
Zolang dat de teller kleiner of gelijk aan de meegegeven hoeveelheid (amount) is blijven we herhalen:
Er wordt eerst en vooral in de console een boodschap getoond over de hoeveelste push-up het is (zie voorbeeld).
Vervolgens wordt er op de teller bijgeteld (count++).
Maak een nieuw knopje aan die, eens op geklikt, de
doPushUps()
doPushUps() functie uitvoert, en geef 100 als argument mee (hint: tussen de ronde haakjes).
Probeer het uit door op de knop te klikken en de console te bekijken.
<h2>Check my private e-mails</h2>
<button class="btn btn-dark" onclick="checkInbox()">Check Inbox 📧</button>
<h2>Fitness</h2>
<p>Check the console to see how many push ups I did</p>
<button class="btn btn-warning" onclick="doPushUps(100)">Do 100 Push-ups💪</button>
<h2>Check my private e-mails</h2>
<button class="btn btn-dark" onclick="checkInbox()">Check Inbox 📧</button>
<h2>Fitness</h2>
<p>Check the console to see how many push ups I did</p>
<button class="btn btn-warning" onclick="doPushUps(100)">Do 100 Push-ups💪</button>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
functioncheckInbox(){
let password = "123";
let input = prompt("Enter password:");
while(input != password){
alert("🚫Wrong password! Try again...");
input = prompt("Enter password:");
}
alert("✅ Success! Welcome! Here are your e-mails...");
}
functiondoPushUps(amount){
count = 1;
while(count <= amount){
console.log("Push-up #" + count);
count++;
}
}
function checkInbox() {
let password = "123";
let input = prompt("Enter password:");
while (input != password) {
alert("🚫Wrong password! Try again...");
input = prompt("Enter password:");
}
alert("✅ Success! Welcome! Here are your e-mails...");
}
function doPushUps(amount) {
count = 1;
while (count <= amount) {
console.log("Push-up #" + count);
count++;
}
}
function checkInbox() {
let password = "123";
let input = prompt("Enter password:");
while (input != password) {
alert("🚫Wrong password! Try again...");
input = prompt("Enter password:");
}
alert("✅ Success! Welcome! Here are your e-mails...");
}
function doPushUps(amount) {
count = 1;
while (count <= amount) {
console.log("Push-up #" + count);
count++;
}
}
We gebruiken cookies op onze website om u de meest relevante ervaring te bieden door uw voorkeuren en herhaalde bezoeken te onthouden. Door op "Alles accepteren" te klikken, stemt u in met het gebruik van ALLE cookies. U kunt echter "Cookie-instellingen" bezoeken om een gecontroleerde toestemming te geven.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the ...
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duur
Beschrijving
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.