1 - empêcher le drag drop d'image - JS inline
ajouter onDragStart="return false;"
ajouter onDragStart="return false;"
// filtre tous les inputs ayant l'attribut alphanum-only
on("input","[alphanum-only]",function(e){
let obj=e.target;
let cursor_position=obj.selectionStart;
obj.value=obj.value.replace(new RegExp(/[^a-zA-z0-9\-_ ]/g), "");
obj.selectionStart=cursor_position;
obj.selectionEnd=cursor_position;
});
// Objet JavaScript brut
const obj = { recette: 'Rôti au kiwi', duree: 120, ingredients: 3 };
// Données à exporter converties en chaîne de texte
const data = JSON.stringify(obj);
// Crée un blob à partir des données
const blob = new Blob([data], { type: 'application/json' });
// Génère une URL temporaire
const url = window.URL.createObjectURL(blob);
// Crée un lien et déclenche le téléchargement
const link = document.createElement('a');
link.href = url;
link.download = 'data.json';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Libère l’URL temporaire et la mémoire 🧹
window.URL.revokeObjectURL(url);
document.getElementById("tunnel").animate(
[
// étapes/keyframes
{ transform: "translateY(0px)" },
{ transform: "translateY(-300px)" },
],
{
// temporisation
duration: 1000,
iterations: Infinity,
},
);
button.addEventListener('click', function(){
element.hidden = !element.hidden;
});
ou en VanillaJS
on("click","button",function(){
element.hidden = !element.hidden;
});
<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();
<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;
}
})
// 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
<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
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")
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);
})()
*/
# 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>
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)
form.addEventListener("submit", function(event){
if (event.keyCode==13){
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
}
});
/* Dans le Head */
<style type="text/css">body{opacity: 0;transition: opacity 1s}</style>
/* balise body */
<body onload="document.body.style.opacity=1" >
// 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;
}
/**
*
* 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;
}
}
navigator.clipboard.writeText("text");
function getHTTP(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
}
};
xhr.open("GET", url);
xhr.send();
});
}
getHTTP("https://www.google.fr")
.then(function (response) {
// On récupère le resultat de la requête dans la varible "response"
console.log(response)
})
<ul id="slides">
<li class="slide showing">Slide 1</li>
<li class="slide">Slide 2</li>
<li class="slide">Slide 3</li>
<li class="slide">Slide 4</li>
<li class="slide">Slide 5</li>
</ul>
/*
essential styles:
these make the slideshow work
*/
#slides {
position: relative;
height: 300px;
padding: 0px;
margin: 0px;
list-style-type: none;
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
}
.showing {
opacity: 1;
z-index: 2;
}
/*
non-essential styles:
just for appearance; change whatever you want
*/
.slide {
font-size: 40px;
padding: 40px;
box-sizing: border-box;
background: #333;
color: #fff;
}
.slide:nth-of-type(1) {
background: red;
}
.slide:nth-of-type(2) {
background: orange;
}
.slide:nth-of-type(3) {
background: green;
}
.slide:nth-of-type(4) {
background: blue;
}
.slide:nth-of-type(5) {
background: purple;
}
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);
function nextSlide() {
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide+1)%slides.length;
slides[currentSlide].className = 'slide showing';
}
//JS
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData(
"text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ','
+ (parseInt(style.getPropertyValue("top"),10) - event.clientY)+','
+ event.target.id
);
}
function drag_over(event) {
event.preventDefault();
return false;
}
on('dragstart','[draggable]',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',function(event){
var offset = event.dataTransfer.getData("text/plain").split(',');
icon =document.getElementById(offset[2]);console.log(icon);
//icon.style.position ="absolute";
icon.style.left =(event.clientX + parseInt(offset[0],10)) + 'px';
icon.style.top =(event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
},false);
/*CSS*/
[draggable]{
width:65px;
height:65px;
z-index: 999;
position:relative;
}
Copy On Click
var button = document.getElementById("copy-button"),
contentHolder = document.getElementById("content-holder");
button.addEventListener("click", function() {
// We will need a range object and a selection.
var range = document.createRange(),
selection = window.getSelection();
// Clear selection from any previous data.
selection.removeAllRanges();
// Make the range select the entire content of the contentHolder paragraph.
range.selectNodeContents(contentHolder);
// Add that range to the selection.
selection.addRange(range);
// Copy the selection to clipboard.
document.execCommand('copy');
// Clear selection if you want to.
selection.removeAllRanges();
}, false);
Modify Copied Text
document.addEventListener('copy', function(e){
// We need to prevent the default copy functionality,
// otherwise it would just copy the selection as usual.
e.preventDefault();
// The copy event doesn't give us access to the clipboard data,
// so we need to get the user selection via the Selection API.
var selection = window.getSelection().toString();
// Transform the selection in any way we want.
// In this example we will escape HTML code.
var escaped = escapeHTML(selection);
// Place the transformed text in the clipboard.
e.clipboardData.setData('text/plain', escaped);
});
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
<button class="button share_twitter" data-url="http://....">
Partager sur twitter
</button>
<button class="button share_facebook" data-url="http://....">
Partager sur facebook
</button>
<button class="button share_gplus" data-url="http://....">
Partager sur google+
</button>
<button class="button share_linkedin" data-url="http://....">
Partager sur linkedin
</button>
<script>
(function(){
var popupCenter = function(url, title, width, height){
var popupWidth = width || 640;
var popupHeight = height || 320;
var windowLeft = window.screenLeft || window.screenX;
var windowTop = window.screenTop || window.screenY;
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
var windowHeight = window.innerHeight || document.documentElement.clientHeight;
var popupLeft = windowLeft + windowWidth / 2 - popupWidth / 2 ;
var popupTop = windowTop + windowHeight / 2 - popupHeight / 2;
var popup = window.open(url, title, 'scrollbars=yes, width=' + popupWidth + ', height=' + popupHeight + ', top=' + popupTop + ', left=' + popupLeft);
popup.focus();
return true;
};
document.querySelector('.share_twitter').addEventListener('click', function(e){
e.preventDefault();
var url = this.getAttribute('data-url');
var shareUrl = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(document.title) +
"&via=Grafikart_fr" +
"&url=" + encodeURIComponent(url);
popupCenter(shareUrl, "Partager sur Twitter");
});
document.querySelector('.share_facebook').addEventListener('click', function(e){
e.preventDefault();
var url = this.getAttribute('data-url');
var shareUrl = "https://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent(url);
popupCenter(shareUrl, "Partager sur facebook");
});
document.querySelector('.share_gplus').addEventListener('click', function(e){
e.preventDefault();
var url = this.getAttribute('data-url');
var shareUrl = "https://plus.google.com/share?url=" + encodeURIComponent(url);
popupCenter(shareUrl, "Partager sur Google+");
});
document.querySelector('.share_linkedin').addEventListener('click', function(e){
e.preventDefault();
var url = this.getAttribute('data-url');
var shareUrl = "https://www.linkedin.com/shareArticle?url=" + encodeURIComponent(url);
popupCenter(shareUrl, "Partager sur Linkedin");
});
})();
</script>
<script type="text/javascript">
function generer_password(champ_cible) {
var ok = 'azertyupqsdfghjkmwxcvbn23456789AZERTYUPQSDFGHJKMWXCVBN';
var pass = '';
longueur = 5;
for(i=0;i<longueur;i++){
var wpos = Math.round(Math.random()*ok.length);
pass+=ok.substring(wpos,wpos+1);
}
document.getElementById(champ_cible).value = pass;
}
/*
<input name="password" id="password" type="text" />
<input type="button" name="generer" value="Générer" onclick="javascript:generer_password('password');" />
*/
</script>
// Initial state
var scrollPos = 0;
// adding scroll event
window.addEventListener('scroll', function(){ scrolling() });
// the function : compares the "new" scrolling state with the previous
// (this allows detecting either "up" or "down" scrolling)
// then saves the new in the $previous for the next iteration.
function scrolling() {
if ((document.body.getBoundingClientRect()).top > scrollPos) {
console.log('scrolling DOWN');
} else {
console.log('scrolling UP');
}
scrollPos = (document.body.getBoundingClientRect()).top;
}
onclick="window.setTimeout('location.assign(location.href)',2000);"
while (box.firstChild) {
box.removeChild(box.firstChild);
}
// est plus rapide que
box.innerHTML = '';
if (typeof obj=='string'){obj=document.getElementById(obj);}
if (window.CustomEvent) {
var event = new CustomEvent(ev, {detail: {some: 'data'}})
} else {
var event = document.createEvent('CustomEvent')
event.initCustomEvent('ev', true, true, {some: 'data'})
}
obj.dispatchEvent(event)
}
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
<div class="dropup">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
avec headers
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu3">
...
<li role="presentation" class="dropdown-header">Dropdown header</li>
...
</ul>
avec séparateurs
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuDivider">
...
<li role="presentation" class="divider"></li>
...
</ul>
<!-- Single button -->
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<!-- Split button -->
<div class="btn-group">
<button type="button" class="btn btn-danger">Action</button>
<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Collapsible Group Item #1
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Collapsible Group Item #2
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Collapsible Group Item #3
</a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
</div>
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Link with href
</a>
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-target
</button>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)
</label>
<label class="btn btn-primary">
<input type="checkbox" autocomplete="off"> Checkbox 2
</label>
<label class="btn btn-primary">
<input type="checkbox" autocomplete="off"> Checkbox 3
</label>
</div>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
</label>
</div>
<a href="#" data-toggle="tooltip" title="" data-original-title="Default tooltip">you probably</a>
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left">Tooltip on left</button>
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top">Tooltip on top</button>
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom">Tooltip on bottom</button>
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right">Tooltip on right</button>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
// pour détecter la fermeture de la boite
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
On peut alors recupérer les données saisies
autres events: show.bs.modal shown.bs.modal hidden.bs.modal loaded.bs.modal
function sendForm(form){
data='';
url=form.getAttribute('action');
Array.prototype.forEach.call(form.elements,function(obj){
type=obj.getAttribute('type');
if (
type!='checkbox'&&type!='radio'&&type!='submit'
||obj.checked==1
){
data+=obj.getAttribute('name')+'='+obj.value+'&';
}
});
request = new XMLHttpRequest;
request.open('post', url, true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(data);
// Gestion de la réponse du serveur
request.onreadystatechange=function(){
if (request.readyState!=4 && request.status!=200){
console.log(request.responseText);
}
}
return false;
}
function strip_tags(input, allowed) {
//http://phpjs.org/functions/strip_tags/
allowed = (((allowed || '') + '')
.toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || [])
.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '')
.replace(tags, function($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
<script type="text/javascript">
window.onload = function() {
/* <textarea id="comment_textarea" ...></textarea> */
var textarea = document.getElementById('comment_textarea');
textarea.onkeydown = function(e) {
e = e || event; // cross-browser (quand IE en fait � sa t�te)
/* Envoyer le formulaire avec Ctrl+Entrer */
if(e.keyCode == 13 && e.ctrlKey) {
this.form.submit();
}
/* Envoyer le formulaire avec Entrer mais autoriser
* les retours � la ligne avec Ctrl+Entrer */
if(e.keyCode == 13 && !e.ctrlKey) {
this.form.submit();
return false;
} else if (e.keyCode == 13) {
this.value += "\n";
}
};
};
</script>
function post(){
obj=document.getElementById('message');
data=obj.value;
request = new XMLHttpRequest;
request.open('POST', 'index.php', true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("message="+data+"&pseudo=roger");// ici on met name=valeur
obj.value='';
}
<img src="logo.svg" onerror="this.src = 'logo.png';" alt="logo" width="140" height="140"/>
/*
# ------------------ BEGIN LICENSE BLOCK ------------------
#
#
# Copyright (c) 2009 - 2014 Cyril MAGUIRE
# Licensed under the CeCILL v2.1 license.
# See http://www.cecill.info/licences.fr.html
#
# ------------------- END LICENSE BLOCK -------------------
*/
;(function(window,undefined) {
'use_strict';
var timeOut;
var isIE = isIE();
function isIE() {
var nav = navigator.userAgent.toLowerCase();
return (nav.indexOf('msie') != -1) ? parseInt(nav.split('msie')[1]) : false;
}
function backToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('backToTop()',40);
}
else {
clearTimeout(timeOut);
}
}
function getScrollPosition() {
return Array((document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft,(document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop);
}
function Remove(idOfParent,idToRemove) {
if (isIE) {
document.getElementById(idToRemove).removeNode(true);
} else {
var Node1 = document.getElementById(idOfParent);
var len = Node1.childNodes.length;
for(var i = 0; i < len; i++){
if (Node1.childNodes[i] != undefined && Node1.childNodes[i].id != undefined && Node1.childNodes[i].id == idToRemove){
Node1.removeChild(Node1.childNodes[i]);
}
}
}
}
function addElement(idOfParent,idToAdd,htmlToInsert) {
var DomParent = document.getElementById(idOfParent);//id of body
var newdiv = document.createElement('div');
newdiv.setAttribute('id',idToAdd);
newdiv.innerHTML = htmlToInsert;
DomParent.appendChild(newdiv);
}
function displayBackButton() {
var pos = [];
var fleche = '\u21E7';
if (isIE) {
fleche = '\u25B2';
}
pos = getScrollPosition();
var topLink = document.getElementById('toplink');
if (pos[1] > 150) {
if (topLink == null) {
addElement('top','toplink',''+fleche+'');
}
} else {
if (topLink != null) {
Remove('top','toplink');
}
}
}
//add to global namespace
window.onscroll = displayBackButton;
window.displayBackButton = displayBackButton;
window.backToTop = backToTop;
})(window);
// CSS
#toplink {
position: fixed;
bottom: 20px;
width: 100px;
text-align: center;
right:10px;
}
#toplink a {
font-size: 40px;
opacity: 0.8;
}
function getScrollPosition()
{
return Array((document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft,(document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop);
}
<!-- BAD: blocking external script -->
<script src="http://somehost.com/awesome-widget.js"></script>
<!-- GOOD: remote script is loaded asynchronously -->
<script>
var script = document.createElement('script');
script.src = "http://somehost.com/awesome-widget.js";
document.getElementsByTagName('head')[0].appendChild(script);
</script>
<!-- GOOD: modern, simpler, faster, and better all around -->
<script src="http://somehost.com/awesome-widget.js" async></script>
var confirmOnLeave = function(msg) {
window.onbeforeunload = function (e) {
e = e || window.event;
msg = msg || '';
// For IE and Firefox
if (e) {e.returnValue = msg;}
// For Chrome and Safari
return msg;
};
};
// message de confirmation générique du navigateur
confirmOnLeave();
// message de confirmation personnalisé
confirmOnLeave('Vous allez perdre votre travail, êtes vous sûr(e) de vouloir quitter la page ?');
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
function htmlEntities(str) {return String(str).replace(/&/g, '&').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');}
var snd = new Audio("beep.wav");
snd.play();
Évènements
// jQuery
$(document).ready(function() {
// code
})
// Vanilla
document.addEventListener('DOMContentLoaded', function() {
// code
})
// jQuery
$('a').click(function() {
// code…
})
// Vanilla
[].forEach.call(document.querySelectorAll('a'), function(el) {
el.addEventListener('click', function() {
// code…
})
})
Sélecteurs
// jQuery
var divs = $('div')
// Vanilla
var divs = document.querySelectorAll('div')
// jQuery
var newDiv = $('<div/>')
// Vanilla
var newDiv = document.createElement('div')
Attributs
// jQuery
$('img').filter(':first').attr('alt', 'My image')
// Vanilla
document.querySelector('img').setAttribute('alt', 'My image')
Classes
// jQuery
newDiv.addClass('foo')
// Vanilla
newDiv.classList.add('foo')
// jQuery
newDiv.toggleClass('foo')
// Vanilla
newDiv.classList.toggle('foo')
Manipulation
// jQuery
$('body').append($('<p/>'))
// Vanilla
document.body.appendChild(document.createElement('p'))
// jQuery
var clonedElement = $('#about').clone()
// Vanilla
var clonedElement = document.getElementById('about').cloneNode(true)
// jQuery
$('#wrap').empty()
// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)
Navigation
// jQuery
var parent = $('#about').parent()
// Vanilla
var parent = document.getElementById('about').parentNode
// jQuery
if($('#wrap').is(':empty'))
// Vanilla
if(!document.getElementById('wrap').hasChildNodes())
// jQuery
var nextElement = $('#wrap').next()
// Vanilla
var nextElement = document.getElementById('wrap').nextSibling
AJAX
GET
// jQuery
$.get('//example.com', function (data) {
// code
})
// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
// code
}
httpRequest.open('GET', url)
httpRequest.send()
POST
// jQuery
$.post('//example.com', { username: username }, function (data) {
// code
})
// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
// code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))
JSONP
// jQuery
$.getJSON('//openexchangerates.org/latest.json?callback=?', function (data) {
// code
})
// Vanilla
function success(data) {
// code
}
var scr = document.createElement('script')
scr.src = '//openexchangerates.org/latest.json?callback=formatCurrency'
document.body.appendChild(scr)
if (typeof markdown === 'undefined') var markdown = {
parse: function (s) {
var r = s, ii, pre1 = [], pre2 = [];
// detect newline format
var newline = r.indexOf('\r\n') != -1 ? '\r\n' : r.indexOf('\n') != -1 ? '\n' : ''
// store CONSTANT "{ unformatted blocks": not defined !} and <pre> pre-formatted blocks </pre>
r = r.replace(/CONSTANT "{": not defined !}/g, function (x) { pre1.push(x.substring(3, x.length - 3)); return 'CONSTANT "{": not defined !}'; });
r = r.replace(new RegExp('<pre>([\\s\\S]*?)</pre>', 'gi'), function (x) { pre2.push(x.substring(5, x.length - 6)); return '<pre></pre>'; });
// h1 - h4 and hr
r = r.replace(/^==== (.*)=*/gm, '<h4>$1</h4>');
r = r.replace(/^=== (.*)=*/gm, '<h3>$1</h3>');
r = r.replace(/^== (.*)=*/gm, '<h2>$1</h2>');
r = r.replace(/^= (.*)=*/gm, '<h1>$1</h1>');
r = r.replace(/^[-*][-*][-*]+/gm, '<hr>');
// bold, italics, and code formatting
r = r.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
r = r.replace(new RegExp('//(((?!https?://).)*?)//', 'g'), '<em>$1</em>');
r = r.replace(/``(.*?)``/g, '<code>$1</code>');
// unordered lists
r = r.replace(/^\*\*\*\* (.*)/gm, '<ul><ul><ul><ul><li>$1</li></ul></ul></ul></ul>');
r = r.replace(/^\*\*\* (.*)/gm, '<ul><ul><ul><li>$1</li></ul></ul></ul>');
r = r.replace(/^\*\* (.*)/gm, '<ul><ul><li>$1</li></ul></ul>');
r = r.replace(/^\* (.*)/gm, '<ul><li>$1</li></ul>');
for (ii = 0; ii < 3; ii++) r = r.replace(new RegExp('</ul>' + newline + '<ul>', 'g'), newline);
// ordered lists
r = r.replace(/^#### (.*)/gm, '<ol><ol><ol><ol><li>$1</li></ol></ol></ol></ol>');
r = r.replace(/^### (.*)/gm, '<ol><ol><ol><li>$1</li></ol></ol></ol>');
r = r.replace(/^## (.*)/gm, '<ol><ol><li>$1</li></ol></ol>');
r = r.replace(/^# (.*)/gm, '<ol><li>$1</li></ol>');
for (ii = 0; ii < 3; ii++) r = r.replace(new RegExp('</ol>' + newline + '<ol>', 'g'), newline);
// links
r = r.replace(/\[\[(http:[^\]|]*?)\]\]/g, '<a target="_blank" href="$1">$1</a>');
r = r.replace(/\[\[(http:[^|]*?)\|(.*?)\]\]/g, '<a target="_blank" href="$1">$2</a>');
r = r.replace(/\[\[([^\]|]*?)\]\]/g, '<a href="$1">$1</a>');
r = r.replace(/\[\[([^|]*?)\|(.*?)\]\]/g, '<a href="$1">$2</a>');
// images
r = r.replace(/{{([^\]|]*?)}}/g, '<img src="$1">');
r = r.replace(/{{([^|]*?)\|(.*?)}}/g, '<img src="$1" alt="$2">');
// video
r = r.replace(/<<(.*?)>>/g, '<embed class="video" src="$1" allowfullscreen="true" allowscriptaccess="never" type="application/x-shockwave/flash"></embed>');
// hard linebreak if there are 2 or more spaces at the end of a line
r = r.replace(new RegExp(' + ' + newline, 'g'), '<br>' + newline);
// split on double-newlines, then add paragraph tags when the first tag isn't a block level element
if (newline != '') for (var p = r.split(newline + newline), i = 0; i < p.length; i++) {
var blockLevel = false;
if (p[i].length >= 1 && p[i].charAt(0) == '<') {
// check if the first tag is a block-level element
var firstSpace = p[i].indexOf(' '), firstCloseTag = p[i].indexOf('>');
var endIndex = firstSpace > -1 && firstCloseTag > -1 ? Math.min(firstSpace, firstCloseTag) : firstSpace > -1 ? firstSpace : firstCloseTag;
var tag = p[i].substring(1, endIndex).toLowerCase();
for (var j = 0; j < blockLevelElements.length; j++) if (blockLevelElements[j] == tag) blockLevel = true;
} else if (p[i].length >= 1 && p[i].charAt(0) == '|') {
// format the paragraph as a table
blockLevel = true;
p[i] = p[i].replace(/ \|= /g, '</th><th>').replace(/\|= /g, '<tr><th>').replace(/ \|=/g, '</th></tr>');
p[i] = p[i].replace(/ \| /g, '</td><td>').replace(/\| /g, '<tr><td>').replace(/ \|/g, '</td></tr>');
p[i] = '<table>' + p[i] + '</table>';
} else if (p[i].length >= 2 && p[i].charAt(0) == '>' && p[i].charAt(1) == ' ') {
// format the paragraph as a blockquote
blockLevel = true;
p[i] = '<blockquote>' + p[i].replace(/^> /gm, '') + '</blockquote>';
}
if (!blockLevel) p[i] = '<p>' + p[i] + '</p>';
}
// reassemble the paragraphs
if (newline != '') r = p.join(newline + newline);
// restore the preformatted and unformatted blocks
r = r.replace(new RegExp('<pre></pre>', 'g'), function (match) { return '<pre>' + pre2.shift() + '</pre>'; });
r = r.replace(/CONSTANT "{": not defined !}/g, function (match) { return pre1.shift(); });
return r;
}
};
// markdown.parse(myText)
/*
= Heading 1
== Heading 2
=== Heading 3
==== Heading 4
**bold**
//italic//
* Bullet list
* Second item
** Sub item
# Numbered list
# Second item
## Sub item
[[link]]
CONSTANT "image": not defined !
<<video>>
|= table |= hdr |=
| table | row |
| table | row |
> blockquote
CONSTANT "{ unformatted text": not defined !}
--- horizontal rule
*/
<script>
function redimtextareas(obj){
obj.style.height='500px';
obj.style.height = obj.scrollHeight + 20 + 'px';
}
</script>
html:
<textarea name="nom" onFocus="redimtextarea(this);" onKeydown="redimtextarea(this);"></textarea>
css:
textarea{overflow:hidden; /* éviter les scrollbars*/}
/* CSS */
<style>
.fadein .carrousel .links{clear:both;width:100%;txtr}
.fadein { position:relative; width:100%; height:300px; }
.fadein .carrousel { position:absolute; left:0; top:0; }
</style>
/* HTML */
<div class="fadein">
<div class="carrousel car1">
<div class="content">
<h1>Titre du premier</h1>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupihref="" datat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="links">
<em>1</em>
<a href="" data="car2">2</a>
<a href="" data="car3">3</a>
</div>
</div>
<div class="carrousel car2">
<div class="content">
Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupit non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="links">
<a href="" data="car1">1</a>
<em>2</em>
<a href="" data="car3">3</a>
</div>
</div>
<div class="carrousel car3">
<div class="content">
</div>
<div class="links">
<a href="" data="car1">2</a>
<a href="" data="car2">3</a>
<em>3</em>
</div>
</div>
</div>
/* JS/JQuery */
<script>
$('.fadein .carrousel:gt(0)').hide();compteur=0;
function slideshow(){
z=setInterval(
function(){
compteur++;
if (compteur==4){montre=1;cache=3;compteur=1;}
else if (compteur>1){montre=compteur;cache=compteur-1;}
else if (compteur==1){montre=1;cache=3;}
$('.fadein > .car'+cache).fadeOut(500)
.parent().find('.car'+montre).fadeIn(500)
.end();
}
,5000);
return z;
}
slide=slideshow();
// si on survole, pause
$('.fadein').hover(function(ev){
clearInterval(slide);
}, function(ev){
slide = slideshow();
}
);
// clic sur un lien pour changer de diapo
$('.links a').click(function(){
car=$(this).attr('data');
$('.fadein > .carrousel').fadeOut(500)
.parent().find('.car'+car).fadeIn(500)
.end();
compteur=car;
return false;
});
</script>
(via HollandaisVolant)
Faire des variables dynamiques en JS.
Un trop dont je ne me sert jamais, mais là ouais.
// En gros, si t’as ça :
var variable = 'machin';
var machin = document.getElementById('id');
// on peut faire :
eval(variable).style.display = 'block';
// variable contient « machin ».
// en faisant le eval(), c’est comme si le contenu de "variable" devenait une variable. Ici, donc, le #id aura comme display un « block ».
// Pratique si on n’a pas envie de faire un « getElementById » pour 50 blocs à la fois, mais qu’on peut écrire dans un boucle avec ça.
Ça existe aussi en PHP :
$var = nombre;
$nombre = 137;
$$var = 42;
/*
Helper functions for RegexPal
(c) 2007 Steven Levithan <http://stevenlevithan.com>
MIT license
*/
function $ (el) {
if (el.nodeName) return el;
if (typeof el === "string") return document.getElementById(el);
return false;
};
var trim = function () {
// See <http://blog.stevenlevithan.com/archives/faster-trim-javascript>
var lSpace = /^ss*/,
rSpace = /ss*$/;
return function (str) {
return str.replace(lSpace, "").replace(rSpace, "");
};
}();
// This is much faster than simple use of innerHTML in some browsers
// See <http://blog.stevenlevithan.com/archives/faster-than-innerhtml>
function replaceHtml (el, html) {
var oldEl = $(el);
/*@cc_on // Pure innerHTML is slightly faster in IE
oldEl.innerHTML = html;
return oldEl;
@*/
var newEl = oldEl.cloneNode(false);
newEl.innerHTML = html;
oldEl.parentNode.replaceChild(newEl, oldEl);
/* Since we just removed the old element from the DOM, return a reference
to the new element, which can be used to restore variable references. */
return newEl;
};
/* outerHTML is used to work around the fact that IE applies text normalization when using innerHTML,
which can cause problems with whitespace, etc. Note that even this approach doesn't work with some
elements such as <div>. However, it mostly works with <pre> elements, at least. */
function replaceOuterHtml (el, html) {
el = replaceHtml(el, "");
if (el.outerHTML) { // If IE
var id = el.id,
className = el.className,
nodeName = el.nodeName;
el.outerHTML = "<" + nodeName + " id="" + id + "" class="" + className + "">" + html + "</" + nodeName + ">";
el = $(id); // Reassign, since we just overwrote the element in the DOM
} else {
el.innerHTML = html;
}
return el;
};
// Return an array of all elements with a specified class name, optionally filtered by tag name and parent
function getElementsByClassName (className, tagName, parentNode) {
var els = ($(parentNode) || document).getElementsByTagName(tagName || "*"),
results = [];
for (var i = 0; i < els.length; i++) {
if (hasClass(className, els[i])) results.push(els[i]);
}
return results;
};
function hasClass (className, el) {
/* It might not make sense to cache all regexes in a more widely used hasClass function,
but RegexPal uses it with a small number of classes so there is little memory overhead. */
return XRegExp.cache("(?:^|s)" + className + "(?:s|$)").test($(el).className);
};
function addClass (className, el) {
el = $(el);
if (!hasClass(className, el)) {
el.className = trim(el.className + " " + className);
}
};
function removeClass (className, el) {
el = $(el);
el.className = trim(el.className.replace(XRegExp.cache("(?:^|s)" + className + "(?:s|$)", "g"), " "));
};
function toggleClass (className, el) {
if (hasClass(className, el)) {
removeClass(className, el);
} else {
addClass(className, el);
}
};
function swapClass (oldClass, newClass, el) {
removeClass(oldClass, el);
addClass(newClass, el);
};
function replaceSelection (textbox, str) {
if (textbox.setSelectionRange) {
var start = textbox.selectionStart,
end = textbox.selectionEnd,
offset = (start + str.length);
textbox.value = (textbox.value.substring(0, start) + str + textbox.value.substring(end));
textbox.setSelectionRange(offset, offset);
} else if (document.selection) { // If IE (Opera has setSelectionRange and Selection objects)
var range = document.selection.createRange();
range.text = str;
range.select();
}
};
function extend (to, from) {
for (var property in from) to[property] = from[property];
return to;
};
// purge by Douglas Crockford <http://javascript.crockford.com/memory/leak.html>
function purge (d) {
var a = d.attributes, i, l, n;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
};
// Sniff
var isWebKit = navigator.userAgent.indexOf("WebKit") > -1,
isIE /*@cc_on = true @*/,
isIE6 = isIE && !window.XMLHttpRequest; // Despite the variable name, this means if IE lower than v7
// RegexPal also needs an Array.prototype.indexOf method, but it's provided by XRegExp
<!--[if IE]><script> document.createElement("article");document.createElement("aside");document.createElement("section");document.createElement("footer");</script> <![endif]-->
/*
addEvent — cette fonction écrite par John Resig , à l’origine de jQuery , a gagné le concours addEvent() recoding contest . Elle permet tout simplement d’attacher une fonction à un événement (onload, onclick, onmouseover, etc) :*/
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
//En prime, voici la fonction inverse, au cas où :
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, obj[type+fn] );
obj[type+fn] = null;
} else
obj.removeEventListener( type, fn, false );
}
/*Quelques exemples d’utilisation :
addEvent( document.getElementById('foo'), 'click', doSomething );
addEvent( obj, 'mouseover', function(){ alert('hello!'); } );
addEvent( window, 'load', maFonction );
Le dernier exemple est idéal pour lancer une fonction au chargement de la page sans intrusion dans le code HTML !*/
body onload="document.getElementById('nom').focus()">
<label for="nom">Nom : </label>
<input type="text" name="nom" id="nom" />
</body>
CSS DE LA LIGHTBOX
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
CONTENU DE LA LIGHTBOX
<div id="light" class="white_content">Hi, I am an happy lightbox</div><div id="fade" class="black_overlay"></div>
APPEL DE LA LIGHTBOX
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">Click me</a>
LIEN POUR FERMER LA LIGHTBOX
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Hide me</a>