Hier sind für verschiedenste Anwendungen Code-Schnipsel aufgelistet. Diese können per copy & paste in Projekte eingefügt und angepasst werden. Für Fragen stehen wir jederzeit zur Verügung, falls die Anwendung Probleme bereitet. Viel Spaß beim durchforsten der Snippets.

HTML

Code ausschließlich für Internet Explorer

<!--[if IE ]>
   ----- CODE -----
<![endif]-->

HTML Kommentare

<div id="header">
   <p>Stuff</p>
</div> <!-- END div-header -->

Flash Objekt einbinden

<object type="application/x-shockwave-flash"
	data="your-flash-file.swf"
	width="0" height="0">
	<param name="movie" value="your-flash-file.swf" />
	<param name="quality" value="high"/>
</object>

Email Link

<a href="mailto:someone@yoursite.com">Email Us</a>

Meta Weiterleitung

<meta http-equiv="refresh" content="0;url=http://example.com/" />

HTML Tooltip

I love <acronym title="Cascading Style Sheets">CSS</acronym>.

CSS

Kommentare in CSS

body {
    font-size: 2em;  /* 1em = 10px - Das ist ein Kommentar */
}

Div Container immer horizontal zentriert im Browser

#container { margin: 0px auto;}

CSS Reset (Meyer)

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-weight: inherit;
	font-style: inherit;
	font-size: 100%;
	font-family: inherit;
	vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
	outline: 0;
}
body {
	line-height: 1;
	color: black;
	background: white;
}
ol, ul {
	list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: separate;
	border-spacing: 0;
}
caption, th, td {
	text-align: left;
	font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: "";
}
blockquote, q {
	quotes: "" "";
}

Deckkraft für alle Browser-Typen

.transparent_class {
  /* IE 8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

  /* IE 5-7 */
  filter: alpha(opacity=50);

  /* Netscape */
  -moz-opacity: 0.5;

  /* Safari 1.x */
  -khtml-opacity: 0.5;

  /* Gute Browser */
  opacity: 0.5;
}

Abgerundete Ecken

-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px; /* future proofing */
-khtml-border-radius: 10px; /* old Konqueror browsers */

CSS Schatten für Boxen (Box-Shadow)

.shadow {
  box-shadow: 5px 5px 5px #ccc;
  -moz-box-shadow: 5px 5px 5px #ccc;
  -webkit-box-shadow: 5px 5px 5px #ccc;
}

Pseudo Klassen für Links

a:link {color: blue;}
a:visited {color: purple;}
a:hover {color: red;}
a:active {color: yellow;}

CSS Schatten für Texte (Text-Shadow)

p { text-shadow: 1px 1px 1px #000; } 

/*  1.Wert: x-koordinate */
/*  2.Wert: y-koordinate */
/*  3.Wert: Blur-Wert */
/*  4.Wert: Farbe des Schattens */

Klickbaren Elementen Pointer Cursor geben

a[href], input[type='submit'], input[type='image'], label[for], select, button, .pointer {
       cursor: pointer;
}

Fixed Footer

#footer {
   position:fixed;
   left:0px;
   bottom:0px;
   height:30px;
   width:100%;
   background:#999;
}

/* IE 6 */
* html #footer {
   position:absolute;
   top:expression((0-(footer.offsetHeight)+(document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)+(ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop))+'px');
}

Markierten Text anders einfärben

/* Mozilla basierte Browser */
::-moz-selection {
       background-color: #FFA;
       color: #000;
}

/* Safari */
::selection {
       background-color: #FFA;
       color: #000;
}

PHP

Überprüfung ob Website verfügbar

<?php

       if (isDomainAvailible('http://www.grafik-deal.de'))
       {
               echo "Seite ist online";
       }
       else
       {
               echo "Seite nicht verügbar";
       }

       //returns true, if domain is availible, false if not
       function isDomainAvailible($domain)
       {
               //check, if a valid url is provided
               if(!filter_var($domain, FILTER_VALIDATE_URL))
               {
                       return false;
               }

               //initialize curl
               $curlInit = curl_init($domain);
               curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
               curl_setopt($curlInit,CURLOPT_HEADER,true);
               curl_setopt($curlInit,CURLOPT_NOBODY,true);
               curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

               //get answer
               $response = curl_exec($curlInit);

               curl_close($curlInit);

               if ($response) return true;

               return false;
       }
?>

PHP Kommentare

<?php

    /*
           Mehrzeiliger Kommentar
    */

    $i = 0;    // Einzeiliger Kommentar

?>

MYSQL Connect, Query und Ergebnisse anzeigen

<?php

define ('HOSTNAME', 'localhost');
define ('USERNAME', 'username');
define ('PASSWORD', 'password');
define ('DATABASE_NAME', 'recommendations');

$db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die ('I cannot connect to MySQL.');

mysql_select_db(DATABASE_NAME);

$query = "SELECT testimonial,author FROM recommendations WHERE 1 ORDER by rand() LIMIT 1";

$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
echo "<p id="quote">" , ($row['testimonial']) , "</p> \n <p id="author">&ndash;" , nl2br($row['author']) , "</p>";
}

mysql_free_result($result);
mysql_close();
?>

Bilder beschneiden

<?php

$filename= "test.jpg";
list($w, $h, $type, $attr) = getimagesize($filename);
$src_im = imagecreatefromjpeg($filename);

$src_x = '0';   // begin x
$src_y = '0';   // begin y
$src_w = '100'; // width
$src_h = '100'; // height
$dst_x = '0';   // destination x
$dst_y = '0';   // destination y

$dst_im = imagecreatetruecolor($src_w, $src_h);
$white = imagecolorallocate($dst_im, 255, 255, 255);
imagefill($dst_im, 0, 0, $white);

imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);

header("Content-type: image/png");
imagepng($dst_im);
imagedestroy($dst_im);

?>

IE 5 & 6 erkennen

function getMSIE6() {
       $userAgent = strtolower($_SERVER["HTTP_USER_AGENT"]);
       if (ereg("msie 6", $userAgent) || ereg("msie 5", $userAgent)) {
               return true;
       }
       return false;
}

Dateigröße auslesen

/*
 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean
 */

function getFilesize($file,$digits = 2) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
           $fileSize = filesize($filePath);
               $sizes = array("TB","GB","MB","KB","B");
               $total = count($sizes);
               while ($total-- && $fileSize > 1024) {
                       $fileSize /= 1024;
                       }
               return round($fileSize, $digits)." ".$sizes[$total];
       }
       return false;
}

User IP Adresse auslesen

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
     $ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
     $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
     $ip=$_SERVER['REMOTE_ADDR'];
}

Zufallszahl erzeugen

function getRandomId($min = NULL, $max = NULL) {
       if (is_numeric($min) && is_numeric($max)) {
               return mt_rand($min, $max);
       }
       else {
               return mt_rand();
       }
}

Internet Explorer erkennen

if ( eregi("MSIE", getenv( "HTTP_USER_AGENT" ) ) || eregi("Internet Explorer", getenv("HTTP_USER_AGENT" ) ) ) {
  // do something
}

PHP Include

<?php include("navigation.php"); ?>

PHP Umleitung

<?php
  header( 'Location: http://www.yoursite.com/new_page.html' ) ;
?>

Zufallsfarbe

<?php 

    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];

?>
<body style="background: <?php echo $color; ?>;">

Zufälligen Slogan anzigen

<?php
       $f_contents = file ("slogans.txt");
       $line = $f_contents[array_rand ($f_contents)];
       print $line;
?>

Zufälligen Slogan anzigen

<form action="" method="post">
  <label for="Name">Name:</label>
  <input type="text" name="Name" id="Name" />

  <label for="Email">Email:</label>
  <input type="text" name="Email" id="Email" />

  <label for="Message">Message:</label><br />
  <textarea name="Message" rows="20" cols="20" id="Message"></textarea>

  <input type="submit" name="submit" value="Submit" />
</form>

<?php
       // from the form
       $name = trim(strip_tags($_POST['name']));
       $email = trim(strip_tags($_POST['email']));
       $message = htmlentities($_POST['message']);

       // set here
       $subject = "Contact form submitted!";
       $to = 'your@email.com';

       $body = <<<HTML
$message
HTML;

       $headers = "From: $email\r\n";
       $headers .= "Content-type: text/html\r\n";

       // send the email
       mail($to, $subject, $body, $headers);

       // redirect afterwords, if needed
       header('Location: thanks.html');
?>

Bildgröße über den Server ändern

<?php

   function imageResizer($url, $width, $height) {

		header('Content-type: image/jpeg');

		list($width_orig, $height_orig) = getimagesize($url);

		$ratio_orig = $width_orig/$height_orig;

		if ($width/$height > $ratio_orig) {
		  $width = $height*$ratio_orig;
		} else {
		  $height = $width/$ratio_orig;
		}

		// This resamples the image
		$image_p = imagecreatetruecolor($width, $height);
		$image = imagecreatefromjpeg($url);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

		// Output the image
		imagejpeg($image_p, null, 100);

	}

	//works with both POST and GET
	$method = $_SERVER['REQUEST_METHOD'];

	if ($method == 'GET') {

		imageResize($_GET['url'], $_GET['w'], $_GET['h']);

	 } elseif ($method == 'POST') {

	    imageResize($_POST['url'], $_POST['w'], $_POST['h']);
	 }

	// makes the process simpler
	function loadImage($url, $width, $height){
         echo 'image.php?url=', urlencode($url) ,
         '&w=',$width,
         '&h=',$height;
	}

?>

Jquery

Klasse beim hovern hinzufügen/entfernen

$('#elm').hover(
       function(){ $(this).addClass('hover') },
       function(){ $(this).removeClass('hover') }
)

Browser erkennen und Klassen verteilen

// jQBrowser v0.2: http://davecardwell.co.uk/javascript/jquery/plugins/jquery-browserdetect/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(c/a))+String.fromCharCode(c%a+161)};while(c--){if(k[c]){p=p.replace(new RegExp(e(c),'g'),k[c])}}return p}('Ö ¡(){® Ø={\'¥\':¡(){¢ £.¥},\'©\':{\'±\':¡(){¢ £.©.±},\'¯\':¡(){¢ £.©.¯}},\'¬\':¡(){¢ £.¬},\'¶\':¡(){¢ £.¶},\'º\':¡(){¢ £.º},\'Á\':¡(){¢ £.Á},\'À\':¡(){¢ £.À},\'?\':¡(){¢ £.?},\'?\':¡(){¢ £.?},\'?\':¡(){¢ £.?},\'·\':¡(){¢ £.·},\'Â\':¡(){¢ £.Â},\'?\':¡(){¢ £.?},\'Ä\':¡(){¢ £.Ä},\'Ã\':¡(){¢ £.Ã},\'Å\':¡(){¢ £.Å},\'¸\':¡(){¢ £.¸}};$.¥=Ø;® £={\'¥\':\'¿\',\'©\':{\'±\':?,\'¯\':\'¿\'},\'¬\':\'¿\',\'¶\':§,\'º\':§,\'Á\':§,\'À\':§,\'?\':§,\'?\':§,\'?\':§,\'·\':§,\'Â\':§,\'?\':§,\'Ä\':§,\'Ã\':§,\'Å\':§,\'¸\':§};Î(® i=0,«=».ì,°=».í,?=[{\'?\':\'?\',\'¥\':¡(){¢/Ù/.¨(°)}},{\'?\':\'Ú\',\'¥\':¡(){¢ Û.?!=?}},{\'?\':\'È\',\'¥\':¡(){¢/È/.¨(°)}},{\'?\':\'Ü\',\'¥\':¡(){¢/?/.¨(°)}},{\'ª\':\'¶\',\'?\':\'ß Ñ\',\'¥\':¡(){¢/à á â/.¨(«)},\'©\':¡(){¢ «.?(/ã(\\d+(?:\\.\\d+)+)/)}},{\'?\':\'Ì\',\'¥\':¡(){¢/Ì/.¨(«)}},{\'?\':\'Í\',\'¥\':¡(){¢/Í/.¨(°)}},{\'?\':\'Ï\',\'¥\':¡(){¢/Ï/.¨(«)}},{\'?\':\'?\',\'¥\':¡(){¢/?/.¨(«)}},{\'ª\':\'·\',\'?\':\'å Ñ\',\'¥\':¡(){¢/Ò/.¨(«)},\'©\':¡(){¢ «.?(/Ò (\\d+(?:\\.\\d+)+(?:b\\d*)?)/)}},{\'?\':\'Ó\',\'¥\':¡(){¢/æ|Ó/.¨(«)},\'©\':¡(){¢ «.?(/è:(\\d+(?:\\.\\d+)+)/)}}];i<?.Ë;i++){µ(?[i].¥()){® ª=?[i].ª??[i].ª:?[i].?.Õ();£[ª]=É;£.¥=?[i].?;® ?;µ(?[i].©!=?&&(?=?[i].©())){£.©.¯=?[1];£.©.±=Ê(?[1])}ê{® Ç=Ö ë(?[i].?+\'(?:\\\\s|\\\\/)(\\\\d+(?:\\\\.\\\\d+)+(?:(?:a|b)\\\\d*)?)\');?=«.?(Ç);µ(?!=?){£.©.¯=?[1];£.©.±=Ê(?[1])}}?}};Î(® i=0,´=».ä,?=[{\'ª\':\'¸\',\'?\':\'ç\',\'¬\':¡(){¢/é/.¨(´)}},{\'?\':\'Ô\',\'¬\':¡(){¢/Ô/.¨(´)}},{\'?\':\'Æ\',\'¬\':¡(){¢/Æ/.¨(´)}}];i<?.Ë;i++){µ(?[i].¬()){® ª=?[i].ª??[i].ª:?[i].?.Õ();£[ª]=É;£.¬=?[i].?;?}}}();',77,77,'function|return|Private|name|browser|data|false|test|version|identifier|ua|OS|result|var|string|ve|number|undefined|opera|pl|if|aol|msie|win|match|camino|navigator|mozilla|icab|konqueror|Unknown|flock|firefox|netscape|linux|safari|mac|Linux|re|iCab|true|parseFloat|length|Flock|Camino|for|Firefox|Netscape|Explorer|MSIE|Mozilla|Mac|toLowerCase|new|break|Public|Apple|Opera|window|Konqueror|Safari|KDE|AOL|America|Online|Browser|rev|platform|Internet|Gecko|Windows|rv|Win|else|RegExp|userAgent|vendor'.split('|')))

/* ----------------------------------------------------------------- */

var aol       = $.browser.aol();       // AOL Explorer
var camino    = $.browser.camino();    // Camino
var firefox   = $.browser.firefox();   // Firefox
var flock     = $.browser.flock();     // Flock
var icab      = $.browser.icab();      // iCab
var konqueror = $.browser.konqueror(); // Konqueror
var mozilla   = $.browser.mozilla();   // Mozilla
var msie      = $.browser.msie();      // Internet Explorer Win / Mac
var netscape  = $.browser.netscape();  // Netscape
var opera     = $.browser.opera();     // Opera
var safari    = $.browser.safari();    // Safari

var userbrowser     = $.browser.browser(); //detected user browser

//operating systems

var linux = $.browser.linux(); // Linux
var mac   = $.browser.mac();   // Mac OS
var win   = $.browser.win();   // Microsoft Windows

//version

var userversion    = $.browser.version.number();

/* ----------------------------------------------------------------- */

if (mac == true) { 

	$("html").addClass("mac"); 

} else if (linux == true) {

	$("html").addClass("linux"); 

} else if (win == true) {

	$("html").addClass("windows");

}

/* ----------------------------------------------------------------- */			

if (userbrowser == "Safari") {

	$("html").addClass("safari"); 

} else if (userbrowser == "Firefox") {

	$("html").addClass("firefox"); 

} else if (userbrowser == "Camino") {

	$("html").addClass("camino"); 

} else if (userbrowser == "AOL Explorer") {

	$("html").addClass("aol"); 

} else if (userbrowser == "Flock") {

	$("html").addClass("flock"); 

} else if (userbrowser == "iCab") {

	$("html").addClass("icab"); 

} else if (userbrowser == "Konqueror") {

	$("html").addClass("konqueror"); 

} else if (userbrowser == "Mozilla") {

	$("html").addClass("mozilla"); 

} else if (userbrowser == "Netscape") {

	$("html").addClass("netscape"); 

} else if (userbrowser == "Opera") {

	$("html").addClass("opera"); 

} else if (userbrowser == "Internet Explorer") {

	$("html").addClass("ie");

} else {}

$("html").addClass("" + userversion + "");

Prüfung auf Vorhandensein eines Elements

if ( $('#myElement').length > 0 ) {
    // it exists
}

Prüfen ob jQuery geladen ist

if (typeof jQuery == 'undefined') {

    // jQuery IS NOT loaded, do stuff here.

}

Letzten Tweet anzeigen

$.getJSON("http://twitter.com/statuses/user_timeline/username.json?callback=?", function(data) {
     $("#twitter").html(data[0].text);
});

Div Höhen angleichen

var maxHeight = 0;

$("div").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});

$("div").height(maxHeight);

Alle internen Links finden

var siteURL = "http://" + top.location.host.toString();

var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

Image Preloader

<script type="text/javascript">
$.preloadImages = function()
{
       for(var i = 0; i<arguments.length; i++)
       {
               $("<img />").attr("src", arguments[i]);
       }
}

$(document).ready(function()
{
       $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});
</script>

Externe Links in neuem Fenster laden

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

Passwortstärke testen

$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('More Characters');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').className = 'ok';
             $('#passstrength').html('Strong!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').className = 'alert';
             $('#passstrength').html('Medium!');
     } else {
             $('#passstrength').className = 'error';
             $('#passstrength').html('Weak!');
     }
     return true;
});

Wordpress

Avatargröße ändern

wp_list_comments('avatar_size=80');

Loop auf Basis von Custom Fields

<?php

 $querydetails = "
   SELECT wposts.*
   FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
   WHERE wposts.ID = wpostmeta.post_id
   AND wpostmeta.meta_key = 'readmoretext'
   AND wpostmeta.meta_value = 'Go check this out'
   AND wposts.post_status = 'publish'
   AND wposts.post_type = 'post'
   ORDER BY wposts.post_date DESC
 ";

 $pageposts = $wpdb->get_results($querydetails, OBJECT)

 ?>

jQuery in Theme einbinden

if( !is_admin()){
   wp_deregister_script('jquery');
   wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"), false, '1.3.2');
   wp_enqueue_script('jquery');
}

Custom Field ausgeben

<?php echo get_post_meta($post->ID, 'mood', true); ?>

Posts auflisten, aktuellen hervorheben

<ul>

    <?php
        $lastposts = get_posts('numberposts=5&orderby=rand&cat=-52');
        foreach($lastposts as $post) :
        setup_postdata($post); ?>

        <li<?php if ( $post->ID == $wp_query->post->ID ) { echo " class="current""; } else {} ?>>

            <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>

        </li>

    <?php endforeach; ?>

</ul>

Such-Bots von Suchergebnissen fernhalten

<?php if(is_search()) { ?>
   <meta name="robots" content="noindex, nofollow" />
<?php }?>

Kategorien aus Loop ausschließen

<?php query_posts('cat=-3'); ?>

<?php if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

		<h3></h3>

		<p><?php the_time('F jS, Y') ?></p>

		<?php the_content(); ?>

<?php endwhile; ?>

Posts einer bestimmten Kategorie loopen

<?php query_posts('cat=5'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
   <?php the_content(); ?>
<?php endwhile; endif; ?>