-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day7 - Character Count.html
53 lines (44 loc) · 2 KB
/
Day7 - Character Count.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
padding: 5vh 5vw 5vh 5vw;
}
textarea {
display: block;
}
</style>
</head>
<body>
<label for="text">Enter your text below.</label>
<textarea id="text" character-count-id="#character-count"></textarea>
<p>You've written <strong><span id="character-count">0</span> characters</strong>.</p>
<script>
//I - A way for changing character count value in one element
/* const textField = document.querySelector("#text"); //getting textarea filed
const characterCount = document.querySelector("#character-count"); //getting the span with the number of char.
document.addEventListener("input", function () {
//inserting the number of characters that a user typed in the textarea into the displaying element's text content
characterCount.textContent = textField.textLength;;
})
*/
//II - A way for changing character count value in multiple elements
//getting textarea fields
const textFields = Array.prototype.slice.call(document.querySelectorAll("textarea"));
// input event - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
document.addEventListener("input", function () {
//looping through all textarea fields
for (let i = 0; i < textFields.length; i++) {
//getting the element that displays the number of characters in the current textarea
const characterCount = document.querySelector(textFields[i].getAttribute("character-count-id"));
//inserting the number of characters that a user typed in the textarea into the displaying element's text content
characterCount.textContent = textFields[i].textLength;
}
})
</script>
</body>
</html>