SnippetVamp

Ne perds plus jamais de temps en cherchant tes snippets !

Bienvenue dans mon SnippetVamp.

3 - sauvegarder un node en html
var doc=first('#node').innerHTML;
var name="filename.html";   
var myFile = new Blob([doc], {type: 'text/plain'});		
		
window.URL = window.URL || window.webkitURL;
var a= create('a',{href:window.URL.createObjectURL(myFile),download:name});
a.click();
			
4 - footer en bas de page en deux lignes
body{
	display:grid;
	grid-template-rows: auto 1fr auto;
}
avec une structure HTML:

<body>
    <header></header>
    <main></main>
    <footer></footer>
</body>
			
6 - Ajouter simplement une confirmation à un lien
<a href="lien" confirm="Êtes-vous sûr ?">Action à confirmer</a>

on("click","a[confirm]",function(e){
	msg=attr(e.target,"confirm");
	if(!msg){msg="Veuillez confirmer";}
	if (!confirm(msg)){
		e.preventDefault();
		return false;
	}
})
			
7 - Closure avec variable du scope exterieur
$closure=function ($arg1,$arg2) use ($var_exterieure){
    #come on, do something
};
			
10 - firstCap()
	function firstCap($str){
		$str=str_replace('_',' ', $str);
		$str=ucwords($str);
		$str=str_replace(' ','',$str);
		return $str;
	}
			
11 - 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;
}



			
12 - 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 (╯°□°)╯︵ ┻━┻');

}
			
13 - 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;
	}
			
14 - 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é.");
  });
  
}
			
16 - 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' }
			
17 - 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
			
18 - 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>
			
21 - 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>

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


			
28 - 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;
}
			
29 - 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;
}