SnippetVamp

Ne perds plus jamais de temps en cherchant tes snippets !

Bienvenue dans mon SnippetVamp.

1 - Reset CSS moderne (2023)
/* Box sizing rules */
*,
*::before,
*::after {
  box-sizing: border-box;
}

/* Prevent font size inflation */
html {
  -moz-text-size-adjust: none;
  -webkit-text-size-adjust: none;
  text-size-adjust: none;
}

/* Remove default margin in favour of better control in authored CSS */
body, h1, h2, h3, h4, p,
figure, blockquote, dl, dd {
  margin: 0;
}

/* Remove list styles on ul, ol elements with a list role, which suggests default styling will be removed */
ul[role='list'],
ol[role='list'] {
  list-style: none;
}

/* Set core body defaults */
body {
  min-height: 100vh;
  line-height: 1.5;
}

/* Set shorter line heights on headings and interactive elements */
h1, h2, h3, h4,
button, input, label {
  line-height: 1.1;
}

/* Balance text wrapping on headings */
h1, h2,
h3, h4 {
  text-wrap: balance;
}

/* A elements that don't have a class get default styles */
a:not([class]) {
  text-decoration-skip-ink: auto;
  color: currentColor;
}

/* Make images easier to work with */
img,
picture {
  max-width: 100%;
  display: block;
}

/* Inherit fonts for inputs and buttons */
input, button,
textarea, select {
  font: inherit;
}

/* Make sure textareas without a rows attribute are not tiny */
textarea:not([rows]) {
  min-height: 10em;
}

/* Anything that has been anchored to should have extra scroll margin */
:target {
  scroll-margin-block: 5ex;
}
			
2 - no accents - js
function strNoAccent(a) {
  var b="áàâäãåçéèêëíïîìñóòôöõúùûüýÁÀÂÄÃÅÇÉÈÊËÍÏÎÌÑÓÒÔÖÕÚÙÛÜÝ",
      c="aaaaaaceeeeiiiinooooouuuuyAAAAAACEEEEIIIINOOOOOUUUUY",
      d="";
  for(var i = 0, j = a.length; i < j; i++) {
    var e = a.substr(i, 1);
    d += (b.indexOf(e) !== -1) ? c.substr(b.indexOf(e), 1) : e;
  }
  return d;
}
			
4 - Modifier et traiter des données formulaire AVANT submit
// à mettre dans le form onsubmit
form.addEventListener("formdata",function(e){
	let formData = e.formData;
	formData.set("chapo", saveSlashes(formData.get("chapo")));
	formData.set("content", saveSlashes(formData.get("content")));
});
			
5 - fonction de «bionic reading»
const e = document.getElementById("edit"), r = document.getElementById("read");
const u = () => r.innerHTML = e.innerHTML.split(" ").map(w => `<b>${w.split("").slice(0,Math.ceil(w.length/2)).join("")}</b>${w.split("").slice(Math.ceil(w.length / 2),w.length).join("")} `).join(" ");
u();
e.addEventListener("input", u);

/* kodun orjinal halini de bırakayım da belki birinin işine yarar
const editor = document.getElementById("edit");
const reader = document.getElementById("read");

const updateContent = (e) => {
  const words = editor.innerHTML.split(" ");
  const edited = [];
  words.forEach((word, index) => {
    const wordSplit = word.split("");
    const boldTo = Math.ceil(word.length / 2);
    const editedWord = `<b>${wordSplit.slice(0,boldTo).join("")}</b>${wordSplit.slice(boldTo,word.length).join("")} `;
    edited.push(editedWord);
  });
  reader.innerHTML = edited.join("");
}

(() => {
  updateContent(); // init
  editor.addEventListener("input", updateContent);
})()
*/
			
7 - Rendre un tableau responsive
 <table class=”events-table” >
    <thead>
    <tr>
    <th class=”event-date”>Date</th>
    <th class=”event-time”>Horaire</th>
    <th class=”event-description”>Evènement</th>
    </tr>
    </thead>

    <tbody>
    <tr>
    <td data-label=”Date”> Le #_EVENTDATES</td>
    <td data-label=”Horaire”>#_EVENTTIMES</td>
    <td data-label=”Evènement”>#_EVENTLINK</td>
    </tr>
    </tbody>
   </table>

table caption {
    display: none;
}

@media all and (max-width:500px){
    table{
        width:100%;
    }

    table caption {
        display: block;
        background-color: #484d55;
        color:white;
    }

    .table thead {
    display: none;
    }

    .table tr{
    display: block;
    margin-bottom: 40px;
    }

    .table td {
    display: block;
    text-align: right;
    }

    .table td:before {
    content: attr(data-label);
    float: left;
    font-weight: bold;
    }
}
			
8 - Vérifier la validité des liens ayant la classe «checkLink»
# Vérifie les URL a/img etc ayant la classe checkLinks
# ou les URL des a/img contenus dans un objet ayant la classe checkLinks
# Ajoute une classe status200, status404 etc (en gros, «statusCODE_DE_REPONSE»

function checkLinks(nodelist){
	function checkUrl(link){
		return fetch(link).then(function(response){		
			return response.status;
		}).catch(function(error){
			return error.status;
		});
	}
	if (!nodelist){
		checkLinks(document.querySelectorAll('.checkLink'));
		return;
	}
	for (let obj of nodelist){
		if (obj.tagName=="A"){
			checkUrl(obj.href).then(function(response){obj.classList.add("status"+response);});
		}else if (obj.hasAttribute("src")){
			checkUrl(obj.src).then(function(response){obj.classList.add("status"+response);});
		}else{
			checkLinks(obj.querySelectorAll("*[href],*[src]"));
		}
	}
}
checkLinks();

# on peut styler les classes:
<style type="text/css">
	.status200{color:green}
	.status404{color:violet}
	.status500{color:red}
</style>
			
9 - arborescence en css uniquement
 .tree {
  --spacing: 1.5rem;
  --radius: 10px;
  --marker-bg-default: #ddd;
  --marker-bg-haschild: #6b9abb;
  line-height: 2rem;
}
.tree li {
  display: block;
  position: relative;
  padding-left: calc(2 * var(--spacing) - var(--radius) - 2px);
}
.tree ul {
  margin-left: calc(var(--radius) - var(--spacing));
  padding-left: 0;
}
.tree ul li {
  border-left: 2px solid #ddd;
}
.tree ul li:last-child {
  border-color: transparent;
}
.tree ul li::before {
  content: "";
  display: block;
  position: absolute;
  top: calc(var(--spacing) / -2);
  left: -2px;
  width: calc(var(--spacing) + 2px);
  height: calc(var(--spacing) + 1px);
  border: solid #ddd;
  border-width: 0 0 2px 2px;
}
.tree summary {
  display: block;
  cursor: pointer;
}
.tree summary::marker,
.tree summary::-webkit-details-marker {
  display: none;
}
.tree summary:focus {
  outline: none;
}
.tree summary:focus-visible {
  outline: 1px dotted #000;
}
.tree li::after,
.tree summary::before {
  content: "";
  display: block;
  position: absolute;
  top: calc(var(--spacing) / 2 - var(--radius) + 2px);
  left: calc(var(--spacing) - var(--radius) - 2px);
  width: calc(2 * var(--radius));
  height: calc(2 * var(--radius));
  border-radius: 50%;
  background: var(--marker-bg-default);
}
.tree summary::before {
  content: "+";
  z-index: 1;
  background: var(--marker-bg-haschild);
  color: #fff;
  line-height: calc(2 * var(--radius));
  text-align: center;
}
.tree details[open] > summary::before {
  content: "−";
}






<ul class="tree">
  <li>
    <details open>
      <summary>Informatique</summary>
      <ul>
        <li>
          <details>
            <summary>Périphériques</summary>
            <ul>
              <li>Clavier</li>
              <li>Souris</li>
              <li>Ecran</li>
            </ul>
          </details>
        </li>
        <li>
          <details open>
            <summary>Stockage</summary>
            <ul>
              <li>Disque dur</li>
              <li>SSD</li>
              <li>Clé USB</li>
            </ul>
          </details>
        </li>
        <li>
          <details>
            <summary>Composants</summary>
            <ul>
              <li>Processeur</li>
              <li>Carte mère</li>
              <li>Mémoire</li>
              <li>
            </ul>
          </details>
        </li>
        <li>
          <details>
            <summary>Composants</summary>
            <ul>
              <li>Processeur</li>
              <li>Carte mère</li>
              <li>Mémoire</li>
              <li>Carte graphique</li>
            </ul>
          </details>
        </li>
      </ul>
    </details>
  </li>
</ul>
</code></pre> codeCarte graphique</li>
            </ul>
          </details>
        </li>
      </ul>
    </details>
  </li>
</ul>
			
10 - console JS

    pour avoir le nom des variables avec leur valeur, utiliser { }: console.log({var})
    console.warn(), console.error() et console.info() pour différencier l'aspect du message.
    console.assert(condition,retour) pour éviter un if (condition){console.log(retour)
    console.trace() pour remonter la pile d'appels
    console.group('nom'), console.groupCollapsed('nom') et console.groupEnd('nom') pour regrouper des console log()
    console.table(array) pour présenter les données sous forme de tableau
    $(selecteur) est équivalent à document.querySelector(selecteur)
    $$(selecteur) est équivalent à document.querySelectorAll(selecteur)

			
11 - touche de clavier en CSS
<style type="text/css">
	key{
		display:inline-block;
		padding:0.5em;
		border:1px solid rgba(0,0,0,0.5);
		border-radius: 3px;
		box-shadow: 0 0.2em 0 0.05em #222;
		background: linear-gradient(180deg, rgba(150,150,150,1) 0%, rgba(240,240,240,1) 100%);;
	}
</style>

<key>Shift</key>+<key>B</key>
			
12 - ordonner un tableau en fonction de la longueur des chaines qui le composent
function order($a,$b){
    return strlen($b)-strlen($a);
}
usort($mots,'order');

			
13 - Des sous-titres qui fonctionnent avec la balise video
<video controls title="sdfgsdfg" preload="auto" crossorigin>
    <source src="Marco_Castelblanco.mp4" type="video/mp4"/>
    <!--   kind="captions" ou "subtitles" ATTENTION AU PLURIEL -->
    <track kind="captions" srclang="fr" label="sous-titre" src="Marco_Castelblanco.vtt" default="true"/>
    Sorry, your browser doesn't support embedded videos.
</video>
			
15 - trier des fichiers par date (ascendant)
$files=glob('*');

usort(
        $files,
        function($file1, $file2) {
        return filemtime($file1) <=> filemtime($file2);
    }
);

// pour descendant:
$files=array_reverse($files);
			
16 - aujourdhui() - la date du jour en français
function aujourdhui()
    {
        $jour=@date("D");
        $njour=@date("j");
        $nmois=@date("n");
        $an=@date("Y");
        $ja="Mon Tue Wen Thu Fri Sat Sun ";
        $jf="Lundi Mardi Mercredi Jeudi Vendredi Samedi Dimanche ";
        $tjours=explode(" ",$jf);
        $mf="Janvier Février Mars Avril Mai Juin Juillet Août Septembre Octobre Novembre Décembre ";
        $tmois=explode(" ",$mf);

        $nj=strpos($ja,$jour)/4;

        $jour=$tjours[$nj];
        $mois=$tmois[$nmois-1];
        $z=$jour." ".$njour." ".$mois." ".$an;
        return $z;
    }
			
17 - Empêcher le submit d'un formulaire par Enter sans bloquer la touche
form.addEventListener("submit", function(event){
	if (event.keyCode==13){
		event.preventDefault();
		event.stopPropagation();
		event.stopImmediatePropagation();
		return false;
	}
});
			
18 - Page HTML5 de base
<!doctype html>

<html lang="fr">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>TITLE</title>
    <meta name="description" content="A simple HTML5 Template for new projects.">
    <meta name="author" content="SitePoint">

    <meta property="og:title" content="TITLE">
    <meta property="og:type" content="website">
    <meta property="og:url" content="URL">
    <meta property="og:description" content="DESCRIPTION">
    <meta property="og:image" content="favicon.svg">

    <link rel="icon" href="/favicon.ico">
    <link rel="icon" href="/favicon.svg" type="image/svg+xml">
    <link rel="apple-touch-icon" href="/apple-touch-icon.png">

    <link rel="stylesheet" href="styles.css?v=1.0">

</head>

<body>
    <!-- your content here... -->
    <script src="scripts.js"></script>
</body>

</html>
			
19 - effet de retournement horizontal d'une animation
<!DOCTYPE html>
<html>
  <head>
    <title>Titre du document</title>
    <style>
      .box {
      background-color: transparent;
      width: 220px;
      height: 300px;
      border: 1px solid #eeeeee;
      perspective: 1000px;
      }
      .box-inner {
      position: relative;
      width: 100%;
      height: 100%;
      text-align: center;
      transition: transform 0.5s;
      transform-style: preserve-3d;
      }
      .box:hover .box-inner {
      transform: rotateY(180deg);
      }
      .box-front, .box-back {
      position: absolute;
      width: 100%;
      height: 100%;
      backface-visibility: hidden;
      }
      .box-front {
      background-color: #cccccc;
      color: #111111;
      }
      .box-back {
      background-color: #8ebf42;
      color: #eeeeee;
      transform: rotateY(180deg);
      }
    </style>
  </head>
  <body>
    <h2>Boîte de retournement 3D (Horizontale)</h2>
    <p>Placez la souris sur la boîte pour voir l'effet:</p>
    <div class="box">
      <div class="box-inner">
        <div class="box-front">
          <h2>Face frontale</h2>
        </div>
        <div class="box-back">
          <h2>Face arrière</h2>
        </div>
      </div>
    </div>
  </body>
</html>
			
20 - Obtenir l'adresse de l'article en cours dans PluXml
$url_article=$plxShow->plxMotor->urlRewrite('index.php?article'.$plxShow->plxMotor->plxRecord_arts->f('numero').'/'.$plxShow->plxMotor->plxRecord_arts->f('url'))
			
21 - Body qui apparait après chargement en 2 lignes
/* Dans le Head */
<style type="text/css">body{opacity: 0;transition: opacity 1s}</style>

/* balise body */
<body onload="document.body.style.opacity=1" >
			
23 - Serveur de fichiers rapide en Python
Terminal depuis le dossier à partager puis:
(en Python 2) : python -m SimpleHTTPServer 5555
(en Python 3) : python -m http.server 5555
et accédez avec un simple navigateur (http://adresseip:5555)
			
24 - Chemin vers un plugin dans pluXML
$plxMotor=plxMotor::getInstance();
$plugin=$plxMotor->plxPlugins->aPlugins['nom_du_plugin'];
$plugin->methode();
			
25 - How To Build Tabs only with CSS - Digital-Heart - Medium
// boutons
<input type="radio" name="tabs" id="tab1" checked />
<label for="tab1">Tab1</label> 
<input type="radio" name="tabs" id="tab2" />
<label for="tab2">Tab2</label>

// contenus
<div class="tab content1">Tab1 Contents </div>
<div class="tab content2">Tab2 Contents </div>


// css pour cacher/montrer
input { display: none; }                /* hide radio buttons */
input + label { display: inline-block } /* show labels in line */
input ~ .tab { display: none }          /* hide contents *//* show contents only for selected tab */
#tab1:checked ~ .tab.content1,
#tab2:checked ~ .tab.content2 { display: block; }

// css pour styler

input + label {             /* box with rounded corner */
  border: 1px solid #999;
  background: #EEE;
  padding: 4px 12px;
  border-radius: 4px 4px 0 0;
  position: relative;
  top: 1px;
}
input:checked + label {     /* white background for selected tab */
  background: #FFF;
  border-bottom: 1px solid transparent;
}
input ~ .tab {          /* grey line between tab and contents */
  border-top: 1px solid #999;
  padding: 12px;
}
			
26 - How can you encode a string to Base64 in JavaScript? - Stack Overflow
/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = this._keyStr.indexOf(input.charAt(i++));
        enc2 = this._keyStr.indexOf(input.charAt(i++));
        enc3 = this._keyStr.indexOf(input.charAt(i++));
        enc4 = this._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

}
			
27 - encoder-decoder une chaine - compatible URL pour GET
function base64url_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
} 
			
30 - CSS masonry with flexbox, :nth-child(), and order | Tobias Ahlin

.container {
  display: flex;
  flex-flow: column wrap;
  align-content: space-between;
  /* Your container needs a fixed height, and it 
   * needs to be taller than your tallest column. */
  height: 600px; 
}

.item {
  width: 32%;
  margin-bottom: 2%; /* Optional */
}

/* Re-order items into 3 rows */
.item:nth-child(3n+1) { order: 1; }
.item:nth-child(3n+2) { order: 2; }
.item:nth-child(3n)   { order: 3; }

/* Force new columns */
.container::before,
.container::after {
  content: "";
  flex-basis: 100%;
  width: 0;
  order: 2;
}



<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  ...
</div>


4 colonnes
.container {
  display: flex;
  flex-flow: column wrap;
  align-content: space-between;
  /* Your container needs a fixed height, and it 
   * needs to be taller than your tallest column. */
  height: 600px; 
}

.item {
  width:24%;
  margin-bottom: 2%; /* Optional */
}

/* Re-order items into 4 rows */
.item:nth-child(4n+1) { order: 1; }
.item:nth-child(4n+2) { order: 2; }
.item:nth-child(4n+3) { order: 3; }
.item:nth-child(4n)   { order: 4; }

/* Force new columns */
.break {
  content: "";
  flex-basis: 100%;
  width: 0;
  margin: 0;
}