JavaScript - Snippets

Aus Wikizone
Wechseln zu: Navigation, Suche

Links

Siehe auch

JavaScript - Plugins
JavaScripts - Basics
JavaScript - DOM Manipulation
jQuery - Snippets
Browser Fallbacks

Sonderzeichen in Alert-Meldungen

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

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

Prüfen ob ein Element existiert (normales JavaScript)

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

var data = {
    "key1" : val,
    "key2" : val,
    "key3" : val
}
if( "key2" in data && data.key2 != null){
...
}

Eingaben Validieren

Handynummer validieren (normales JavaScript)

function phone_is_valid(nr){
	var reg2 = /^([0-9]{4,6})+\/([0-9]{6,11})$/;
	return reg2.test(nr);
}

Datum validieren (normales JavaScript)

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

JavaScript - Maus

Timer

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

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

Elemente hinzufügen / entfernen

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

// 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

JavaScript - Objektorientierte Programmierung

Objekte löschen

for (prop in allOverlays) { if (allOverlays.hasOwnProperty(prop)) { delete allOverlays[prop]; } } //ie 6 gc problems
//allOverlays = {};

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

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
});

JavaScript - HTML5 Audio

JavaScript - HTML5 Audio

Links

JavaScript - Tricks mit Links

JavaScript - Verschiedenes

Enter 2 Tabs

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

Siehe Animation im Web

Sortieren

http://www.javascriptkit.com/javatutors/arraysort.shtml

Scrolling

Smooth Scroll & Sticky - Fixed Navbar

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

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

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)
$('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

statt

.top

einfach

.top-100

http://1stwebmagazine.com/jquery-scroll-to-anchor-point

Smooth Scrolling mit Vanilla JS

JavaScript - Smooth Scrolling
Beispiel 3 Materialize Pushpin ToTop

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%;
}
Beispiel Markup für ToTop Navigation
<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

<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

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

<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

    <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

Seite geladen?

https://www.mediaevent.de/javascript/onload.html
 window.onload = function () {
        console.log('Dokument geladen');
        function init();
        function machwas();
    }

Seite und Bilder geladen

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!

Seite verlassen

https://www.mediaevent.de/javascript/onload.html