SnippetVamp

Ne perds plus jamais de temps en cherchant tes snippets !

Bienvenue dans mon SnippetVamp.

1 - labels input flottants CSS pur
// HTML
<body>
	<form>
		<h1>Please login</h1>
		<label><span>Username</span>
			<input type="text" name="login" value="" placeholder=" " >
		</label>
		<label><span>Password</span>
			<input type="password" name="pswd" value="" placeholder=" ">
		</label>

		<input type="submit" value="Ok">
		<hr>
		<h4>or <a href="">subscribe</a></h4>
	</form>

</body>

// CSS
body{
	height: 100%;
	max-height: 100%;
}
form{
	max-width:320px;
	margin:auto;
	border:1px solid rgba(0,0,0,0.2);
	border-radius: 0.5em;
	padding:0.5em;
	background:var(--color);
	
	position : relative;
    top: 50%;
    transform: translateY(-50%);

}
label{
	display: block;
	margin-top:1em;
}
input{
	outline: 0;
	display: block;
	width:100%;
	border-radius: 0.5em;
	border:1px solid rgba(0,0,0,0.2);
	margin-top:0.5em;
}

input[name="login"]{
	padding:0.5em;
	padding-left:24px;
	background: url(http://api.warriordudimanche.net/iconeleon/?i=fontawesome%20solid/circle-user.svg&c=black) no-repeat 4px center;
	background-size: 16px 16px;
}
input[type="password"]{
	padding:0.5em;
	padding-left:24px;
	background: url(http://api.warriordudimanche.net/iconeleon/?i=elusive/unlock-alt.svg&c=black) no-repeat 4px center;
	background-size: 16px 16px;
}

label span{
	position: relative;
	top:2em;
	left:24px;
	transition:all 500ms;
}
label:has(input:placeholder-shown) span{
	position: relative;
	top:2em;
	left:24px;
	transition:all 500ms;
}

label:has(input:focus) span,
label:has(input:not(:placeholder-shown)) span
{
	color:blue;
	top:0;
	left:0;
	transition:all 500ms;
}



			
2 - fonction PHP - servir un fichier avec headers corrects
function serveFile($path){

	if (is_file($path)){
		$mime=mime_content_type($path);
		header('Content-type: '.$mime.'; charset=utf-8');
		header('Content-Transfer-Encoding: binary');
		header('Content-Disposition: filename="'.tools::basename($path).'"');
		header('Content-Length: '.filesize($path));
		readfile($path);
		exit;
	}
        header("HTTP/1.1 404 Not Found");
        exit('404 - Not Found (╯°□°)╯︵ ┻━┻');

}
			
3 - folder2array()
function folder2array($path=''){
		//$path=empty($path)?'./':$path;
		$array=[];
		$current_dir=glob($path.'/*');
		if ($current_dir[0]==$path) unset($current_dir[0]);
		foreach ($current_dir as $key => $item) {
			if (is_file($item)){
				$array[]=$item;
			}else{
				$array[]=folder2array($item);
			}
		}
		return $array;
	}
			
4 - poster un blob vers PHP
// on utilise un filereader
function sendBlob(theBlob){  
  let reader = new FileReader();
  reader.addEventListener("loadend", function () {
    formData = new FormData();
    formData.append("blob", reader.result);
    formData.append("path", destination_folder);
    formData.append("token", token);
    postBlob(formData);
  });

  reader.readAsDataURL(theBlob);
}

function postBlob(data){
  fetch("index.php", { method: 'POST', body: data })
  .then((response)=>{return response.text()})
  .then((text)=>{
    token=text;
    alert("Fichier sauvegardé.");
  });
  
}
			
6 - trigger event on HTML element using JavaScript - 30 seconds of code
const triggerEvent = (el, eventType, detail) =>
  el.dispatchEvent(new CustomEvent(eventType, { detail }));

const myElement = document.getElementById('my-element');
myElement.addEventListener('click', e => console.log(e.detail));

triggerEvent(myElement, 'click');
// The event listener will log: null

triggerEvent(myElement, 'click', { username: 'bob' });
// The event listener will log: { username: 'bob' }
			
7 - listen for a click outside of an element in JavaScript? - 30 seconds of code
const onClickOutside = (element, callback) => {
  document.addEventListener('click', e => {
    if (!element.contains(e.target)) callback();
  });
};

onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element
			
8 - CSS Menu on image hover
<figure class="hover-menu">
	<img src="https://picsum.photos/id/1060/800/480.jpg"/>
	<div>
		<a href="#">Home</a>
		<a href="#">Pricing</a>
		<a href="#">About</a>
	</div>
</figure>
<style>
.hover-menu {
  position: relative;
  overflow: hidden;
  margin: 8px;
  min-width: 340px;
  max-width: 480px;
  max-height: 290px;
  width: 100%;
  background: #000;
  text-align: center;
  box-sizing: border-box;
}

.hover-menu * {
  box-sizing: border-box;
}

.hover-menu img {
  position: relative;
  max-width: 100%;
  top: 0;
  right: 0;
  opacity: 1;
  transition: 0.3s ease-in-out;
}

.hover-menu div {
  position: absolute;
  top: 0;
  left: -120px;
  width: 120px;
  height: 100%;
  padding: 8px 4px;
  background: #000;
  transition: 0.3s ease-in-out;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.hover-menu div a {
  display: block;
  line-height: 2;
  color: #fff;
  text-decoration: none;
  opacity: 0.8;
  padding: 5px 15px;
  position: relative;
  transition: 0.3s ease-in-out;
}

.hover-menu div a:hover {
  text-decoration: underline;
}

.hover-menu:hover img {
  opacity: 0.5;
  right: -120px;
}

.hover-menu:hover div {
  left: 0;
  opacity: 1;
}
</style>
			
11 - Pure CSS3 Image Slideshow Example
<style>
body {
	font-family: Arial, Helvetica, sans-serif;
}
.image-slideshow {
	width: 600px;
    height: 300px;
    overflow: hidden;
    white-space: nowrap;
    font-size: 0;
    position: relative;
}
.image-slideshow > div {
	width: 600px;
    height: 300px;
	animation: move 15s ease-in-out 2s infinite alternate;
    display:inline-block;
}
.image-slideshow > div div {
	position: absolute;
    bottom: 0;
    background: rgba(0,0,0,0.4);
    width: 100%;
}
.image-slideshow h2 {
	padding: 15px;
    margin: 0;
    font-size: 18px;
    color: #f9f9f9;
}
.image-slideshow p {
	padding: 0 15px 15px 15px;
    margin: 0;
    font-size: 14px;
    color: #dddddd;
}
@keyframes move {
	0%,30% { transform: translateX(0); }
   	40%,70% { transform: translateX(-600px); }
   	80%,100% { transform: translateX(-1200px); }
}
</style> 

<div class="image-slideshow">
	<div>
    	<img src="https://via.placeholder.com/600x300" width="600" height="300" alt="">
        <div>
        	<h2>Example Photo 1</h2>
            <p>Example description for the photo...</p>
        </div>
    </div>
	<div>
    	<img src="https://via.placeholder.com/600x300" width="600" height="300" alt="">
        <div>
        	<h2>Example Photo 2</h2>
            <p>Example description for the photo...</p>
        </div>
    </div>
	<div>
    	<img src="https://via.placeholder.com/600x300" width="600" height="300" alt="">
        <div>
        	<h2>Example Photo 3</h2>
            <p>Example description for the photo...</p>
        </div>
    </div>
</div>

			
14 - JS URL Manipulation
// Get parameters from a URL:

const url = new URL('https://example.com/index.php?name=David&surname=Adams');
console.log(url.searchParams.get('name')); // David 
console.log(url.searchParams.get('surname')); // Adams


// Redirect URL

location.href = "https://codeshack.io";

// Redirect in 10 seconds:

setTimeout(() => location.href = "https://codeshack.io", 10000); 


// Get Hash Value

// URL: http://example.com/home#MyProfile
console.log(window.location.hash.substr(1)); // Output: MyProfile


			
18 - 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;
}
			
19 - 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;
}
			
21 - 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")));
});
			
22 - 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);
})()
*/
			
24 - 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;
    }
}
			
25 - 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>
			
26 - 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>
			
27 - 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)

			
28 - 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>
			
29 - 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');

			
30 - 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>