1 - foreach (data as key=>value) en js
for (let [key, value] of data) {
console.log(key);
console.log(value);
}
for (let [key, value] of data) {
console.log(key);
console.log(value);
}
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' }
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
<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>
<button id="my-btn">Click me!</button>
const listenOnce = (el, evt, fn) =>
el.addEventListener(evt, fn, { once: true });
listenOnce(
document.getElementById('my-btn'),
'click',
() => console.log('Hello!')
); // 'Hello!' will only be logged on the first click
const runPromisesInSeries = ps =>
ps.reduce((p, next) => p.then(next), Promise.resolve());
const delay = d => new Promise(r => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]);
// Executes each promise sequentially, taking a total of 3 seconds to complete
<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>
The following snippet will detect if the visitor is using a mobile device:
JS
const isMobile = /iPhone|iPad|iPod|Android|Opera Mini|BlackBerry|IEMobile|WPDesktop|Windows Phone|webOS|/i.test(navigator.userAgent);
if (isMobile) {
console.log('Device is mobile');
}
Countdown Timer
The following snippet will countdown a number in an element:
HTML
<p id="num">100</p>
JS
const num = document.querySelector('#num');
setInterval(() => num.innerHTML = parseInt(num.innerHTML) != 0 ? parseInt(num.innerHTML)-1 : 0, 1000);
// 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
// save
localStorage.setItem('username', 'David');
// load
console.log(localStorage.getItem('username'));
// Test if item exists
if (localStorage.getItem('username')) {
console.log('Item exists!');
}
// Remove one item
localStorage.removeItem('username');
// Remove all items:
localStorage.clear();
const fetchAPI = async(URL) => {
const response = await fetch(URL);
const data = await response.json();
console.log(data)
}
fetchAPI("https://jsonplaceholder.typicode.com/todos/1")
# Escape
htmlentities($text, ENT_QUOTES, 'UTF-8');
# Unescape HTML entities:
html_entity_decode($text);
/* 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;
}
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;
}
<a onclick="this.href='data:text/html;charset=UTF-8,'+encodeURIComponent(document.documentElement.outerHTML)" href="#" download="page.html">Download</a>
// à 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")));
});
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);
})()
*/
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<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;
}
}
# 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>
.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>
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)
<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>
function order($a,$b){
return strlen($b)-strlen($a);
}
usort($mots,'order');
<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>
function redirect($url=null){
@header('location: '.$url);
exit('<script>document.location.href="'.$url.'";</script>');
}
$files=glob('*');
usort(
$files,
function($file1, $file2) {
return filemtime($file1) <=> filemtime($file2);
}
);
// pour descendant:
$files=array_reverse($files);
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;
}
form.addEventListener("submit", function(event){
if (event.keyCode==13){
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
}
});