JavaScript - Snippets: Unterschied zwischen den Versionen
Steff (Diskussion | Beiträge) (→Links) |
|||
| (26 dazwischenliegende Versionen von 5 Benutzern werden nicht angezeigt) | |||
| Zeile 2: | Zeile 2: | ||
Siehe auch | Siehe auch | ||
| − | [[JavaScript - Plugins]] | + | [[JavaScript - Plugins]] |
| − | + | [[JavaScripts - Basics]] | |
| − | [[JavaScripts - Basics]] | + | [[JavaScript - DOM Manipulation]] |
| − | + | [[jQuery - Snippets]] | |
| − | [[jQuery - Snippets]] | + | [[Browser Fallbacks]] |
| − | + | https://wiki.stephanschlegel.de/index.php?title=JQuery_vs_Vanilla_JavaScript | |
| − | [[Browser Fallbacks]] | ||
== Sonderzeichen in Alert-Meldungen == | == Sonderzeichen in Alert-Meldungen == | ||
| Zeile 198: | Zeile 197: | ||
Viel mehr gibt’s eigentlich nicht dazu zu sagen – die Dokumentation dazu findet man, genau wie das Plugin selbst, unter http://plugins.jquery.com/project/timers. | Viel mehr gibt’s eigentlich nicht dazu zu sagen – die Dokumentation dazu findet man, genau wie das Plugin selbst, unter http://plugins.jquery.com/project/timers. | ||
| + | |||
| + | == Arrays == | ||
| + | === Elemente hinzufügen / entfernen === | ||
| + | Gegeben ist ein Array items in der Art | ||
| + | [{id: 1, name: Anton, isFavourite: true}, {id: 2, name: Berta},...] | ||
| + | |||
| + | <syntaxhighlight lang="javascript"> | ||
| + | // add to end of array | ||
| + | this.friends.push(newFriend) | ||
| + | |||
| + | // add to start of array | ||
| + | this.friends.unshift(newFriend) | ||
| + | |||
| + | // delete item from array via id - v1 -> override complete array | ||
| + | deleteItem(id){ | ||
| + | this.items = this.items.filter( item => item.id !== sarchId) | ||
| + | // filter( filterFunction ) uses filterFunction for every item in items. | ||
| + | // If filterFunction returns true the item is kept. item.id !== id returns true for every | ||
| + | // item which has NOT the id | ||
| + | } | ||
| + | |||
| + | // v2 - change array | ||
| + | deleteItem(id){ | ||
| + | const itemIndex = this.items.findIndex(item => item.id === id) | ||
| + | this.items.splice(resIndex, 1); | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | === Finden und Suchen === | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | // find in array and change prop | ||
| + | const identifiedItem = this.items.find( | ||
| + | (item) => item.id === searchId // the same as function(friend){return friend.id...} | ||
| + | ) | ||
| + | // filter(callback) - callback is executed on every array (array item) first item match is returned | ||
| + | identifiedItem.isFavourite = !identifiedItem.isFavourite | ||
| + | // identifiedItem is a proxy connected to the original items array. | ||
| + | // thus why we can modify identifiedItems and items will be altered too | ||
| + | </syntaxhighlight> | ||
== JavaScript - Objekte == | == JavaScript - Objekte == | ||
[[JavaScript - Objektorientierte Programmierung]] | [[JavaScript - Objektorientierte Programmierung]] | ||
| + | |||
=== Objekte löschen === | === Objekte löschen === | ||
for (prop in allOverlays) { if (allOverlays.hasOwnProperty(prop)) { delete allOverlays[prop]; } } //ie 6 gc problems | for (prop in allOverlays) { if (allOverlays.hasOwnProperty(prop)) { delete allOverlays[prop]; } } //ie 6 gc problems | ||
| Zeile 207: | Zeile 246: | ||
== JavaScript - Strings == | == JavaScript - Strings == | ||
[[JavaScript - Strings]] | [[JavaScript - Strings]] | ||
| + | |||
| + | == JavaScript - Numbers == | ||
| + | const x = '1' | ||
| + | const y = +x // y is a number now | ||
| + | const y = x.parseInt() | ||
| + | |||
| + | == Viewport / Offset / Scrolling == | ||
| + | === Element sichtbar im Viewport === | ||
| + | ==== Kommt in den Viewport mit Self-Destroy ==== | ||
| + | Wird nur einmal ausgeführt | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | document.body.onscroll = function() { | ||
| + | if (document.getElementById("viewElement").getBoundingClientRect().bottom <= window.innerHeight) { | ||
| + | document.body.onscroll = ""; | ||
| + | alert("The tag just came into view"); | ||
| + | } | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ==== Komplett im Viewport ==== | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | function isInViewport(el) { | ||
| + | const rect = el.getBoundingClientRect(); | ||
| + | return ( | ||
| + | rect.top >= 0 && | ||
| + | rect.left >= 0 && | ||
| + | rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && | ||
| + | rect.right <= (window.innerWidth || document.documentElement.clientWidth) | ||
| + | |||
| + | ); | ||
| + | } | ||
| + | |||
| + | |||
| + | const box = document.querySelector('.box'); | ||
| + | const message = document.querySelector('#message'); | ||
| + | |||
| + | document.addEventListener('scroll', function () { | ||
| + | const messageText = isInViewport(box) ? | ||
| + | 'The box is visible in the viewport' : | ||
| + | 'The box is not visible in the viewport'; | ||
| + | |||
| + | message.textContent = messageText; | ||
| + | |||
| + | }, { | ||
| + | passive: true | ||
| + | }); | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ==== Teil im Viewport ==== | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | /** | ||
| + | * checks if any part of the element is in viewport | ||
| + | */ | ||
| + | function isInViewport(el){ | ||
| + | h = el.height(); | ||
| + | hVp = $(window).height(); | ||
| + | posY = el.offset().top - $(window).scrollTop(); | ||
| + | dh = posY+h; | ||
| + | // dh < 0 -> oben raus | ||
| + | // posY > hVp -> unten raus | ||
| + | if ( dh < 0 || posY > hVp ) return false; | ||
| + | else return true; | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | ==== Funktion mit GSAP ScrollTrigger starten ==== | ||
| + | Counter Beispiel | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | function count(){ | ||
| + | $('.counter').each(function() { | ||
| + | var $this = $(this), countTo = $this.attr('data-count'); | ||
| + | $({ countNum: $this.text()}).animate({ | ||
| + | countNum: countTo | ||
| + | }, | ||
| + | { | ||
| + | duration: 5000, | ||
| + | easing:'linear', | ||
| + | step: function() { | ||
| + | $this.text(Math.floor(this.countNum)); | ||
| + | }, | ||
| + | complete: function() { | ||
| + | $this.text(this.countNum); | ||
| + | //alert('finished'); | ||
| + | } | ||
| + | }); | ||
| + | }); | ||
| + | |||
| + | } | ||
| + | |||
| + | ScrollTrigger.create({ | ||
| + | trigger: '#counterTrigger', | ||
| + | onEnter: ()=>{ | ||
| + | console.log('count') | ||
| + | count() | ||
| + | }, | ||
| + | |||
| + | }); | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ==== Scrollbar mit Hide/Show Funktion beim Scrollen ==== | ||
| + | Verstecke Navbar beim runterscrollen zeige beim hochscrollen. | ||
| + | |||
| + | <syntaxhighlight lang="javascript"> | ||
| + | document.addEventListener('DOMContentLoaded', function(event) { | ||
| + | var lastScrollTop = 0; | ||
| + | var navbar = document.querySelector('.hd'); | ||
| + | var navbarHeight = navbar.offsetHeight; | ||
| + | |||
| + | function handleScroll() { | ||
| + | var scrollTop = window.scrollY; | ||
| + | |||
| + | if (scrollTop > lastScrollTop) { | ||
| + | // Beim Herunterscrollen | ||
| + | navbar.style.transform = 'translateY(-' + navbarHeight + 'px)'; | ||
| + | } else { | ||
| + | // Beim Hochscrollen | ||
| + | navbar.style.transform = 'translateY(0)'; | ||
| + | } | ||
| + | |||
| + | if (scrollTop === 0) { | ||
| + | // Wenn die Seite ganz oben ist | ||
| + | navbar.classList.add('transparent'); | ||
| + | } else { | ||
| + | // Wenn die Seite nicht ganz oben ist | ||
| + | navbar.classList.remove('transparent'); | ||
| + | } | ||
| + | |||
| + | lastScrollTop = scrollTop; | ||
| + | } | ||
| + | |||
| + | // Initialer Aufruf bei Laden der Seite | ||
| + | handleScroll(); | ||
| + | |||
| + | window.addEventListener('scroll', handleScroll); | ||
| + | </syntaxhighlight> | ||
== JavaScript - HTML5 Audio == | == JavaScript - HTML5 Audio == | ||
| Zeile 243: | Zeile 416: | ||
=== Scrolling === | === Scrolling === | ||
| − | ==== Scroll & Sticky - Fixed Navbar ==== | + | ==== Smooth Scroll & Sticky - Fixed Navbar ==== |
jQuery | jQuery | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
| Zeile 276: | Zeile 449: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| − | ==== Smooth | + | ==== Smooth Scroll für Anchor Tags oder toTop Links ==== |
| + | https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link | ||
| + | noch ein Beispiel (Vanilla) | ||
| + | https://perishablepress.com/vanilla-javascript-scroll-anchor/ | ||
| + | |||
| + | ===== Beispiel ab 2018 ===== | ||
| + | Nutzt das CSS Verhalten (kann man auch direkt als CSS nutzen. Manchmal funktioniert es (Stand 2020) nicht ganz sauber. Safari und Edge funktionieren nicht mit dem CSS Behaviour | ||
| + | <pre> | ||
| + | document.querySelectorAll('a[href^="#"]').forEach(anchor => { | ||
| + | anchor.addEventListener('click', function (e) { | ||
| + | e.preventDefault(); | ||
| + | |||
| + | document.querySelector(this.getAttribute('href')).scrollIntoView({ | ||
| + | behavior: 'smooth' | ||
| + | }); | ||
| + | }); | ||
| + | }); | ||
| + | </pre> | ||
| + | |||
| + | For older browser support, you can use this jQuery technique: | ||
| + | <pre> | ||
| + | $(document).on('click', 'a[href^="#"]', function (event) { | ||
| + | event.preventDefault(); | ||
| + | |||
| + | $('html, body').animate({ | ||
| + | scrollTop: $($.attr(this, 'href')).offset().top | ||
| + | }, 500); | ||
| + | }); | ||
| + | </pre> | ||
| + | And here's the fiddle: http://jsfiddle.net/9SDLw/ | ||
| + | |||
| + | If your target element does not have an ID, and you're linking to it by its name, use this: | ||
| + | <pre> | ||
| + | $('a[href^="#"]').click(function () { | ||
| + | $('html, body').animate({ | ||
| + | scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top | ||
| + | }, 500); | ||
| + | |||
| + | return false; | ||
| + | }); | ||
| + | </pre> | ||
| + | |||
===== Beispiel 1 (jQuery) ===== | ===== Beispiel 1 (jQuery) ===== | ||
<pre> | <pre> | ||
| Zeile 301: | Zeile 515: | ||
.top-100 | .top-100 | ||
http://1stwebmagazine.com/jquery-scroll-to-anchor-point | http://1stwebmagazine.com/jquery-scroll-to-anchor-point | ||
| + | |||
| + | ==== Smooth Scrolling mit Vanilla JS ==== | ||
| + | [[JavaScript - Smooth Scrolling]] | ||
===== Beispiel 3 Materialize Pushpin ToTop ===== | ===== Beispiel 3 Materialize Pushpin ToTop ===== | ||
| Zeile 370: | Zeile 587: | ||
</script> | </script> | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| + | |||
| + | === Toggle === | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | <a href="javascript:void(0);" class="icon" onclick="myFunction()"> | ||
| + | <i class="fa fa-bars"></i> | ||
| + | </a> | ||
| + | oder registrieren | ||
| + | |||
| + | element.addEventListener('click', myFunctionReference , false); | ||
| + | |||
| + | function toggleNavigation() { | ||
| + | var x = document.getElementById("#mobileNavigationPanel"); | ||
| + | if (x.style.display === "block") { | ||
| + | x.style.display = "none"; | ||
| + | } else { | ||
| + | x.style.display = "block"; | ||
| + | } | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | === Zwischenablage (Clipboard) modifizieren === | ||
| + | https://developer.mozilla.org/en-US/docs/Web/API/Element/copy_event | ||
| + | Mit dem Copy Event kann man die Zwischenablage modifizieren wenn der User etwas hineinkopiert. Z.B. könnte das ein Copyright Hinweis sein, den man anhängt. | ||
| + | |||
| + | ==== Beispiel - Uppercase ==== | ||
| + | <syntaxhighlight lang="html5"> | ||
| + | |||
| + | <div class="source" contenteditable="true">Try copying text from this box...</div> | ||
| + | <div class="target" contenteditable="true">...and pasting it into this one</div> | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | <syntaxhighlight lang="javascript"> | ||
| + | const source = document.querySelector('div.source'); | ||
| + | |||
| + | source.addEventListener('copy', (event) => { | ||
| + | const selection = document.getSelection(); | ||
| + | event.clipboardData.setData('text/plain', selection.toString().toUpperCase()); | ||
| + | event.preventDefault(); | ||
| + | }); | ||
| + | |||
| + | </syntaxhighlight> | ||
| + | |||
| + | ==== Beispiel - Copyright Hinweis hinzufügen ==== | ||
| + | <syntaxhighlight lang="html5"> | ||
| + | <div class="box source" contenteditable="true">Kopiere Text aus dieser Box...</div> | ||
| + | <div class="box target" contenteditable="true">...in diese Box!</div> | ||
| + | |||
| + | |||
| + | <script> | ||
| + | const source = document.querySelector('div.source'); | ||
| + | var today = new Date(); | ||
| + | var dd = String(today.getDate()).padStart(2, '0'); | ||
| + | var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0! | ||
| + | var yyyy = today.getFullYear(); | ||
| + | copyDate = dd + '.' + mm + '.' + yyyy; | ||
| + | copyHint = '\nQuelle: ' + window.location.href + ' (Zugriff am: ' + copyDate + ')'; //href, hostname or pathname is possible | ||
| + | source.addEventListener('copy', (event) => { | ||
| + | const selection = document.getSelection(); | ||
| + | event.clipboardData.setData('text/plain', selection.toString() + copyHint); | ||
| + | event.preventDefault(); | ||
| + | }); | ||
| + | </script> | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | == Must Know - Wichtige JavaScript Snippets und Konzepte == | ||
| + | === Seite geladen? === | ||
| + | https://www.mediaevent.de/javascript/onload.html | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | window.onload = function () { | ||
| + | console.log('Dokument geladen'); | ||
| + | function init(); | ||
| + | function machwas(); | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | === Seite und Bilder geladen === | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | window.addEventListener('load', function () { | ||
| + | alert("It's loaded!") | ||
| + | }) | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | https://www.mediaevent.de/javascript/onload.html | ||
| + | <syntaxhighlight lang="javascript"> | ||
| + | let img = new Image; | ||
| + | |||
| + | img.onload = function() { | ||
| + | console.log ("Bild geladen"); | ||
| + | elem.appendChild (img); | ||
| + | } | ||
| + | img.src = "little-snail.png"; // erst nach dem Event Listener! | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | === Schriften geladen UND angewendet? === | ||
| + | Siehe | ||
| + | [[JavaScript - Webfont loaded?]] | ||
| + | |||
| + | |||
| + | fontsReady(); | ||
| + | === Seite verlassen === | ||
| + | https://www.mediaevent.de/javascript/onload.html | ||
| + | |||
| + | === Feature Detection === | ||
| + | Herausfinden was ein Browser unterstützt und darauf reagieren. | ||
| + | [[JavaScript - Feature Detection]] | ||
Aktuelle Version vom 10. Dezember 2024, 12:59 Uhr
Links[Bearbeiten]
Siehe auch
JavaScript - Plugins JavaScripts - Basics JavaScript - DOM Manipulation jQuery - Snippets Browser Fallbacks https://wiki.stephanschlegel.de/index.php?title=JQuery_vs_Vanilla_JavaScript
Sonderzeichen in Alert-Meldungen[Bearbeiten]
Oft sieht man im Web sehr hässliche alert-Meldungen , in denen die Umlaute nicht korrekt dargestellt sind. Das liegt auch daran, dass unterschiedliche Betriebssystem Zeichen unterschiedlich kodieren. Damit so etwas möglichst vermieden wird, sollte man solche Meldungen mit alert(unescape("...")) anzeigen.
Beispiel:
alert(unescape("So was d%E4mliches%21"));
Zeichen so verschlüsseln: \ \\ " \" ' \' Zeilenumbruch \n Wagenrücklauf \r (Den Unterschied zum Zeilenumbruch habe ich auch noch nicht begriffen.) Tabulator \t
Zeichen so:
Ä %C4
Ö %D6
Ü %DC
ä %E4
ö %F6
ü %FC
ß %DF
€ %u20AC
$ %24
% %25
Generier Tool: http://www.salesianer.de/util/alert-umlaute.html
Teil einer Seite drucken[Bearbeiten]
Old School JavaScript, sollte sich aber relativ einfach auf jQuery übertragen lassen.
Quelle: http://www.webstool.de/de/tipps_down_druck3.html Zugriff: 10/2011
Mit einem einfachen JavaScript lässt sich mit relativ wenig Aufwand eine druckerfreundliche Version einer Webseite bei Bedarf erzeugen.
Das JavaScript wird nachstehend vorgestellt:
function ausgabe()
{
var ref = document.getElementById("auswahl");
var ausgabe;
// nächste Zeile öffnet ein Fenster der Größe 800 x 600 Pixel
ausgabe=window.open("#","fenster","width=800,height=600,resizable=yes,menubar=yes,left=50,top=50");
ausgabe.document.open();
ausgabe.document.write('<html>\n<head>\n<title>Druckversion</title>\n');
ausgabe.document.write('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\n');
// in der nächsten Zeile an das eigene Stylesheet anpassen
ausgabe.document.write('<link rel="stylesheet" href="../css/design1.css">\n</head>\n');
ausgabe.document.write('<body>\n<h1 align="center">© web s tool - Partner für Ihren Internetauftritt</h1>\n');
ausgabe.document.write('<div>\n');
// Ausgabe aller Inhalte mit der id = auswahl
while (ref!=null)
{
ausgabe.document.write(ref.innerHTML + '\n');
ref = ref.nextSibling;
}
ausgabe.document.write('</div>\n<p align="center"><a href="javascript:window.print()">drucken</a></p>\n</body>\n</html>\n');
ausgabe.document.close();
ausgabe.focus();
}
Die externe Einbindung des JavaScripts erfolgt dabei z.B. im head-Bereich der Webseite über
<script language="JavaScript" src="../scripts/ausgabe4print.js"></script> .
Von entscheidender Bedeutung ist, dass auf der Seite das auszuwählende Objekt mit der id = "auswahl" (bitte bei Bedarf anpassen) versehen ist. Das auszuwählende Objekt kann dabei eine Tabelle oder ein div-Container sein.
Der Aufruf erfolgt z.B. durch den Link <a href="javascript:ausgabe();"> Druckversion</a>
Fehler Behandlung[Bearbeiten]
Prüfen ob ein Element existiert (normales JavaScript)[Bearbeiten]
function isElement(obj) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrom)
return obj instanceof HTMLElement;
}
catch(e){
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
Prüfen ob ein Element in einem Objekt-Literal existiert und nicht null ist[Bearbeiten]
var data = {
"key1" : val,
"key2" : val,
"key3" : val
}
if( "key2" in data && data.key2 != null){
...
}
Eingaben Validieren[Bearbeiten]
Handynummer validieren (normales JavaScript)[Bearbeiten]
function phone_is_valid(nr){
var reg2 = /^([0-9]{4,6})+\/([0-9]{6,11})$/;
return reg2.test(nr);
}
Datum validieren (normales JavaScript)[Bearbeiten]
function date_is_valid(myDate){
var isValid = false;
var today = new Date();
if (!myDate) return false;
myDate=myDate.toString();
arrDate=myDate.split(".");
if (arrDate.length!=3) return false;
arrDate[0]=parseInt(arrDate[0],10);
arrDate[1]=parseInt(arrDate[1],10)-1;
if (arrDate[2].length==2) arrDate[2]="20"+arrDate[2]
var kontrolldatum=new Date(arrDate[2],arrDate[1],arrDate[0]);
// Datum gültig ?
if (kontrolldatum.getDate()==arrDate[0] && kontrolldatum.getMonth()==arrDate[1] && kontrolldatum.getFullYear()==arrDate[2])
{
// in der Zukunft
if (kontrolldatum.getTime()-today.getTime()+(24*60*60*1000) > 0)
return true;
}
return false;
}
Maus[Bearbeiten]
Timer[Bearbeiten]
Quelle: http://blog.agrafix.net/2011/10/javascript-timers-mit-jquery/
Benötigte Funktionen sind window.setTimeout und window.setInterval
// funktion verzögert aufrufen
function machWas() {
alert('alert() mit 1000ms verzögerung!');
}
window.setTimeout(machWas, 1000);
// funktion alle X Millisekunden aufruden
function machWasOft() {
alert('alle 1000ms ein alert()');
}
window.setInterval(machWasOft, 1000);
Doch was ist, wenn ich jetzt einen solchen Timer ändern oder abbrechen möchte? Das ist eigentlich auch nicht schwer – die Funktionen setTimeout/setInterval geben ein Objekt zurück über das sie sich wieder beenden lassen.
var x = 0;
function machWasAbbrechbarOft() {
x += 1;
if (x > 200) {
window.clearInterval(running); // beende das "Interval" nach 201 Ausführungen
}
}
var running = window.setInterval(machWasAbbrechbarOft, 1000);
Timer mit jQuery[Bearbeiten]
Für größere Projekte gibt es ein komfortableres jQuery Plugin
Mit diesem Plugin geht das “Interval” setzen dann wie folgt:
$(document).everyTime(1000, "machWasOftAbbrechbar", function(i) { // alle 1000ms
alert('Hallo ich bin der ' + i + 'te Aufruf!'); // machWasOftAbbrechbar, hier die funktion die aufgerufen werden soll
}, 200); // 200 mal ausführen
Der zweite Parameter, machWasOftAbbrechbar, stellt hierbei ein sogenanntes “label” dar, über das man den gestarten Timer dann wieder abbrechen kann:
$(document).stopTime("machWasOftAbbrechbar"); // stoppe machWasOftAbbrechbar
Viel mehr gibt’s eigentlich nicht dazu zu sagen – die Dokumentation dazu findet man, genau wie das Plugin selbst, unter http://plugins.jquery.com/project/timers.
Arrays[Bearbeiten]
Elemente hinzufügen / entfernen[Bearbeiten]
Gegeben ist ein Array items in der Art
[{id: 1, name: Anton, isFavourite: true}, {id: 2, name: Berta},...]
// add to end of array
this.friends.push(newFriend)
// add to start of array
this.friends.unshift(newFriend)
// delete item from array via id - v1 -> override complete array
deleteItem(id){
this.items = this.items.filter( item => item.id !== sarchId)
// filter( filterFunction ) uses filterFunction for every item in items.
// If filterFunction returns true the item is kept. item.id !== id returns true for every
// item which has NOT the id
}
// v2 - change array
deleteItem(id){
const itemIndex = this.items.findIndex(item => item.id === id)
this.items.splice(resIndex, 1);
}
Finden und Suchen[Bearbeiten]
// find in array and change prop
const identifiedItem = this.items.find(
(item) => item.id === searchId // the same as function(friend){return friend.id...}
)
// filter(callback) - callback is executed on every array (array item) first item match is returned
identifiedItem.isFavourite = !identifiedItem.isFavourite
// identifiedItem is a proxy connected to the original items array.
// thus why we can modify identifiedItems and items will be altered too
JavaScript - Objekte[Bearbeiten]
JavaScript - Objektorientierte Programmierung
Objekte löschen[Bearbeiten]
for (prop in allOverlays) { if (allOverlays.hasOwnProperty(prop)) { delete allOverlays[prop]; } } //ie 6 gc problems
//allOverlays = {};
JavaScript - Strings[Bearbeiten]
JavaScript - Numbers[Bearbeiten]
const x = '1' const y = +x // y is a number now const y = x.parseInt()
Viewport / Offset / Scrolling[Bearbeiten]
Element sichtbar im Viewport[Bearbeiten]
Kommt in den Viewport mit Self-Destroy[Bearbeiten]
Wird nur einmal ausgeführt
document.body.onscroll = function() {
if (document.getElementById("viewElement").getBoundingClientRect().bottom <= window.innerHeight) {
document.body.onscroll = "";
alert("The tag just came into view");
}
}
Komplett im Viewport[Bearbeiten]
function isInViewport(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
const box = document.querySelector('.box');
const message = document.querySelector('#message');
document.addEventListener('scroll', function () {
const messageText = isInViewport(box) ?
'The box is visible in the viewport' :
'The box is not visible in the viewport';
message.textContent = messageText;
}, {
passive: true
});
Teil im Viewport[Bearbeiten]
/**
* checks if any part of the element is in viewport
*/
function isInViewport(el){
h = el.height();
hVp = $(window).height();
posY = el.offset().top - $(window).scrollTop();
dh = posY+h;
// dh < 0 -> oben raus
// posY > hVp -> unten raus
if ( dh < 0 || posY > hVp ) return false;
else return true;
}
Funktion mit GSAP ScrollTrigger starten[Bearbeiten]
Counter Beispiel
function count(){
$('.counter').each(function() {
var $this = $(this), countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 5000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
}
ScrollTrigger.create({
trigger: '#counterTrigger',
onEnter: ()=>{
console.log('count')
count()
},
});
Scrollbar mit Hide/Show Funktion beim Scrollen[Bearbeiten]
Verstecke Navbar beim runterscrollen zeige beim hochscrollen.
document.addEventListener('DOMContentLoaded', function(event) {
var lastScrollTop = 0;
var navbar = document.querySelector('.hd');
var navbarHeight = navbar.offsetHeight;
function handleScroll() {
var scrollTop = window.scrollY;
if (scrollTop > lastScrollTop) {
// Beim Herunterscrollen
navbar.style.transform = 'translateY(-' + navbarHeight + 'px)';
} else {
// Beim Hochscrollen
navbar.style.transform = 'translateY(0)';
}
if (scrollTop === 0) {
// Wenn die Seite ganz oben ist
navbar.classList.add('transparent');
} else {
// Wenn die Seite nicht ganz oben ist
navbar.classList.remove('transparent');
}
lastScrollTop = scrollTop;
}
// Initialer Aufruf bei Laden der Seite
handleScroll();
window.addEventListener('scroll', handleScroll);
JavaScript - HTML5 Audio[Bearbeiten]
Links[Bearbeiten]
JavaScript - Verschiedenes[Bearbeiten]
Enter 2 Tabs[Bearbeiten]
JQuery
Wenn der User in einem Formular die Eingabetaste drückt wird in vielen Browsxern das Formular abgesendet. Stattdessen, kann man den Tastendruck in einen Tab verwandeln, dann kommt der User stattdessen ins nächste Eingabefeld. In diesem Beispiel wird der Cursor zu Beginn gleich ins erste Feld gesetzt (eingesetzt bei Mietlager XL Rechner).
// enter2tab for textboxes
$(document).ready(function() {
$('input:text:first').focus();
$('input:text').bind('keydown', function(e) {
if (e.keyCode == 13) {
e.preventDefault();
var nextIndex = $('input:text').index(this) + 1;
var maxIndex = $('input:text').length;
if (nextIndex < maxIndex) {
$('input:text:eq(' + nextIndex+')').focus();
}
}
});
});
JavaScript Animation[Bearbeiten]
Siehe Animation im Web
Sortieren[Bearbeiten]
http://www.javascriptkit.com/javatutors/arraysort.shtml
Scrolling[Bearbeiten]
[Bearbeiten]
jQuery
$(document).ready(function() {
var stickyNavTop = $('.nav').offset().top;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
});
CSS - wichtig vor allem fixed.
.sticky {
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
}
Smooth Scroll für Anchor Tags oder toTop Links[Bearbeiten]
https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link
noch ein Beispiel (Vanilla)
https://perishablepress.com/vanilla-javascript-scroll-anchor/
Beispiel ab 2018[Bearbeiten]
Nutzt das CSS Verhalten (kann man auch direkt als CSS nutzen. Manchmal funktioniert es (Stand 2020) nicht ganz sauber. Safari und Edge funktionieren nicht mit dem CSS Behaviour
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
For older browser support, you can use this jQuery technique:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
And here's the fiddle: http://jsfiddle.net/9SDLw/
If your target element does not have an ID, and you're linking to it by its name, use this:
$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
Beispiel 1 (jQuery)[Bearbeiten]
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
Beispiel 2 (jQuery) mit Offset[Bearbeiten]
statt
.top
einfach
.top-100
http://1stwebmagazine.com/jquery-scroll-to-anchor-point
Smooth Scrolling mit Vanilla JS[Bearbeiten]
JavaScript - Smooth Scrolling
Beispiel 3 Materialize Pushpin ToTop[Bearbeiten]
jQuery Plugin enthalten in MaterializeCSS http://materializecss.com/pushpin.html
Kann für ToTop Navigation oder Fixed Navigations etc. eingesetzt werden. Liegt im Verzeichnis js/pushpin geht aber nicht ohne weiteres Standalone
//PUSHPIN TOTOP
$( document ).ready(function(){
$('.totop').pushpin({
top: 500,// distance where pin becomes fixed (class)- default 0
bottom: 'infinity', // distance when pin stops being fixed - default infinity
offset: 24 // style="top:[offset]""" - default 0
})
});
//You can remove pushpin and pushpin classes
$('.tabs-wrapper .row').pushpin('remove');
CSS
/* Class for when element is above threshold */
.pin-top {
position: relative;
}
/* Class for when element is below threshold*/
.pin-bottom {
position: relative;
}
/* Class for when element is pinned */
.pinned {
position: fixed !important;
right: 24px;
bottom: 24px;
z-index: 9;
}
/* Only necessary for window height sized blocks. */
html, body, .block {
height: 100%;
}
[Bearbeiten]
<body>
<a class="anchor" name="top"></a>
...
<!-- totop -->
<div class="totop" style="display:none;"><a href="top"><i class="fa fa-angle-double-up fa-2x"></i></a></div>
<script type="text/javascript">
$(document).ready(function() {
$('.totop').hide();
$(window).scroll(function(){
var value = 200; // Toplink beim vertikalen scrollen ab einem Wert von XXX 'px' anzeigen
var scrolling = $(window).scrollTop();
if (scrolling > value) {
$('.totop').fadeIn();
} else {
$('.totop').fadeOut();
}
});
$('.totop').click(function(){
$('html, body').animate({scrollTop:'0px'}, 400);
return false;
});
});
</script>
Toggle[Bearbeiten]
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
oder registrieren
element.addEventListener('click', myFunctionReference , false);
function toggleNavigation() {
var x = document.getElementById("#mobileNavigationPanel");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
Zwischenablage (Clipboard) modifizieren[Bearbeiten]
https://developer.mozilla.org/en-US/docs/Web/API/Element/copy_event
Mit dem Copy Event kann man die Zwischenablage modifizieren wenn der User etwas hineinkopiert. Z.B. könnte das ein Copyright Hinweis sein, den man anhängt.
Beispiel - Uppercase[Bearbeiten]
<div class="source" contenteditable="true">Try copying text from this box...</div>
<div class="target" contenteditable="true">...and pasting it into this one</div>
const source = document.querySelector('div.source');
source.addEventListener('copy', (event) => {
const selection = document.getSelection();
event.clipboardData.setData('text/plain', selection.toString().toUpperCase());
event.preventDefault();
});
Beispiel - Copyright Hinweis hinzufügen[Bearbeiten]
<div class="box source" contenteditable="true">Kopiere Text aus dieser Box...</div>
<div class="box target" contenteditable="true">...in diese Box!</div>
<script>
const source = document.querySelector('div.source');
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
copyDate = dd + '.' + mm + '.' + yyyy;
copyHint = '\nQuelle: ' + window.location.href + ' (Zugriff am: ' + copyDate + ')'; //href, hostname or pathname is possible
source.addEventListener('copy', (event) => {
const selection = document.getSelection();
event.clipboardData.setData('text/plain', selection.toString() + copyHint);
event.preventDefault();
});
</script>
Must Know - Wichtige JavaScript Snippets und Konzepte[Bearbeiten]
Seite geladen?[Bearbeiten]
https://www.mediaevent.de/javascript/onload.html
window.onload = function () {
console.log('Dokument geladen');
function init();
function machwas();
}
Seite und Bilder geladen[Bearbeiten]
window.addEventListener('load', function () {
alert("It's loaded!")
})
https://www.mediaevent.de/javascript/onload.html
let img = new Image;
img.onload = function() {
console.log ("Bild geladen");
elem.appendChild (img);
}
img.src = "little-snail.png"; // erst nach dem Event Listener!
Schriften geladen UND angewendet?[Bearbeiten]
Siehe
JavaScript - Webfont loaded?
fontsReady();
Seite verlassen[Bearbeiten]
https://www.mediaevent.de/javascript/onload.html
Feature Detection[Bearbeiten]
Herausfinden was ein Browser unterstützt und darauf reagieren.
JavaScript - Feature Detection