JQuery - Snippets: Unterschied zwischen den Versionen

Aus Wikizone
Wechseln zu: Navigation, Suche
 
(44 dazwischenliegende Versionen von 16 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
 
Nützliche jQuery Schnipsel
 
Nützliche jQuery Schnipsel
 +
== Grundgerüst zum testen ==
 +
<pre>
 +
<html>
 +
<head>
 +
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
 +
<title>Test</title>
 +
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
 +
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
 +
</head>
 +
 +
<body>
 +
 +
<style type="text/css">
 +
</style>
 +
 +
<script type="text/javascript">
 +
$(document).ready(function() {
 +
 +
});
 +
 +
function newFunc(myParam){
 +
alert('hello world')
 +
}
 +
</script>
 +
 +
<h1>Testpage</h1>
 +
 +
</body>
 +
</html>
 +
</pre>
 
== Links ==
 
== Links ==
 
[[JavaScript - Snippets]]
 
[[JavaScript - Snippets]]
Zeile 5: Zeile 35:
 
http://css-tricks.com/snippets/jquery/
 
http://css-tricks.com/snippets/jquery/
  
 +
http://www.jquery4u.com/
 +
 +
== Each ==
 +
[[jQuery - Nested each / verschachtelte Liste]]
 +
 +
http://www.jquery4u.com/jquery-functions/jquery-each-examples/
 +
<pre>
 +
//DOM ELEMENTS
 +
$("div").each(function(index, value) {
 +
    console.log('div' + index + ':' + $(this).attr('id'));
 +
});
 +
//outputs the ids of every div on the web page
 +
//ie - div1:header, div2:body, div3:footer
 +
 +
//ARRAYS
 +
var arr = [ "one", "two", "three", "four", "five" ];
 +
jQuery.each(arr, function(index, value) {
 +
      console.log(this);
 +
      return (this != "three"); // will stop running after "three"
 +
  });
 +
//outputs: one two three
 +
 +
//OBJECTS
 +
var obj = { one:1, two:2, three:3, four:4, five:5 };
 +
    jQuery.each(obj, function(i, val) {
 +
      console.log(val);
 +
    });
 +
//outputs: 1 2 3 4 5
 +
</pre>
 
=== jQuery Countdown Scripts ===
 
=== jQuery Countdown Scripts ===
 
http://www.tripwiremagazine.com/2012/01/jquery-countdown-scripts.html
 
http://www.tripwiremagazine.com/2012/01/jquery-countdown-scripts.html
  
 
== Formulare ==
 
== Formulare ==
 +
Siehe auch [[JQuery - AJAX]]
 +
=== GET-Variable in URL auslesen ===
 +
Diese muß extrahiert werden.
 +
 +
Beispiel 1:
 +
 +
Quelle: http://jquery-howto.blogspot.de/2009/09/get-url-parameters-values-with-jquery.html (Zugriff: 2013/01)
 +
 +
<pre>
 +
// Read a page's GET URL variables and return them as an associative array.
 +
function getUrlVars()
 +
{
 +
    var vars = [], hash;
 +
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 +
    for(var i = 0; i < hashes.length; i++)
 +
    {
 +
        hash = hashes[i].split('=');
 +
        vars.push(hash[0]);
 +
        vars[hash[0]] = hash[1];
 +
    }
 +
    return vars;
 +
}
 +
</pre>
 +
 +
Kurzform:
 +
<pre>
 +
function getUrlVars()
 +
{
 +
return window.location.href.slice(window.location.href.indexOf('?')).split(/[&?]{1}[\w\d]+=/);
 +
}
 +
</pre>
 +
 +
Aufruf von:
 +
http://www.example.com/?me=myValue&name2=SomeOtherValue
 +
 +
ergibt folgendes Array:
 +
<pre>
 +
{
 +
    "me"    : "myValue",
 +
    "name2" : "SomeOtherValue"
 +
}
 +
</pre>
 +
Hinweis: Bei mir funktionierte es nicht mit Aufruf ohne Parameter. Dann entsteht nur ein nicht assoziatives Array. Das liegt wahrscheinlich daran, daß JavaScript eigentlich keine assoziativen Arrays kennt. Folgender Aufruf funktioniert aber:
 +
 +
<pre>
 +
var first = getUrlVars()["me"];
 +
 +
// To get the second parameter
 +
var second = getUrlVars()["name2"];
 +
</pre>
 +
 +
Beispiel 2:
 +
 +
Etwas älteres Beispiel von: http://www.tutorials.de/javascript-ajax/149174-probleme-mit-dem-auslesen-von-variablen.html (Zugriff 2013/01)
 +
 +
<pre>
 +
<SCRIPT type="text/javascript">
 +
<!--
 +
HTTP_GET_VARS=new Array();
 +
strGET=document.location.search.substr(1,document.location.search.length);
 +
if(strGET!='')
 +
    {
 +
    gArr=strGET.split('&');
 +
    for(i=0;i<gArr.length;++i)
 +
        {
 +
        v='';vArr=gArr[i].split('=');
 +
        if(vArr.length>1){v=vArr[1];}
 +
        HTTP_GET_VARS[unescape(vArr[0])]=unescape(v);
 +
        }
 +
    }
 +
 +
function GET(v)
 +
{
 +
if(!HTTP_GET_VARS[v]){return 'undefined';}
 +
return HTTP_GET_VARS[v];
 +
}
 +
 +
document.writeln ('Erste Var:' + GET('text') + ' du');
 +
document.writeln ('Zweite Var:' + GET('text2') + ' da draussen');
 +
// -->
 +
</SCRIPT>
 +
</pre>
 +
 
=== Fokus auf erstes Input-Feld im Formular setzen ===
 
=== Fokus auf erstes Input-Feld im Formular setzen ===
 
  // focus on the first text input field on the page
 
  // focus on the first text input field on the page
 
  $("input[type='text']:first", document.forms[0]).focus();
 
  $("input[type='text']:first", document.forms[0]).focus();
 +
 +
=== Werte von Formularen auslesen ===
 +
http://www.beier-christian.eu/blog/weblog/jquery-ausgewahlte-option-aus-select-box-auslesen/
 +
 +
==== Select Boxen ====
 +
Hinweis, vieles ist natürlich auch mit anderen Elementen möglich.
 +
<pre>
 +
<label for="obst">Obst</label>
 +
<select name="obst" id="obst">
 +
  <option value="1">Orange</option>
 +
  <option value="2">Apfel</option>
 +
  <option value="3">Banane</option>
 +
</select>
 +
</pre>
 +
 +
Wert auslesen
 +
$('select#obst').val();
 +
 +
Text des Wertes auslesen
 +
$('select#obst :selected').text();
 +
 +
Text mehrerer gewählter Optionen ausgeben:
 +
 +
<pre>
 +
$('select#obst :selected').each(function(i, option) {
 +
  // Verarbeitung der Optionen
 +
  alert(option.value + ' ' + option.text);
 +
});
 +
</pre>
 +
Beispiel: Alle gewählten Werte bei Veränderung in ein div (id=message) schreiben:
 +
<pre>
 +
$("select").change(function () {
 +
  var str = "";
 +
  $("select option:selected").each(function () {
 +
    str += $(this).text();
 +
  });
 +
  $("div#message").text(str);
 +
}).change();
 +
</pre>
 +
 +
==== Checkboxen ====
 +
Links:
 +
http://technosophos.com/node/223 (Zugriff 07-2012)
 +
 +
Beispiele
 +
<pre>
 +
// Checked ? Returns a boolean, true if checked, false otherwise
 +
jQuery('#my-checkbox').is(':checked');
 +
 +
// Check checkbox - this sets the attribute checked="checked"
 +
jQuery('#my-checkbox').attr('checked','checked');
 +
 +
// Uncheck checkbox (right way)
 +
jQuery('#my-checkbox').removeAttr('checked');
 +
</pre>
 +
<pre>
 +
// Check / Uncheck everything
 +
 +
// Check anything that is not already checked:
 +
jQuery(':checkbox:not(:checked)').attr('checked', 'checked');
 +
 +
// Remove the checkbox
 +
jQuery(':checkbox:checked').removeAttr('checked');
 +
</pre>
 +
 +
Kleines Hide Show Script wenn eine Checkbox ausgewählt ist:
 +
<pre>
 +
$("input[name='calib_as_offered']").change(function() {
 +
if ($("input[name='calib_as_offered']").is(":checked")){
 +
$("#contact_address").show();
 +
$("#offer_nr_wrap").show();
 +
}
 +
else {
 +
$("#contact_address").hide();
 +
$("#offer_nr_wrap").hide();
 +
}
 +
});
 +
 +
</pre>
 +
 +
==== Radio Buttons ====
 +
''' Uncheck Radio Button'''
 +
this.checked = false;
 +
or (jQuery)
 +
<pre>
 +
$(this).prop('checked', false);
 +
// Note that the pre-jQuery 1.6 idiom was
 +
// $(this).attr('checked', false);
 +
</pre>
 +
 +
'''Change Listener für Radio Buttons''' (Quelle: http://stackoverflow.com/questions/10167395/how-can-i-attach-a-listener-to-multiple-radio-buttons Zugriff: 2013-08)
 +
<pre>
 +
$('input:radio').on('change', function(){
 +
    //access value of changed radio group with $(this).val()
 +
});
 +
</pre>
 +
 +
Quelle der folgenden Beispiele: http://mabraham.de/jquery-radio-buttons-auslesen-und-manipulieren/ (Zugriff 2013-08)
 +
 +
'''Wert (value) einer Radio Group auslesen.'''
 +
<pre>
 +
$('#radio-button-value').click(function(){
 +
    alert($("input[name='radio-button-gruppe']:checked").val());
 +
});
 +
</pre>
 +
 +
'''Radio Button gewählt checked ?'''
 +
<pre>
 +
$('#element').click(function() {
 +
  if($('#radio_button').is(':checked')) { alert("it's checked"); }
 +
});
 +
</pre>
 +
<pre>
 +
$('#radio-button-is-set').click(function(){
 +
    alert(typeof $("input[name='radio-button-gruppe']:checked").val() != 'undefined');
 +
});
 +
</pre>
 +
 +
'''Radio Button anhand seiner Id auswählen (check)'''
 +
<pre>
 +
$('#radio-checked-by-id').click(function(){
 +
    $("#gruppe1").attr("checked","checked");
 +
});
 +
</pre>
 +
 +
'''Radio Button über Wert auswählen (check) '''
 +
<pre>
 +
$('#radio-checked-by-value').click(function(){
 +
    $("input[name='radio-button-gruppe'][value='2']").attr("checked","checked");
 +
});
 +
</pre>
 +
 +
'''Radio Button abwählen'''
 +
<pre>
 +
$('#radio-uncheck').click(function(){
 +
    $("input[name='radio-button-gruppe']:checked").removeAttr("checked");
 +
});
 +
</pre>
  
 
== Browser ==
 
== Browser ==
Zeile 31: Zeile 311:
  
 
</pre>
 
</pre>
 +
== Element erreicht Fensterrand ==
 +
http://jsfiddle.net/gizmovation/x8FDU/
  
 
== Templates - Vorlagen ==
 
== Templates - Vorlagen ==
Zeile 170: Zeile 452:
 
</pre>
 
</pre>
  
== DOM Manipulation ==
+
== DOM Manipulation und Rendering ==
 +
=== Höhe eines Divs an Browserfenster anpassen ===
 +
Siehe [[JavaScript - Full Height Container]]
 +
 
 
=== Einfaches Rollover Hide Show Skript ===
 
=== Einfaches Rollover Hide Show Skript ===
 +
 
<pre>
 
<pre>
 
<script type="text/javascript">
 
<script type="text/javascript">
Zeile 217: Zeile 503:
  
 
Siehe auch: [[Media:Maphilight-sample01.zip]]‎
 
Siehe auch: [[Media:Maphilight-sample01.zip]]‎
 +
 +
Hinweis: damit fadeIn oder show funktionieren indem jQuery den Stil display: none und display: block hinzufügt. Eventuell muß das Element zuerst mit hide() o.ä. versteckt werden. Z.B.:
 +
$(".myElement").hide().fadeIn(500);
 +
vorsicht mit visibility: hidden im CSS. Dies führt dazu, daß man das Element trotz show() nicht sieht.
  
 
===Append Site Overlay DIV===
 
===Append Site Overlay DIV===
Zeile 247: Zeile 537:
  
 
Beispiele:
 
Beispiele:
 +
 +
=== Position eines Elements auslesen ===
 +
 +
<pre>
 +
// get Pos of act Item
 +
var position = $("#myElement").offset();
 +
//console.log(position);
 +
 +
//set positon to other elements...
 +
$("#otherElement").css(position);
 +
$("#anotherElement").css("top",(position.top+5));
 +
 +
</pre>
 +
 +
=== Größe eines Elements auslesen ===
 +
<pre>
 +
// Größe eines Divs auslesen
 +
var dx = $('#bubbles').width();
 +
var dy = $('#bubbles').height();
 +
// Zufälliger Punkt innerhalb dieses Bereiches
 +
var posX = Math.floor(Math.random() * dx);
 +
var posY = Math.floor(Math.random() * dy);
 +
</pre>
 +
 +
== Usability ==
 +
=== Loading Icon bis Seite komplett geladen ist ===
 +
Quelle: siehe Links
 +
 +
<pre>
 +
<head>
 +
<meta charset='UTF-8'>
 +
<title>Simple Loader</title>
 +
<style>
 +
/* This only works with JavaScript,
 +
  if it's not present, don't show loader */
 +
.no-js #loader { display: none;  }
 +
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
 +
</style>
 +
 +
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
 +
 +
<script src="https://github.com/Modernizr/Modernizr/raw/master/modernizr.js"></script>
 +
<script>
 +
// Wait for window load
 +
$(window).load(function() {
 +
// Animate loader off screen
 +
$("#loader").animate({
 +
top: -200
 +
}, 1500);
 +
});
 +
</script>
 +
</head>
 +
 +
<body>
 +
<img src="download.png" id="loader">
 +
<img src="http://farm6.static.flickr.com/5299/5400751421_55d49b2786_o.jpg">
 +
</body>
 +
 +
</pre>
 +
 +
== Animation ==
 +
$('#gbreslib-details-wrap').fadeTo('slow', 1,function() {scrollToAnchor("gbres_details_anchor");});
 +
 +
=== Smooth Anchor Scrolling (ScrollTop Animation)===
 +
http://stackoverflow.com/questions/7717527/jquery-smooth-scrolling-when-clicking-an-anchor-link (2015-07)
 +
 +
'''Link auf ID'''
 +
<syntaxhighlight lang="javascript">
 +
$('a').click(function(){
 +
    $('html, body').animate({
 +
        scrollTop: $( $.attr(this, 'href') ).offset().top
 +
    }, 500);
 +
    return false;
 +
});
 +
</syntaxhighlight>
 +
And here's the fiddle: http://jsfiddle.net/9SDLw/
 +
 +
'''Link auf name Attribut'''
 +
If your target element does not have an ID, and you're linking to it by its name, use this:
 +
<syntaxhighlight lang="javascript">
 +
$('a').click(function(){
 +
    $('html, body').animate({
 +
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
 +
    }, 500);
 +
    return false;
 +
});
 +
</syntaxhighlight>
 +
For '''increased performance''', you should cache that $('html, body') selector, so that it doesn't run every single time an anchor is clicked:
 +
<syntaxhighlight lang="javascript">
 +
var $root = $('html, body');
 +
$('a').click(function() {
 +
    $root.animate({
 +
        scrollTop: $( $.attr(this, 'href') ).offset().top
 +
    }, 500);
 +
    return false;
 +
});
 +
</syntaxhighlight>
 +
If you want the '''URL to be updated''', do it within the animate callback:
 +
<syntaxhighlight lang="javascript">
 +
var $root = $('html, body');
 +
$('a').click(function() {
 +
    var href = $.attr(this, 'href');
 +
    $root.animate({
 +
        scrollTop: $(href).offset().top
 +
    }, 500, function () {
 +
        window.location.hash = href;
 +
    });
 +
    return false;
 +
});
 +
</syntaxhighlight>
 +
 +
=== show / hide ===
 +
.show(fast)
 +
.hide(500)
 +
...
 +
 +
== Elemente find / traversing / selecting ==
 +
$( "li.item-ii" ).find( "li" )
 +
is equivalent to
 +
$( "li", "li.item-ii" )
 +
=== Elemente zählen ===
 +
.length
 +
=== n-tes Element ansprechen ===
 +
<pre>
 +
.eq(n) //js function -> better performance
 +
$(".myClass:eq(1)") //jQuery selector -> bad performance but flexible
 +
.eq(-1) //last element
 +
// test if available
 +
 +
</pre>
 +
=== Element vorhanden ? ===
 +
Beispiel:
 +
<pre>
 +
function getPidFromPn(pn){
 +
var myId = '';
 +
if( $(".page:eq("+(pn)+")").length > 0){
 +
myId = $(".page:eq("+pn+")").attr("id");
 +
}
 +
return myId;
 +
}
 +
</pre>
 +
 +
== Attribute==
 +
https://api.jquery.com/category/selectors/attribute-selectors/
 +
=== Attribute vorhanden ? ===
 +
<pre>
 +
myAttr = $(this).attr('myAttr');
 +
if (typeof myAttr !== typeof undefined && myAttr !== false && myAttr !== "false") {
 +
  // Attribut ist vorhanden und nicht "false" -> tu was
 +
}
 +
</pre>
 +
=== Attribut auslesen / setzen ===
 +
var meinWert = $(this).attr("myAttr");
 +
$(this).attr("myAttr","meinWert");
 +
 +
=== Attribute auslesen ===
 +
Nicht über Property sondern über Methode
 +
val.getAttribute("title")
 +
 +
=== Elemente mit bestimmten Attributen finden ===
 +
$('.slide-link[data-slide="0"]').addClass('active');
 +
Beispiel mehrere Attribute mit UND Verknüpfung
 +
[name="value"][name2="value2"]
 +
 +
==== Attribut mit filter() finden ====
 +
$('.slide-link').filter('[data-slide="0"]').addClass('active');
 +
 +
=== Attribut beginnt mit ===
 +
Beispiel: Beginnt mit Wert gefolgt von -
 +
<pre>
 +
<a href="example.html" hreflang="en">Some text</a>
 +
<a href="example.html" hreflang="en-UK">Some other text</a>
 +
<a href="example.html" hreflang="english">will not be outlined</a>
 +
 +
<script>
 +
$( "a[hreflang|='en']" ).css( "border", "3px dotted green" );
 +
</script>
 +
</pre>
 +
Beispiel: Beginnt mit...
 +
 +
[name^="value"]
 +
 +
 +
=== Attributswert enthält ===
 +
[name*="value"]
 +
=== Attributswert endet mit ===
 +
[name$="value"]
 +
 +
== Events ==
 +
[[JavaScript - Event Handling]]
 +
=== Anchor Click - Defaultverhalten des Browsers verhindern ===
 +
Manchmal möchte man verhindern, daß der Browser bei Klick auf einen Anchor zum Anchor Scrollt. Wenn man den Event als Argument mitgibt, kann man das Browser Verhalten unterbinden über preventDefault();
 +
 +
Beispiel aus drpetry.de Map
 +
<syntaxhighlight lang="javascript">
 +
  // click-listeners to countries
 +
  $(".level1 area[name]").click(function(e){
 +
    e.preventDefault();
 +
    hideAllItems();
 +
    myItem = $(this).attr("name");
 +
    showItem(myItem);
 +
  })
 +
</syntaxhighlight>
 +
 +
== Diverses ==
 +
=== Callback ===
 +
Beispiel für Callbacks:
 +
==== Funktionen nacheinander ausführen ====
 +
Wenn man möchte, daß jQuery etwas ausführt, nachdem eine andere Funktion beendet ist benötigt man Callbacks. D.h. eine Funktion ruft nach dem Beenden eine andere oder sich selbst erneut auf. Wenn eine Funktion keinen Callback bereitstellt, kann man auf vorhandene Funktionen zurückgreifen (siehe Beispiel)
 +
==== Animate Funktion als Callback nutzen ====
 +
Kein Callback in deinem Plugin oder deiner Funktion - Animate als Callback nutzen:
 +
<syntaxhighlight lang="javascript">
 +
$('.equal-height2').animate({"height": max_height2}, function() { 
 +
  alert('###');
 +
  pc_img_height = $('.podcasts-meta-img').height();
 +
  $('.podcasts-meta-img').width(pc_img_height);
 +
})
 +
</syntaxhighlight>
 +
=== Plugins ===
 +
[[jQuery - Plugins]]
 +
 +
=== LocalStorage ===
 +
==== Popup nur einmal per User anzeigen lassen.====
 +
 +
<syntaxhighlight lang="javascript">
 +
<script type="text/javascript">
 +
$(document).ready(function() {
 +
  if(localStorage.getItem('popState') != 'shown'){
 +
    $.magnificPopup.open({items: {src: '#test-popup'},type: 'inline'}, 0);
 +
    localStorage.setItem('popState','shown');
 +
  }
 +
});
 +
</script>
 +
</syntaxhighlight>
 +
==== Popup (Modal) nur einmal alle 14 Tage ====
 +
Nutzt localstorage um den Timestamp des letzten Aufrufs zu speichern.
 +
<syntaxhighlight lang="javascript">
 +
$(document).ready(function() {
 +
  var now, lastTimeShown;
 +
  now = new Date().getTime();
 +
  //delay = 1 * 60000; // minutes (for testing)
 +
  delay = 24 * 3600000 // hours
 +
  if (localStorage.getItem('lastTimeShown') !== null) {
 +
    lastTimeShown = parseInt(localStorage.getItem('lastTimeShown'));
 +
  }
 +
  if ( (parseInt(now) - parseInt(lastTimeShown) >= (delay)) || !lastTimeShown) {
 +
    $.magnificPopup.open({items: {src: '#test-popup'},type: 'inline'}, 0);
 +
    localStorage.setItem('lastTimeShown', now);
 +
  }
 +
});
 +
</syntaxhighlight>

Aktuelle Version vom 10. August 2020, 18:14 Uhr

Nützliche jQuery Schnipsel

Grundgerüst zum testen[Bearbeiten]

<html>
<head>
	<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
	<title>Test</title>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  	<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
</head>

<body>

<style type="text/css">
</style>

<script type="text/javascript">	
$(document).ready(function() {

});

function newFunc(myParam){
	alert('hello world')
}
</script>

<h1>Testpage</h1>

</body>
</html>

Links[Bearbeiten]

JavaScript - Snippets

http://css-tricks.com/snippets/jquery/

http://www.jquery4u.com/

Each[Bearbeiten]

jQuery - Nested each / verschachtelte Liste

http://www.jquery4u.com/jquery-functions/jquery-each-examples/

//DOM ELEMENTS
$("div").each(function(index, value) { 
    console.log('div' + index + ':' + $(this).attr('id')); 
});
//outputs the ids of every div on the web page
//ie - div1:header, div2:body, div3:footer

//ARRAYS
var arr = [ "one", "two", "three", "four", "five" ];
jQuery.each(arr, function(index, value) {
       console.log(this);
       return (this != "three"); // will stop running after "three"
   });
//outputs: one two three

//OBJECTS
var obj = { one:1, two:2, three:3, four:4, five:5 };
    jQuery.each(obj, function(i, val) {
       console.log(val);
    });
//outputs: 1 2 3 4 5

jQuery Countdown Scripts[Bearbeiten]

http://www.tripwiremagazine.com/2012/01/jquery-countdown-scripts.html

Formulare[Bearbeiten]

Siehe auch JQuery - AJAX

GET-Variable in URL auslesen[Bearbeiten]

Diese muß extrahiert werden.

Beispiel 1:

Quelle: http://jquery-howto.blogspot.de/2009/09/get-url-parameters-values-with-jquery.html (Zugriff: 2013/01)

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Kurzform:

function getUrlVars()
{
return window.location.href.slice(window.location.href.indexOf('?')).split(/[&?]{1}[\w\d]+=/);
}

Aufruf von:

http://www.example.com/?me=myValue&name2=SomeOtherValue

ergibt folgendes Array:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

Hinweis: Bei mir funktionierte es nicht mit Aufruf ohne Parameter. Dann entsteht nur ein nicht assoziatives Array. Das liegt wahrscheinlich daran, daß JavaScript eigentlich keine assoziativen Arrays kennt. Folgender Aufruf funktioniert aber:

var first = getUrlVars()["me"];

// To get the second parameter
var second = getUrlVars()["name2"];

Beispiel 2:

Etwas älteres Beispiel von: http://www.tutorials.de/javascript-ajax/149174-probleme-mit-dem-auslesen-von-variablen.html (Zugriff 2013/01)

<SCRIPT type="text/javascript">
<!--
HTTP_GET_VARS=new Array();
strGET=document.location.search.substr(1,document.location.search.length);
if(strGET!='')
    {
    gArr=strGET.split('&');
    for(i=0;i<gArr.length;++i)
        {
        v='';vArr=gArr[i].split('=');
        if(vArr.length>1){v=vArr[1];}
        HTTP_GET_VARS[unescape(vArr[0])]=unescape(v);
        }
    }
 
function GET(v)
{
if(!HTTP_GET_VARS[v]){return 'undefined';}
return HTTP_GET_VARS[v];
}
 
document.writeln ('Erste Var:' + GET('text') + ' du');
document.writeln ('Zweite Var:' + GET('text2') + ' da draussen');
// -->
</SCRIPT>

Fokus auf erstes Input-Feld im Formular setzen[Bearbeiten]

// focus on the first text input field on the page
$("input[type='text']:first", document.forms[0]).focus();

Werte von Formularen auslesen[Bearbeiten]

http://www.beier-christian.eu/blog/weblog/jquery-ausgewahlte-option-aus-select-box-auslesen/

Select Boxen[Bearbeiten]

Hinweis, vieles ist natürlich auch mit anderen Elementen möglich.

<label for="obst">Obst</label>
<select name="obst" id="obst">
  <option value="1">Orange</option>
  <option value="2">Apfel</option>
  <option value="3">Banane</option>
</select>

Wert auslesen

$('select#obst').val();

Text des Wertes auslesen

$('select#obst :selected').text();

Text mehrerer gewählter Optionen ausgeben:

$('select#obst :selected').each(function(i, option) {
  // Verarbeitung der Optionen
  alert(option.value + ' ' + option.text);
});

Beispiel: Alle gewählten Werte bei Veränderung in ein div (id=message) schreiben:

$("select").change(function () {
  var str = "";
  $("select option:selected").each(function () {
    str += $(this).text();
  });
  $("div#message").text(str);
}).change(); 

Checkboxen[Bearbeiten]

Links: http://technosophos.com/node/223 (Zugriff 07-2012)

Beispiele

// Checked ? Returns a boolean, true if checked, false otherwise
jQuery('#my-checkbox').is(':checked');

// Check checkbox - this sets the attribute checked="checked"
jQuery('#my-checkbox').attr('checked','checked');

// Uncheck checkbox (right way)
jQuery('#my-checkbox').removeAttr('checked');
// Check / Uncheck everything

// Check anything that is not already checked:
jQuery(':checkbox:not(:checked)').attr('checked', 'checked');
 
// Remove the checkbox
jQuery(':checkbox:checked').removeAttr('checked');

Kleines Hide Show Script wenn eine Checkbox ausgewählt ist:

			$("input[name='calib_as_offered']").change(function() {
				if ($("input[name='calib_as_offered']").is(":checked")){
					$("#contact_address").show();
					$("#offer_nr_wrap").show();
				} 
				else {
					$("#contact_address").hide();
					$("#offer_nr_wrap").hide();					
				}
			});

Radio Buttons[Bearbeiten]

Uncheck Radio Button

this.checked = false;

or (jQuery)

$(this).prop('checked', false);
// Note that the pre-jQuery 1.6 idiom was
// $(this).attr('checked', false);

Change Listener für Radio Buttons (Quelle: http://stackoverflow.com/questions/10167395/how-can-i-attach-a-listener-to-multiple-radio-buttons Zugriff: 2013-08)

$('input:radio').on('change', function(){
    //access value of changed radio group with $(this).val()
});

Quelle der folgenden Beispiele: http://mabraham.de/jquery-radio-buttons-auslesen-und-manipulieren/ (Zugriff 2013-08)

Wert (value) einer Radio Group auslesen.

$('#radio-button-value').click(function(){
    alert($("input[name='radio-button-gruppe']:checked").val());
});

Radio Button gewählt checked ?

$('#element').click(function() {
   if($('#radio_button').is(':checked')) { alert("it's checked"); }
});
$('#radio-button-is-set').click(function(){
    alert(typeof $("input[name='radio-button-gruppe']:checked").val() != 'undefined');
});

Radio Button anhand seiner Id auswählen (check)

$('#radio-checked-by-id').click(function(){
    $("#gruppe1").attr("checked","checked");
});

Radio Button über Wert auswählen (check)

$('#radio-checked-by-value').click(function(){
    $("input[name='radio-button-gruppe'][value='2']").attr("checked","checked");
});

Radio Button abwählen

$('#radio-uncheck').click(function(){
    $("input[name='radio-button-gruppe']:checked").removeAttr("checked");
});

Browser[Bearbeiten]

Resize des Browserfensters feststellen[Bearbeiten]

<script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
 
//If the User resizes the window, adjust the #container height
$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
	var newWindowHeight = $(window).height();
	$("#container").css("min-height", newWindowHeight );
}
 
});			
</script>

Element erreicht Fensterrand[Bearbeiten]

http://jsfiddle.net/gizmovation/x8FDU/

Templates - Vorlagen[Bearbeiten]

XHTML 1.0 Template mit jQuery[Bearbeiten]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>Title goes here » Site title here</title>

	<!-- Meta Tags -->
	<base href="" />
	<meta name="author" content="#" />
	<meta name="description" content="#" />
	<meta name="copyright" content="#" />
	<meta name="robots" content="#" />
	<meta name="generator" content="#" />
	<meta name="keywords" content="#" />
	<meta http-equiv="expires" content="#" />
	<meta http-equiv="cache-control" content="#" />
	
	<!-- Fav icon -->
	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

	<!-- JavaScript setup -->
	<script type="text/javascript">
	/*<![CDATA[*/
	// add 'js' class to root element to nicely allow css that degrades gracefully if js is disabled
	document.getElementsByTagName('html')[0].className = 'js';
	/*]]>*/
	</script>
	
	<!-- CSS -->
	<link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" />
	<link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" />
	
	<!--[if IE]>
	<link rel="stylesheet" href="/stylesheets/ie-all.css" type="text/css" media="screen, projection" />
	<![endif]-->
	
</head>
<body>
	<div id="container">
	
		<div id="header">
			<h1>Title of page goes here</h1>
			<h2>Subtitle of page goes here</h2>
		</div><!-- end header div -->
		
		<div id="nav">
			<ul class="menu">
				<li><a href="#">Link #1</a></li>
				<li><a href="#">Link #2</a></li>
				<li><a href="#">Link #3</a></li>
			</ul>
			<ul class="breadcrumbs">
				<li><a href="#">Home</a></li>
				<li><a href="#">Sub directory</a></li>
				<li><a href="#">Current page</a></li>
			</ul>
		</div><!-- end nav div -->

		<div id="main">
			<ul class="sidebar">
				<li><a href="#">Sidebar link #1</a></li>
				<li><a href="#">Sidebar link #2</a></li>
			</ul>

			<div id="sub1">
				<h3>Title of content</h3>
				<p>Begin content here</p>
			</div>
			
			<div id="sub2" class="hide">
				<h3>Title of content</h3>
				<p>Begin content here</p>
			</div>
		</div><!-- end main div -->

		<div id="footer">
			<p>©2XXX company name here. Creative Commons link, your own link, validation, etc.</p>
		</div><!-- end footer div -->
		
	</div><!-- end container div -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/app.js"></script>
	
<!-- place Google Analytics code here -->

</body>
</html>

JavaScript nachladen während die Seite schon angezeigt wird[Bearbeiten]

// Add this onDocumentReady function to the end of the jQuery.js file. 
// It MUST be in the jquery file to work correctly.
$(function(){
	var scripts = /\?(.*)/, files = [], path = /^.*\//, loaded = 0, count = 0;
 
	$('script').each(function(){
		var src = $(this).attr('src');
		if (!scripts.test(src)) return;
		var pathto = src.match(path);
		files = files.concat($.map(src.match(scripts).pop().split(','), function(e,i){
			return pathto+e+'.js'
		}));
	})
 
	count = files.length;
 
	$.each(files, function(){
		$.getScript(this, function(){
			loaded++;
			if(loaded == count && typeof onBackload == 'function')
				onBackload(loaded)
		})
	})
});
 
/**
 * If you have the following script tags:
 * 	<script src="/path/to/jquery.min.js?somefile,otherfile.min,thirdfile"></script>
 * 	<script src="/other/path/foo.js?different.file,final.file"></script>
 * This script will "backload" the following files:
 * 	/path/to/somefile.js
 *	/path/to/otherfile.min.js
 * 	/path/to/thirdfile.js
 * 	/other/path/different.file.js
 *	/other/path/final.file.js
 */
 
// And if you declare a function named "onBackload", it will be fired when all the scripts are loaded
// This is handy for getting things going once you're confident your scripts have all been included.
function onBackload(loaded){
	alert('All ' + loaded + ' files backloaded!')
}

DOM Manipulation und Rendering[Bearbeiten]

Höhe eines Divs an Browserfenster anpassen[Bearbeiten]

Siehe JavaScript - Full Height Container

Einfaches Rollover Hide Show Skript[Bearbeiten]

<script type="text/javascript">
	/*<![CDATA[*/
<!--
//var j = jQuery.noConflict();
$(document).ready(function() {
    hideAllItems();	

    $("h5").hover( 
      function () {
         showItem($(this));
      }, 
      function () {
        hideItem($(this));
      }

    );
 
});

function hideAllItems(){
    $(".bodytext").hide();	
}

function showItem(myItem){
      myItem.next().fadeIn(250);
      myItem.parent().addClass("topLine");
    //myItem.parents().append($("<span> ***</span>"));
    //myItem.parents().("p").fadeIn(250);
    //myItem.parents().append($("<span> ***</span>"));
}

function hideItem(myItem){
    myItem.next().fadeOut(250);
    myItem.parent().removeClass("topLine");
    //hideAllItems();
    //myItem.find("span:last").remove();

}
// -->
	/*]]>*/
</script>

Siehe auch: Media:Maphilight-sample01.zip

Hinweis: damit fadeIn oder show funktionieren indem jQuery den Stil display: none und display: block hinzufügt. Eventuell muß das Element zuerst mit hide() o.ä. versteckt werden. Z.B.:

$(".myElement").hide().fadeIn(500);

vorsicht mit visibility: hidden im CSS. Dies führt dazu, daß man das Element trotz show() nicht sieht.

Append Site Overlay DIV[Bearbeiten]

Quelle: http://css-tricks.com/snippets/jquery/append-site-overlay-div/ (11/2011)

$(function() {

   var docHeight = $(document).height();

   $("body").append("<div id='overlay'></div>");

   $("#overlay")
      .height(docHeight)
      .css({
         'opacity' : 0.4,
         'position': 'absolute',
         'top': 0,
         'left': 0,
         'background-color': 'black',
         'width': '100%',
         'z-index': 5000
      });

});

jQuery - overlay, modal box, lightbox, tooltips[Bearbeiten]

Infos über die verschiedenen Möglichkeiten und die Unterschiede (Todo)

Beispiele:

Position eines Elements auslesen[Bearbeiten]

// get Pos of act Item
var position = $("#myElement").offset();
//console.log(position);

//set positon to other elements...
$("#otherElement").css(position);
$("#anotherElement").css("top",(position.top+5));

Größe eines Elements auslesen[Bearbeiten]

// Größe eines Divs auslesen
var dx = $('#bubbles').width(); 
var dy = $('#bubbles').height();
// Zufälliger Punkt innerhalb dieses Bereiches
var posX = Math.floor(Math.random() * dx);
var posY = Math.floor(Math.random() * dy);

Usability[Bearbeiten]

Loading Icon bis Seite komplett geladen ist[Bearbeiten]

Quelle: siehe Links

<head>
	<meta charset='UTF-8'>
	<title>Simple Loader</title>
	<style>
		/* This only works with JavaScript,
		   if it's not present, don't show loader */
		.no-js #loader { display: none;  }
		.js #loader { display: block; position: absolute; left: 100px; top: 0; }
	</style>

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
	
	<script src="https://github.com/Modernizr/Modernizr/raw/master/modernizr.js"></script>
	<script>
		// Wait for window load
		$(window).load(function() {
			// Animate loader off screen
			$("#loader").animate({
				top: -200
			}, 1500);
		});
	</script>
</head>

<body>
	<img src="download.png" id="loader">
	<img src="http://farm6.static.flickr.com/5299/5400751421_55d49b2786_o.jpg">
</body>

Animation[Bearbeiten]

$('#gbreslib-details-wrap').fadeTo('slow', 1,function() {scrollToAnchor("gbres_details_anchor");});

Smooth Anchor Scrolling (ScrollTop Animation)[Bearbeiten]

http://stackoverflow.com/questions/7717527/jquery-smooth-scrolling-when-clicking-an-anchor-link (2015-07)

Link auf ID

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});

And here's the fiddle: http://jsfiddle.net/9SDLw/

Link auf name Attribut If your target element does not have an ID, and you're linking to it by its name, use this:

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);
    return false;
});

For increased performance, you should cache that $('html, body') selector, so that it doesn't run every single time an anchor is clicked:

var $root = $('html, body');
$('a').click(function() {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});

If you want the URL to be updated, do it within the animate callback:

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

show / hide[Bearbeiten]

.show(fast)
.hide(500)
...

Elemente find / traversing / selecting[Bearbeiten]

$( "li.item-ii" ).find( "li" ) 

is equivalent to

$( "li", "li.item-ii" )

Elemente zählen[Bearbeiten]

.length

n-tes Element ansprechen[Bearbeiten]

.eq(n) //js function -> better performance
$(".myClass:eq(1)") //jQuery selector -> bad performance but flexible
.eq(-1) //last element
// test if available

Element vorhanden ?[Bearbeiten]

Beispiel:

function getPidFromPn(pn){
	var myId = '';
	if( $(".page:eq("+(pn)+")").length > 0){
		myId = $(".page:eq("+pn+")").attr("id");
	}
	return myId;
}

Attribute[Bearbeiten]

https://api.jquery.com/category/selectors/attribute-selectors/

Attribute vorhanden ?[Bearbeiten]

myAttr = $(this).attr('myAttr');
if (typeof myAttr !== typeof undefined && myAttr !== false && myAttr !== "false") {
   // Attribut ist vorhanden und nicht "false" -> tu was
}

Attribut auslesen / setzen[Bearbeiten]

var meinWert = $(this).attr("myAttr");

$(this).attr("myAttr","meinWert");

Attribute auslesen[Bearbeiten]

Nicht über Property sondern über Methode

val.getAttribute("title")

Elemente mit bestimmten Attributen finden[Bearbeiten]

$('.slide-link[data-slide="0"]').addClass('active');

Beispiel mehrere Attribute mit UND Verknüpfung

[name="value"][name2="value2"]

Attribut mit filter() finden[Bearbeiten]

$('.slide-link').filter('[data-slide="0"]').addClass('active');

Attribut beginnt mit[Bearbeiten]

Beispiel: Beginnt mit Wert gefolgt von -

<a href="example.html" hreflang="en">Some text</a>
<a href="example.html" hreflang="en-UK">Some other text</a>
<a href="example.html" hreflang="english">will not be outlined</a>
 
<script>
$( "a[hreflang|='en']" ).css( "border", "3px dotted green" );
</script>

Beispiel: Beginnt mit...

[name^="value"]


Attributswert enthält[Bearbeiten]

[name*="value"]

Attributswert endet mit[Bearbeiten]

[name$="value"]

Events[Bearbeiten]

JavaScript - Event Handling

Anchor Click - Defaultverhalten des Browsers verhindern[Bearbeiten]

Manchmal möchte man verhindern, daß der Browser bei Klick auf einen Anchor zum Anchor Scrollt. Wenn man den Event als Argument mitgibt, kann man das Browser Verhalten unterbinden über preventDefault();

Beispiel aus drpetry.de Map

  // click-listeners to countries
  $(".level1 area[name]").click(function(e){
    e.preventDefault();
    hideAllItems();
    myItem = $(this).attr("name");
    showItem(myItem);
  })

Diverses[Bearbeiten]

Callback[Bearbeiten]

Beispiel für Callbacks:

Funktionen nacheinander ausführen[Bearbeiten]

Wenn man möchte, daß jQuery etwas ausführt, nachdem eine andere Funktion beendet ist benötigt man Callbacks. D.h. eine Funktion ruft nach dem Beenden eine andere oder sich selbst erneut auf. Wenn eine Funktion keinen Callback bereitstellt, kann man auf vorhandene Funktionen zurückgreifen (siehe Beispiel)

Animate Funktion als Callback nutzen[Bearbeiten]

Kein Callback in deinem Plugin oder deiner Funktion - Animate als Callback nutzen:

$('.equal-height2').animate({"height": max_height2}, function() {  
  alert('###');
  pc_img_height = $('.podcasts-meta-img').height();
  $('.podcasts-meta-img').width(pc_img_height); 
})

Plugins[Bearbeiten]

jQuery - Plugins

LocalStorage[Bearbeiten]

Popup nur einmal per User anzeigen lassen.[Bearbeiten]

<script type="text/javascript">
$(document).ready(function() {
  if(localStorage.getItem('popState') != 'shown'){
    $.magnificPopup.open({items: {src: '#test-popup'},type: 'inline'}, 0);
    localStorage.setItem('popState','shown');
  }
});
</script>

Popup (Modal) nur einmal alle 14 Tage[Bearbeiten]

Nutzt localstorage um den Timestamp des letzten Aufrufs zu speichern.

$(document).ready(function() {
  var now, lastTimeShown;
  now = new Date().getTime();
  //delay = 1 * 60000; // minutes (for testing)
  delay = 24 * 3600000 // hours 
  if (localStorage.getItem('lastTimeShown') !== null) {
    lastTimeShown = parseInt(localStorage.getItem('lastTimeShown'));
  }
  if ( (parseInt(now) - parseInt(lastTimeShown) >= (delay)) || !lastTimeShown) {
    $.magnificPopup.open({items: {src: '#test-popup'},type: 'inline'}, 0);
    localStorage.setItem('lastTimeShown', now);
  }
});