Javascript Games!
%%html
<button id="myButton">Click Me</button>
<p id="result"></p>
<p id="timer"></p>
%%js
var count = 0;
var button = document.getElementById("myButton");
var result = document.getElementById("result");
button.onclick = function() {
count++;
result.innerHTML = count;
}
%%html
<h2>Color: <span class="color"></span></h2>
<button id="btn">Flip</button>
%%js
//array of colors
const colors = ["Yellow", "Brown", "Green", "Red", "Blue", "Purple", "Turquoise"];
const btn = document.getElementById("btn");
//querySelector returns element that matches the selector
const select = document.querySelector(".color");
btn.addEventListener("click", function () {
//generates random number
const randomNumber = getRandomNumber();
//changes background to random index selected inside colors array
document.body.style.backgroundColor = colors[randomNumber];
select.textContent = colors[randomNumber];
});
//random number generator
function getRandomNumber() {
return Math.floor(Math.random() * colors.length);
}
%%html
<button class="btn">New Dad Joke!</button>
<p class="result">Dad jokes...</p>
%%js
//url of the dad joke api
const url = 'https://icanhazdadjoke.com/';
const btn = document.querySelector('.btn');
const result = document.querySelector('.result');
//waiting on button click
btn.addEventListener('click', () => {
fetchDadJoke();
});
//fetches dad joke
const fetchDadJoke = async () => {
result.textContent = 'Loading...';
try {
const response = await fetch(url, {
headers: {
Accept: 'application/json',
'User-Agent': 'learning app',
},
});
if (!response.ok) {
throw new Error(' error');
}
const data = await response.json();
result.textContent = data.joke;
} catch (error) {
console.log(error.message);
result.textContent = 'There was an error...';
}
};
fetchDadJoke();