Rechercher

Un sommaire auto en JS

Placeholder image

Créer un sommaire automatique pour vos pages en JS :

  • Mettre une div pour recevoir le code généré par le JS
  • Choisir dans quelle div vous souhaitez chercher vos titres
function generateSlug(text) {
    return text.normalize("NFD")
                .replace(/[\u0300-\u036f]/g, "")
                .toLowerCase()
                .replace(/[^\w\s]/g, '')
                .replace(/\s+/g, '-');
}

// Fonction pour créer la table des matières
function createTableOfContents() {
    // Sélectionner tous les titres de niveau 2 dans la div page-body
    const pageBody = document.querySelector('.page-body');
    const headings = pageBody.querySelectorAll('h2');

    // Sélectionner la div #toc et la liste UL où insérer les liens
    const toc = document.querySelector('#toc ul');

    // Parcourir tous les <h2>
    headings.forEach((heading, index) => {
        // Générer une slug (ID) à partir du texte du titre
        const headingText = heading.textContent;
        const slug = generateSlug(headingText);

        // Ajouter une ID au titre <h2> avec la slug générée
        heading.id = slug;

        // Créer un élément <li> pour la table des matières
        const listItem = document.createElement('li');
        
        // Créer un lien <a> qui pointe vers le titre avec l'ID
        const link = document.createElement('a');
        link.href = `#${slug}`;
        link.textContent = headingText;

        // Ajouter le lien à l'élément <li>
        listItem.appendChild(link);

        // Ajouter l'élément <li> à la table des matières (dans l'ul)
        toc.appendChild(listItem);
    });
}

// Appeler la fonction pour créer la table des matières
createTableOfContents();

Déterminer le sens du scroll (up or down)

Placeholder image
var scrollText = document.getElementById('scroll');
var lastScrollTop = 0;
var ticking = false;

function handleScroll() {
    var st = window.scrollY || document.documentElement.scrollTop;
    if (st > lastScrollTop) {
        scrollText.innerText = 'Scroll Down';
    } else {
        scrollText.innerText = 'Scroll Up';
    }
    lastScrollTop = Math.max(st, 0); // Éviter des valeurs négatives pour le scroll
}

window.addEventListener("scroll", function() {
    if (!ticking) {
        window.requestAnimationFrame(function() {
            handleScroll();
            ticking = false;
        });
        ticking = true;
    }
});

Une liste déroulante personnalisée en JS + CSS

Placeholder image

Personnaliser le style d’un selecteur avec un peu de JS et de CSS.

const selectsContainers =  document.querySelectorAll('.select-container');
const selects = document.querySelectorAll('select');
const change = new Event("change");
// create the links & anchors
if(selects.length > 0) {
  document.addEventListener("DOMContentLoaded", function() {
      for (var i = 0; i < selectsContainers.length; i++) {
        let childrens = selects[i].children;
        let dropdown  = document.createElement('div');
        dropdown.setAttribute('id', 'select-' + selects[i].getAttribute('id'));
        dropdown.setAttribute('class', 'select-stylized');
        let dropdownSelected = document.createElement('span');
        dropdownSelected.setAttribute('id', 'selected-' + selects[i].getAttribute('id'));
        dropdownSelected.setAttribute('class', 'empty');
        dropdownSelected.innerText = childrens[0].innerText;
        dropdown.appendChild(dropdownSelected);
        let dropdownUl = document.createElement('ul');
        for (var j = 1; j < childrens.length; j++) {
          let option = document.createElement('li');
          option.innerText = childrens[j].innerText;
          option.setAttribute('data-value', childrens[j].getAttribute('value'));
          option.setAttribute('data-select', selects[i].getAttribute('id'));
          option.addEventListener("click", function() {
            document.getElementById(option.getAttribute('data-select')).value =  option.getAttribute('data-value');
            document.getElementById(option.getAttribute('data-select')).dispatchEvent(change);
            document.getElementById('selected-' + option.getAttribute('data-select')).innerText = option.getAttribute('data-value');
            document.getElementById('selected-' + option.getAttribute('data-select')).classList.remove("empty");
          })
          dropdownUl.appendChild(option);
        }
        dropdown.appendChild(dropdownUl);
        dropdown.addEventListener("click", function() {
          dropdown.classList.toggle('open');
          let selectsOpen = document.querySelectorAll('.select-stylized.open');
          for (var h = 0; h < selectsOpen.length; h++) {
            if(selectsOpen[h] != dropdown ) {
              selectsOpen[h].classList.remove('open');
            }
          }
        })
        selectsContainers[i].insertBefore(dropdown, selects[i]);
      }
  });
}

Récupérer la largeur de la scrollbar

Placeholder image

Permet d’avoir une variable CSS contenant la largeur de la scrollbar

const scrollbarWidth = window.innerWidth - document.body.clientWidth;
const halfScrollbarWidth = scrollbarWidth / 2;
document.documentElement.style.setProperty('--scrollbar-width', scrollbarWidth + 'px');
document.documentElement.style.setProperty('--half-scrollbar-width', halfScrollbarWidth + 'px');

Un acordéon simple avec une checkbox

Placeholder image

Un accordéon tout simple avec du JS sans library.

function accordionToggler(el) {
			let checkeds = document.querySelectorAll(`input[name="${el.target.name}"]`);
			 for (var i = 0; i < checkeds.length; i++) {
			  	if(checkeds[i].id != el.target.id) {
			  		checkeds[i].checked = false;
			  	}
			 }
		}
.accordion {
  position: relative;
}

.accordion input {
  position: absolute;
  top: 0;
  opacity: 0;
  z-index: -1;
}

.accordion label {
  display: block;
  margin-bottom: 10px;
  padding-bottom: 6px;
  font-weight: bold;
  border-bottom: 1px solid var(--purple-light);
}

.accordion div p {
  margin-top: 20px;
}

.accordion div p span {
  text-transform: uppercase;
    display: inline-block;
    padding-top: 9px;
}

.accordion div {
  max-height: 0px;
  overflow: hidden;
  transition: max-height ease-in 0.6s;
}

.accordion input:checked + label + div {
  max-height: 600px;
}

Fenêtre modale

Placeholder image

Une fenêtre modale simple avec un peu de JS et pas de librarie.

<script>
  function openModal(id) {
    let modal = document.getElementById(id);
    modal.classList.add('animate-modal');
    setTimeout(function(){ modal.classList.add('animated-modal'); modal.classList.remove('animate-modal'); }, 400);
  }
  
  function closeModal(id) {
    let modal = document.getElementById(id);
    modal.classList.add('animate-out-modal');
    modal.classList.remove('animated-modal');
    setTimeout(function(){  modal.classList.remove('animate-out-modal'); }, 400);
  }
</script>
<style>
  /* ===================================================================*/
  /* ============================= MODAL ============================ */
  /* ===================================================================*/

  .modal-mahii {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: rgba(31,32,38,.7);
    z-index: 99;
  }
  .modal-mahii-content {
      position: fixed;
      top: 10vh;
      left: 50%;
      transform: translateX(-50%);
      width: 600px;
      max-width: 95vw;
      background-color: #fff;
      padding: 30px 0 30px 30px;
  }
  .modal-mahii-content-inner {
      max-height: 70vh;
      overflow: auto;
  }
  .modal-mahii-header {
      padding-bottom: 12px;
  }
  .close-modal {
    position: absolute;
    top: 0px;
    right: 15px;
    cursor: pointer;
    font-size: 4rem;
    color: #000;
  }

  .animate-modal {
    display: block !important;
    opacity: 0;
    animation: fadeIn 0.4s ease-in-out 1 forwards;
  }

  .animated-modal {
    display: block !important;
    opacity: 1;
  }

  .animate-out-modal {
    display: block !important;
    animation: fadeIn 0.4s ease-in-out 1 reverse backwards;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

</style>

Animation au scroll de la souris

Placeholder image

Petit code qui permet de faire en sorte de faire avancer (ou reculer) une animation CSS en fonction du scroll.

.animate .animation {
  animation: 1s linear;
  animation-play-state: paused;
  animation-delay: calc(0 * -1s);
  animation-iteration-count: 1;
  animation-fill-mode: both;
}

.animate.fadeIn .animation {
  opacity: 0;
  animation-name: fadeIn;
}

.animate.zommScrollImg .animation {
  transform: scale(1);
  animation-name: zommScrollImg;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes zommScrollImg {
to {
  transform: scale(1.3);
}
}
<script>
  function elementInView(elem){
    return elem.getBoundingClientRect().top > 0 && elem.getBoundingClientRect().top < window.innerHeight;
  }

  // L'animation se délenche quand le haut de l'élément est à 0% de la hauteur de la fenêtre et se termine quand le bas de l'élément atteint 50% de la hauteur de la fenêtre
  function getScrollPercentage(element) {
    const rect = element.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    if (rect.bottom <= viewportHeight * 0.5) {
      return 1;
    }
    if (rect.top >= viewportHeight) {
      return 0;
    }
    const distanceFromBottom = viewportHeight - rect.top;
    const totalScrollableDistance = viewportHeight + rect.height - (viewportHeight * 0.5);
    const percentage = distanceFromBottom / totalScrollableDistance;
    return Math.min(1, Math.max(0, percentage));
  }

  const animate = document.querySelectorAll('.animate');
  window.addEventListener('scroll', scrollAnimate);
  function scrollAnimate() {
    for(var i = 0; i < animate.length; i++) {        
      if( elementInView(animate[i]) ) {
        let offsetY = animate[i].getBoundingClientRect().top + window.scrollY;
      var stateAnimation = getScrollPercentage(animate[i]);
        animate[i].querySelector(".animation").style.animationDelay = 'calc('+stateAnimation+' * -1s)';
      }        
    }
  }
</script>