JQuery - Snippets

Aus Wikizone
Wechseln zu: Navigation, Suche

Nützliche jQuery Schnipsel

Grundgerüst zum testen

<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

JavaScript - Snippets

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/

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

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

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)

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

// focus on the first text input field on the page
$("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.

<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

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

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

Resize des Browserfensters feststellen

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

Templates - Vorlagen

XHTML 1.0 Template mit jQuery

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

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

Einfaches Rollover Hide Show Skript

<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

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

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

Beispiele:

Position eines Elements auslesen

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

Usability

Loading Icon bis Seite komplett geladen ist

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

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

show / hide

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

Elemente find / traversing / selecting

Elemente zählen

.length

n-tes Element ansprechen

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

Element vorhanden ?

Beispiel:

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

Diverses

Attribute vorhanden?

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

Attribut auslesen / setzen

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

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

Attribute auslesen

Nicht über Property sondern über Methode

val.getAttribute("title")