Membership index
NOTE:
NOTA:
Downloads reserved for members can also be made without registration with a free donation in support of the site.
I download riservati ai membri possono essere effettuati anche senza registrazione con una donazione libera in sostegno del sito.
List of downloadable sresources with donationLista delle risorse scaricabili con donazione
Review of solutions for different problems in Javascript code.
Rassegna di soluzioni per differenti problematiche in codice Javascript.
NOTA: per provare i codici, puoi utilizzare l'HTML Editor.
NOTE: to test the codes you can use the HTML Editor.
Special characters in regular expressions
Caratteri speciali nelle espressioni regolari
\a the beginning of the text
\A beep
\b leading or trailing edge of the word
\B the word except the leading or trailing edge
\c the control code (Ctrl)
\d only the digits (digits)
\D everything except digits
\e the escape code
\f the end of the page
\n the end of the line
\r the carriage return
\s the space
\S everything but space
\t the horizontal tab
\v the vertical tab
\w the character of a word
\W everything except a word character
\Z the end of the text
\a inizio del testo
\A segnale acustico
\b bordoiniziale o finale della parola
\B la parola tranne il bordo iniziale o finale
\c il codice di controllo (Ctrl)
\d solo le cifre ( digit )
\D tutto tranne le cifre
\e il codice di escape
\f la fine della pagina
\n la fine della riga
\r ilritorno a capo
\s lospazio
\S tutto tranne lo spazio
\t la tabulazione orizzontale
\v la tabulazione verticale
\w il carattere di una parola
\W tutto tranne il carattere di una parola
\Z la fine del testo
Per approfondimentoFor information:
https://www.mpi.nl/corpus/html/trova/ch01s04.html
New line in javascript
Andare a capo in javascript
To go to new line with the text in a javascript code the symbol to use is \n
Example in alert:
Per andare a capo con il testo in un codice javascript si usa il simbolo \n
Esempio in alert:
<button onclick="myFunction()">Apri</button>
<script>
function myFunction() {
alert("Testo\nTesto");
}
</script>
Multiple functions with single click
Multiple funzioni con un unico click
onclick="One(); Two(); Three()"
Adjust Iframes script
18a-Script to make iframes responsive even in height.
18a-Script per rendere responsive gli iframe anche in altezza.
Need jQuery.
Necessita di jQuery.
Download for memberDownload with donation
Change text color onclick
Cambiare il colore del testo al click
Script to choose the text color.
Script per la scelta del colore del testo.
<script>
function changeColor() {
var newColor = document.getElementById('colorPicker').value;
document.body.style.color = newColor;
}
</script>
<span id="colorMsg">Choose text color...</span>
<select id="colorPicker" onchange="JavaScript:changeColor()">
<option value="black">Black</option>
<option value="yellow">Yellow</option>
<option value="salmon">Salmon</option>
<option value="lightblue">Light Blue</option>
<option value="limegreen">Lime Green</option>
</select>
Change text and text color onclick
Cambiare il testo e il colore del testo al click
<p id="champAChanger">Click</p>
<button type="button" onclick="myFunctionDEtat()">Change</button>
<script>
function myFunctionDEtat()
{
if( maVariableDEtat < MAX_ETAT )
maVariableDEtat++;
else
maVariableDEtat = 1;
switch( maVariableDEtat )
{
case 1:
document.getElementById( "champAChanger" ).innerHTML = "Click";
document.getElementById( "champAChanger" ).setAttribute( "style", "color:#ff00ff" );
break;
case 2:
document.getElementById( "champAChanger" ).innerHTML = "Click2";
document.getElementById( "champAChanger" ).setAttribute( "style", "backcolor:#00ffff" );
break;
case 3:
document.getElementById( "champAChanger" ).innerHTML = "Click3";
document.getElementById( "champAChanger" ).setAttribute( "style", "color:#ffff00" );
break;
default:
document.getElementById( "champAChanger" ).innerHTML = "HELLO";
break;
}
}
var maVariableDEtat = 1;
const MAX_ETAT = 3;
document.getElementById( "champAChanger" ).setAttribute( "style", "color:#ff00ff" );
</script>
Change page color onclick
Cambiare il colore della pagina al click
Script to choose the page color.
Script per la scelta del colore della pagina.
<script>
function changeColor() {
var newColor = document.getElementById('colorPicker').value;
document.body.style.background = newColor;
}
</script>
<h4 id="colorMsg">Choose a background color...</div>
<select id="colorPicker" onchange="JavaScript:changeColor()">
<option value="transparent">None</option>
<option value="#FBBC05">Yellow</option>
<option value="salmon">Salmon</option>
<option value="lightblue">Light Blue</option>
<option value="limegreen">Lime Green</option>
</select>
Change page and text color onclick
Cambiare il colore della pagina e del testo al click
Script to change the background color of the page and the color of the text by clicking on the background.
Script per cambiare il colore di fondo della pagina e il colore del testo al click sullo sfondo.
<style>
.changecolor {
background-color: lime;
color: red;
}
</style>
<p>Page content</p>
<script>
window.onclick = function(){
document.getElementsByTagName("BODY")[0].classList.toggle("changecolor");
};
</script>
Change header background color on scroll
Cambiare il colore di background dell'header allo scroll
Script to change the background color of the fixed header (or other container) on page scroll.
Script per cambiare il colore di fondo dell'header fisso (o altro contenitore) allo scroll della pagina.
<style>
header.active {
background-color: #cbcdce;
}
</style>
<script>
$(function() {
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$("nav").addClass("active");
} else {
$("header").removeClass("active");
}
});
});
</script>
Script to reverse list order onclick
Invertire l'ordine di una lista al click
Need jQuery.
Necessita di jQuery.
<div id="switch">Click to reverse the order</div>
<ul>
<li>pappa</li>
<li>ciccia</li>
<li>tizio</li>
<li>remo</li>
<li>dado</li>
</ul>
<script>
$('#switch').on('click', function() {
var el = $('ul li').get().reverse();
$('ul').append(el);
});
</script>
Script to reverse paragraph order onclick
Invertire l'ordine dei paragrafi al click
Need jQuery.
Necessita di jQuery.
<div id="switch">Click to reverse the order</div>
<div class="reverse">
<p>pappa</p>
<p>ciccia</p>
<p>tizio</p>
<p>remo</p>
<p>dado</p>
</div>
<script>
$('#switch').on('click', function() {
var el = $('.reverse p').get().reverse();
$('.reverse').append(el);
});
</script>
Details, summary, open
Details, summary, open
Curtain always open when loading.
Tendina sempre aperta al caricamento.
<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>
<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>
<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>
<script>
// Open all details elements, onload
document.body.querySelectorAll('details')
.forEach((e) => {(e.hasAttribute('open')) ?
e.removeAttribute('open') : e.setAttribute('open',true);
console.log(e.hasAttribute('open'))
})
</script>
Signature protection script
Protezione della firma
Useful, for example, to protect the author's signature in a template and prevent it from being deleted.
Utile, per esempio, per proteggere la firma dell'autore in un template ed evitare che venga cancellata.
<!DOCTYPE html>
<html>
<head>
<style>
#by {
cursor: pointer;
color: #000;
}
</style>
</head>
<body>
<p id="by"></p>
<script>
var myElem = document.getElementById('by');
if (myElem === null) alert('You may not remove the designer signature!\n\n\t\t\t\t\t\t www.nomesito.com'); //messaggio di avviso
var p = document.getElementById('by');
p.innerHTML += 'Firma'; //inserire il testo della firma
</script>
</body>
</html>
Document protection script
Protezione di un documento
Useful, for example, to protect the legal documents of the website.
Utile, per esempio, per proteggere i documenti legali del sito.
<script>
$('.doc').bind('contextmenu selectstart dragstart keydown mousedown', function(e) {
return false;
});
</script>
Page content protection script
Protezione dei contenuti di una pagina
The script adds a copyright notice with link to the source page to the content copied by a user .
Lo script aggiunge un avviso di copyright con link alla pagina d'origine al contenuto copiato da un utente.
<script>
function addLink() {
var selection = window.getSelection();
pagelink = "<br>Copyright protected content. Read more at: " + document.location.href;
copytext = selection + pagelink;
newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
}
document.addEventListener('copy', addLink);
</script>
Return to previous page
Tornare alla pagina precedente
Button:
<input class="back" type="button" onclick="history.back();" value="Back">
Link:
<a href="#" onclick="history.back();">Back</a>
Disable browsers' back button
Disabilitare il ritorno del browser alla pagina precedente
<script>
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
}
</script
Close the current browser tab
Chiudere la scheda corrente del browser
<p><input type="button" value="Close Tab" onclick="closeCurrentTab()"></p>
<script type="text/javascript">
function closeCurrentTab(){
var conf=confirm("Are you sure, you want to close this tab?");
if(conf==true){
close();
}
}
</script>
Alert when internet connection is gone
Avviso sulla pagina quando viene persa la connessione
If the user loses the connection, a warning appears above the web page.
Se l'utente perde la connessione, appare un avviso sulla pagina del sito che era attiva in quel momento.
<script>
window.addEventListener('offline', function(event){ alert("You are offline please turn on internet connection to run website");});
</script>
Simple redirect
Redirect semplice
Instant redirect
Redirect istantaneo
<script>
window.location.replace("https://www.sitename.com");
</script>
or:
oppure:
<script>
window.location.href = "https://www.sitename.com";
</script>
The difference between replace and location is that replace removes the URL of the page from the chronology and it is not possible to use the browser back button.
La differenza tra replace e location è che replace rimuove l'url dalla cronologia ed è impossibile tornare indietro tramite il browser.
Redirect con timeout
Redirect con timeout
<script>
setTimeout(function() {
window.location = './protezione3.php';
}, 1000);
</script>
18b-Detect Adblock and redirect and show alternative content
18b-Rilevazione Adblock e mostrare contenuti alternativi
Script that replaces ads with other content if the visitor has an active adblock in their browser.
Script che sostituisce gli annunci con altro contenuto se il visitatore ha un adblock attivo nel suo browser.
Download for member
Download with donation
18c-Redirect with countdown
18c-Redirect con conto alla rovescia
Script that redirects to a new page at the end of a countdown with an established number of seconds.
Script che reindirizza ad una nuova pagina al termine di un conto alla rovescia con numero di secondi stabilito.
Download for member
Download with donation
Download + redirect
Link for downloading a file with simultaneous redirect to a new web page.
Link per il download di un file con contemporaneo redirect ad una nuova pagina web.
<html>
<body>
<a href="file.zip" onClick="triggerTime()">link</a>
<script>
function Redirect() {
// The URL between the quotation marks may be changed.
window.open('https://www.nomesito.com', '_blank');
}
function triggerTime(){
setTimeout("Redirect()",2000); //redirect delay
}
</script>
</body>
</html>
Redirect based on browser language
Redirect in base alla lingua del browser
<script>
var language = navigator.language || navigator.userLanguage;
language = language.substring( 0, 2 );
if (language == "en"){
window.location.href = "path to/page.html"; // English
}
else if (language == "fr"){
window.location.href = "path to/page.html"; // French
}
else if (language == "es"){
window.location.href = "path to/page.html"; // Spanish
}
else {
window.location.href = "/index.html"; // everyone else : your site url
}
</script>
18d-Show content by lang
18d-Contenuti secondo la lingua del browser
Script showing different contents according to the browser language.
Script che mostra contenuti differenti secondo la lingua del browser.
Download for member
Download with donation
Refresh page button
Pulsante aggiorna pagina
<a href="#" onclick="window.location.reload(true);return false;">reload</a>
Web push notifications - activation button
Notifiche web push - pulsante di attivazione
<html>
<body>
<button onclick="notifyMe()">Notify Me</button>
<script>
function notifyMe() {
if (!window.Notification) {
console.log('Browser does not support notifications.');
} else {
// check if permission is already granted
if (Notification.permission === 'granted') {
// show notification here
var notify = new Notification('Hi there!', {
body: 'How are you doing?',
icon: 'https://img.icons8.com/ios-glyphs/2x/alarm.png',
});
} else {
// request permission from user
Notification.requestPermission().then(function (p) {
if (p === 'granted') {
// show notification here
var notify = new Notification('Hi there!', {
body: 'How are you doing?',
icon: 'https://img.icons8.com/ios-glyphs/2x/alarm.png',
});
} else {
console.log('User blocked notifications.');
}
}).catch(function (err) {
console.error(err);
});
}
}
}
</script>
</body>
</html>
Change text using javascript
Cambiare un testo con javascript
<div id="demo">Original text</div>
<script>
document.getElementById("demo").innerHTML = "Replaced text";
</script>
Copy text on click on it
Copiare testo al click su di esso
<p class="guide" onclick="copyDivToClipboard()">Text to copy</p>
<script>
function copyDivToClipboard() {
var range = document.getSelection().getRangeAt(0);
range.selectNode(document.getElementsByClassName("guide")[0]);
window.getSelection().addRange(range);
document.execCommand("copy");
alert("text copied")
}
</script>
Copy text on button click
Copiare testo al click su un pulsante
<div class="code-bg" id="divClipboard">
Text to copy
</div>
<br>
<button id="flick" onclick="copyClipboard()">Copy</button>
<script>
function copyClipboard() {
var elm = document.getElementById("divClipboard");
const btnText = document.querySelector("#flick");
if(window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(elm);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
//for alert:
//alert("Copied div content to clipboard");
//for button text:
btnText.textContent = "Copied!";
setTimeout(function(){
btnText.textContent = "Copy";
}, 3000); //restores the text after the set milliseconds
}
}
</script>
Screenshot on button click
Screenshot al click su un pulsante
<style>
.btn {
display: block;
margin: 20px 0;
padding: 6px 12px;
text-align: center;
border: 1px solid;
border-radius: 4px;
border-color: #ccc;
}
</style>
<div class="specific">
Page content here.
<button type="button" class="btn btn-default">Take a Screenshot!</button>
</div>
<script>
document.querySelector('button').addEventListener('click', function () {
html2canvas(document.querySelector('.specific'), {
onrendered: function (canvas) {
// document.body.appendChild(canvas);
return Canvas2Image.saveAsPNG(canvas);
} });
});
</script>
Export content as HTML
Esportare contenuto come HTML
<div id="content">
<p>Hello world</p>
</div>
<script>
var a = document.body.appendChild(
document.createElement("a")
);
a.download = "export.html";
a.href = "data:text/html," + document.getElementById("content").innerHTML;
a.innerHTML = "[Export content]";
</script>
Disable right button, dragging and selecting content
Disabilitare tasto dx, trascinamento e selezione di un contenuto
<script>
$('.doc').bind('contextmenu selectstart dragstart keydown mousedown', function(e) { //your container class in place of .doc
return false;
});
</script>
Disable right button on images
Disabilitare il tasto dx sulle immagini
Script that requires jQuery.
Script che necessita di jQuery.
<script>
function nocontext(e) {
var clickedTag = (e==null) ? event.srcElement.tagName : e.target.tagName;
if (clickedTag == "IMG") {
return false;
}
}
document.oncontextmenu = nocontext;
</script>
Exclude functions according to the screen width
Escludere funzioni secondo la larghezza dello schermo
Useful, for example, to disable a script only on mobile.
Utile, per esempio, per disabilitare uno script solo su mobile.
<script>
if($(window).width() >= 1024){
// your stuff here
}
</script>
Exclude remove one or more classes according to the screen width
Rimuovere una, o più classi di stile secondo la larghezza dello schermo
<script>
if($(window).width() >= 1024){
const div = document.querySelector('img');
div.classList.remove('first','second');
}
</script>
Show/hide an element based on the presence of another specific element
Mostrare o nascondere un elemento in base alla presenza di un altro elemento specifico
Script that requires jQuery.
Script che necessita di jQuery.
<div class="firstElement">first</div>
<div class="secondElement">second</div>
<script>
if($('.firstElement').length){ // returns true if element is present
// show or hide another div
$('.secondElement').show();
} else {
$('.secondElement').hide();
}
</script>
Count and show onclick child elements number in parent div
Contare e mostrare al click il numero di elementi figli in un div genitore
<button onclick="myFunction()">Click</button>
<p id="number"></p>
<div id="container">
<div>first child element</div>
<div>second child element</div>
<div>third child element</div>
-------
</div>
<script>
function myFunction() {
var c = document.getElementById("container").childElementCount;
document.getElementById("number").innerHTML = c;
$('#number').css({
'border': '1px solid #f86f0b',
'width': '100px',
'margin': '0 auto'
});
}
Prevent page images caching
Impedire la cache di specifiche immagini di una pagina
Script that requires jQuery.
NOTE: it also works on mobile Safari
Lo script necessita di jQuery.
NOTA: funziona anche su Safari mobile.
<img class="no-cache" src="01.jpg">
<script>
$(document).ready(function ()
{
$('.no-cache').attr('src',function () { return $(this).attr('src') + "?a=" + Math.random() });
});
</script>
Prevent stylesheet caching
Impedire la cache del foglio di stile
<script>
refreshCSS = () => {
let links = document.getElementsByTagName('link');
for (let i = 0; i < links.length; i++) {
if (links[i].getAttribute('rel') == 'stylesheet') {
let href = links[i].getAttribute('href')
.split('?')[0];
let newHref = href + '?version='
+ new Date().getMilliseconds();
links[i].setAttribute('href', newHref);
}
}
}
</script>;
Prevent htlm page caching
Impedire la cache di una pagina html
<script>
window.location.reload(true)
</script>
Membership index
Share on Social:
Condividi sui social: