Cards

Soit les trois fichiers HTML, CSS et JS suivants.

1
<!DOCTYPE html>
2
<html lang="fr">
3
  <head>
4
    <meta charset="utf-8">
5
    <title>Exercice</title>
6
    <link rel="stylesheet" type="text/css" href="style.css">
7
    <script src="script.js" defer></script>
8
  </head>
9
  <body>
10
    <section class="cards"></section>
11
    <button id="add">Ajouter</button>
12
  </body>
13
</html>
14
1
.cards {
2
  display: flex;
3
  flex-wrap: wrap;
4
  justify-content: center;
5
  padding: 0 20px;
6
}
7
div {
8
  padding: 70px 50px;
9
  margin: 20px;
10
  border-radius: 5%;
11
  color: white;
12
  font-weight: bold;
13
}
14
.green {
15
  background: green;
16
}
17
.blue {
18
  background: blue;
19
}
20
.red {
21
  background: red;
22
}
23
.yellow {
24
  background: yellow;
25
}
26
button {
27
  background: white;
28
  border: solid 1px black;
29
  padding: 10px;
30
  border-radius: 10px;
31
}
32
1
// Add a card to the section
2
function add() {
3
  const colors = ["green", "red", "yellow", "blue"]
4
  const cards = document.querySelector(".cards");
5
  const num = Math.trunc(Math.random() * 9);
6
  const randomColor = Math.trunc(Math.random() * 4);
7
  const newCard = document.createElement("div");
8
  newCard.classList = colors[randomColor];
9
  newCard.innerText = num;
10
  newCard.addEventListener('click', hide)
11
  cards.appendChild(newCard);
12
}
13
14
// This lazy function does nothing
15
function hide() {
16
  // Empty function
17
}
18
19
// Call function add once to display first card
20
add()
21
22
// When button is clicked, function add is called
23
button = document.querySelector('#add')
24
button.addEventListener('click', add)
25

Question

Enregistrez et faites fonctionner ces fichiers.

Question

Modifier le code JavaScript afin de permettre d'effacer une carte lorsque l'on clique dessus.