JQuery - Snippets: Unterschied zwischen den Versionen

Aus Wikizone
Wechseln zu: Navigation, Suche
Zeile 39: Zeile 39:
  
 
== Formulare ==
 
== Formulare ==
 +
=== GET-Variable in URL auslesen ===
 +
Diese muß extrahiert werden.
 +
 +
Beispiel:
 +
 +
<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

Version vom 4. Januar 2013, 14:07 Uhr

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/

jQuery Countdown Scripts

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

Formulare

GET-Variable in URL auslesen

Diese muß extrahiert werden.

Beispiel:

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

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

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>