1 - recharger les img qui ont échoue
<script>
on("error","img",function(e){
let img=e.target;
let src=img.src;
img.src="";
img.src=src;
});
</script>
<script>
on("error","img",function(e){
let img=e.target;
let src=img.src;
img.src="";
img.src=src;
});
</script>
const capsLockOn = keyboardEvent.getModifierState('CapsLock');
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();
body{
display:grid;
grid-template-rows: auto 1fr auto;
}
avec une structure HTML:
<body>
<header></header>
<main></main>
<footer></footer>
</body>
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
ou
display: grid;
justify-items: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
<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;
}
})
$closure=function ($arg1,$arg2) use ($var_exterieure){
#come on, do something
};
<FilesMatch "\.php *$">
Order allow,deny
Deny from all
</FilesMatch>
php -S 0.0.0.0:5555 -t "/path/to/folder"
function firstCap($str){
$str=str_replace('_',' ', $str);
$str=ucwords($str);
$str=str_replace(' ','',$str);
return $str;
}
// 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;
}
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 (╯°□°)╯︵ ┻━┻');
}
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;
}
// 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é.");
});
}
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>