'Javascript Text loop on click
I want to code in javascript that writes ten times the sentence “I know a bit of JavaScript” after clicking on a text within an <h1> tag. The code should use a for loop or a while loop and if statements. Must use a function to write the sentence.
Solution 1:[1]
I will not give you any code since this sounds like homework, but how about breaking the question down and googling every step of it.
Lets break it down:
Write ten times a sentace. Your code should use a loop. Lets check what the JavaScript docs say about while loops :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
Clicking on a text within an tag: Lets check what the JavaScript docs say about the click event: https://developer.mozilla.org/en-US/docs/Web/Events/click
You muse use a function to write the sentance Lets check what the JavaScript docs say about functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
So take it piece by piece. It doesn't have to to all the right things at once. Just break it down.
Try to make a while loop do something 10 times. Just to console.log('stuff') out. Just so that you see something happening 10 times.
Try to make a onClick event console.log('I got clicked'), just to make sure you have your event
Try to make a function do something.
When you have a function that does something, a loop that runs 10 times and an onClick event that fires then its just a matter of putting it all together.
Solution 2:[2]
This can be done by for loop:
const demoEl = document.querySelector('.demo')
const repeatElement = (repeatWord, repeatNumber) =>{
let total = ""
let error = false
let errorMessage = ""
if(repeatWord != null && repeatNumber != null){
error = false
for(let i = 0; i < repeatNumber; i++){
total += `${repeatWord}\n`;
}
}else{
error = true
errorMessage = "Please fill all perimeter."
return errorMessage
}
return total
}
// Calling Function
demoEl.addEventListener('click', ()=>{
console.log(repeatElement("I know a bit of JavaScript", 10))
})
<!doctype HTML>
<html>
<head>
<title>Stack Over Flow</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1 class="demo">DEMO</h1>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bergur |
| Solution 2 | Christian |
