← Niveau 2 : Magicien

Leçon 5 sur 8 ⏱ 35 minutes

Galerie photo avec visionneuse

Cliquer sur une photo la rend plus grande, remplissant tout l'écran. Tu vas apprendre à travailler avec un groupe d'éléments.

Comment ça va fonctionner

On va améliorer la galerie du Niveau 1 : cliquer sur une petite photo ouvre une grande version sur toute la page avec un fond sombre (ça s’appelle une lightbox). Cliquer à nouveau la ferme.

Montre-moi : la lightbox

HTML : ajoute une « fenêtre de zoom » sous la galerie (cachée au départ) :

<div class="gallery">
  <img src="images/p1.jpg" alt="First photo">
  <img src="images/p2.jpg" alt="Second photo">
  <img src="images/p3.jpg" alt="Third photo">
</div>

<div id="lightbox" class="hidden">
  <img id="lightbox-photo" src="" alt="">
</div>

CSS : une fenêtre couvrant tout l’écran :

#lightbox {
  position: fixed;          /* stuck over the whole window */
  inset: 0;                 /* 0 from every edge = the whole area */
  background-color: rgba(0, 0, 0, 0.85);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

#lightbox img {
  max-width: 90%;
  max-height: 90%;
}

.hidden {
  display: none !important; /* hide completely */
}

JavaScript : et maintenant quelque chose de nouveau : on travaille avec toutes les photos à la fois :

const photos = document.querySelectorAll(".gallery img");
const lightbox = document.getElementById("lightbox");
const lightboxPhoto = document.getElementById("lightbox-photo");

// For every photo in the gallery: show it big on click
photos.forEach((photo) => {
  photo.addEventListener("click", () => {
    lightboxPhoto.src = photo.src;
    lightboxPhoto.alt = photo.alt;
    lightbox.classList.remove("hidden");
  });
});

// Clicking anywhere in the lightbox closes it
lightbox.addEventListener("click", () => {
  lightbox.classList.add("hidden");
});

Nouveautés :

À toi 💪

  1. Ajoute une lightbox à ton site web en suivant l’exemple. Tu as déjà une galerie du Niveau 1 : assure-toi juste que le sélecteur (.gallery img) correspond à tes classes.
  2. Une amélioration pour les courageux : navigation avec les flèches :
Bonus : naviguer vers la photo suivante/précédente

Extension du script : on se souvient quelle photo est ouverte :

const photos = document.querySelectorAll(".gallery img");
const lightbox = document.getElementById("lightbox");
const lightboxPhoto = document.getElementById("lightbox-photo");
let current = 0;

function showPhoto(number) {
  // Handle wraparound: after the last photo comes the first again
  if (number < 0) number = photos.length - 1;
  if (number >= photos.length) number = 0;

  current = number;
  lightboxPhoto.src = photos[current].src;
  lightboxPhoto.alt = photos[current].alt;
}

photos.forEach((photo, index) => {
  photo.addEventListener("click", () => {
    showPhoto(index);
    lightbox.classList.remove("hidden");
  });
});

lightbox.addEventListener("click", () => {
  lightbox.classList.add("hidden");
});

// Navigate with the keyboard
document.addEventListener("keydown", (event) => {
  if (lightbox.classList.contains("hidden")) return;

  if (event.key === "ArrowRight") showPhoto(current + 1);
  if (event.key === "ArrowLeft") showPhoto(current - 1);
  if (event.key === "Escape") lightbox.classList.add("hidden");
});

Deux nouveautés de plus : function showPhoto(number) {...} est une fonction nommée : un paquet de code que tu peux exécuter de n’importe où par son nom. Et photos[current] tire un élément d’une liste par sa position (le comptage commence à zéro !).

Idées de projet : 🏫 photos d’événements scolaires · 🙋 tes créations et aventures · 🌍 photos de voyages (c’est là que la lightbox brille vraiment !) · ⚽ moments de matchs.

✅

Vérifie : Tu cliques sur une photo → elle grandit sur un fond sombre. Tu cliques à nouveau → elle se ferme. Avec le bonus, tu peux aussi naviguer avec les flèches et fermer avec Échap. C’est exactement comme les galeries sur les sites web professionnels, et maintenant tu sais ce qu’il y a dedans.

Ce que tu retiens de cette leçon