<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Xguiden &#187; AJAX</title>
	<atom:link href="http://xguiden.dk/tag/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://xguiden.dk</link>
	<description>Dine guides findes her</description>
	<lastBuildDate>Sat, 13 Mar 2010 16:37:57 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Awesome CSS+JS form styling</title>
		<link>http://xguiden.dk/2010/03/10/awesome-cssjs-form-styling/</link>
		<comments>http://xguiden.dk/2010/03/10/awesome-cssjs-form-styling/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 10:14:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[attribute]]></category>
		<category><![CDATA[auto login]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[content]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[element]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[input type text]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[javascript library]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[open source project]]></category>
		<category><![CDATA[scenarios]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Transparent]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[webkit]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=5558</guid>
		<description><![CDATA[Sexy CSS+JS Form

I was working on our new open source project that i think you will like and I was working on the registration page. This is what I got in the end and i will walk you trough the process with me. This new tutorial is about styling the forms of your website, I [...]]]></description>
			<content:encoded><![CDATA[<div><a rel="attachment wp-att-312" href="http://xguiden.dk/?attachment_id=312"><img class="size-medium wp-image-312" src="http://blog.ajaxmasters.com/wp-content/uploads/2010/03/sexy-form-300x214.png" alt="Sexy CSS Form" width="300" height="214" /></a>Sexy CSS+JS Form</p>
</div>
<p>I was working on our new open source project that i think you will like and I was working on the registration page. This is what I got in the end and i will walk you trough the process with me. This new tutorial is about styling the forms of your website, I find it very good looking and very simple to implement. We will use simple CSS and some JavaScript.</p>
<p>Usually for inserting text into the inputs or our forms we set the value attribute with the text and then use javascript to check for different scenarios for doing some fancy things. This is different we will use labels to fill the text and move them under the inputs and then just do our magic with JS.</p>
<p>The JavaScript library that we will use to create this effect for our forms is <a href="http://jquery.com" target="_blank">Jquery</a></p>
<p><strong>1. Creating the markup!</strong></p>
<pre>            &lt;div id="login"&gt;
                &lt;div class="sayit"&gt;Log In:&lt;/div&gt;
                &lt;form action="javascript:void(0)" onsubmit="login()" autocomplete="off"&gt;
                    &lt;label for="username"&gt;Username&lt;/label&gt;
                    &lt;input type="text" id="username"/&gt;
                    &lt;label for="password"&gt;Password&lt;/label&gt;
                    &lt;input type="password" id="password"/&gt;
                    &lt;input type="submit" class="medium button green" value="Log me In"/&gt;
                &lt;/form&gt;
            &lt;/div&gt;</pre>
<p>The above code is our markup and as you can see is very simple and it can be changed as you like because the code that we will use for checking for different scenarios in javascript will work without necessary classes or ids. We have 2 inputs and 2 labels, one is password one is text and we can work with these ones, you can add as many as you like.</p>
<p>Now let’s style these bastards! <img class="wp-smiley" src="http://blog.ajaxmasters.com/wp-content/plugins/smilies-themer/pidgin/smile-big.png" alt=":D" /></p>
<p><strong>2. Use CSS to style the form elements!</strong></p>
<pre>input[type=text],input[type=password]{padding: 5px 10px; background-color: transparent;	position: relative; z-index: 2;}
label{position: absolute; z-index: 1;-webkit-transition: opacity 0.15s linear; color: #bababa; background-color: #FFFFFF; }

#login{width: 290px; margin: 0 auto;}
#login input[type=text],#login input[type=password]{width:270px; margin: 5px 0; font-size: 24px; font-weight: bold; border: 1px solid #ccc; -moz-border-radius:5px; -webkit-border-radius:5px; color: #595959;}
#login label{font-size: 24px; margin: 14px 10px;}

#login .sayit{font-size:24px; color: #595959; font-style: italic; padding-bottom: 5px;}</pre>
<p>What we did here is make the label absolute so it will go under the input. This is important you will have to place the label before the input so remember this! The input will have a position relative and a z-index of 2 so we can be sure it will land above the label. Next we define the login div by using his id(<em>#login</em>). We use CSS3 for creating the round borders for the input and style the label by setting a big font-size to fit the input. The rest is pretty obvious, if you have trouble understanding this then let us know in the comments.</p>
<p><strong>3. Make everything move with JS!</strong></p>
<pre>$(document).ready(function(){
    $.string(String.prototype);
    $("input,textarea").each(function (type) {
        $(this).focus(function () {
            if($(this).val().blank())
                $(this).prev("label").fadeTo('fast',0.45);
        });

        $(this).keypress(function () {
            $(this).prev("label").fadeTo('fast',0);
        });

        $(this).blur(function () {
            if($(this).val().blank()){
                $(this).prev("label").fadeTo('fast',1);
            }
        });
    });
});</pre>
<p>We use here jQuery of course that we add using the google api like this:</p>
<pre>        &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt;</pre>
<p>And one plugin that I use to extend the jQuery string properties and that is <a href="http://stilldesigning.com/dotstring/">$.string plugin</a>. After we do that we create the above code and we assign to input and textarea elements a focus, keypress and blur actions. We use the focus action to lower the labels opacity to 45% then on keypress we just hide it for good. Then on blur we check to see if anything was written in our sexy element and if not then we fade the label back to 100%. This is kind of everything we do here, pretty simple. <img class="wp-smiley" src="http://blog.ajaxmasters.com/wp-content/plugins/smilies-themer/pidgin/smile.png" alt=":)" /></p>
<p><strong>4. Showing of a demo and download source</strong></p>
<p>I’ve set up a demo here: <a href="http://tutorials.ajaxmasters.com/sexy-form/" target="_blank"><strong><em>DEMO</em></strong></a></p>
<p>The source code you can either pick it from the demo page or from here: <a href="http://tutorials.ajaxmasters.com/sexy-form/source.zip"><strong><em>SOURCE</em></strong></a></p>
<p><strong>5. Wrapping up!</strong></p>
<p>So here is our nice form styling that you can use on your website and that can be done very easily. Feel free to leave us comments and suggestions. <strong>Thanks a lot!</strong></p>
<p>Have fun coding!<img src="http://feeds.feedburner.com/~r/AjaxmastersBlogRss/~4/0J4er0tKB4Q" alt="" width="1" height="1" /></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/attribute/" title="attribute" rel="tag">attribute</a>, <a href="http://xguiden.dk/tag/auto-login/" title="auto login" rel="tag">auto login</a>, <a href="http://xguiden.dk/tag/code/" title="code" rel="tag">code</a>, <a href="http://xguiden.dk/tag/content/" title="content" rel="tag">content</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/css3/" title="css3" rel="tag">css3</a>, <a href="http://xguiden.dk/tag/design/" title="design" rel="tag">design</a>, <a href="http://xguiden.dk/tag/element/" title="element" rel="tag">element</a>, <a href="http://xguiden.dk/tag/function/" title="function" rel="tag">function</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/input-type-text/" title="input type text" rel="tag">input type text</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/javascript-library/" title="javascript library" rel="tag">javascript library</a>, <a href="http://xguiden.dk/tag/jquery/" title="jquery" rel="tag">jquery</a>, <a href="http://xguiden.dk/tag/js/" title="js" rel="tag">js</a>, <a href="http://xguiden.dk/tag/login/" title="login" rel="tag">login</a>, <a href="http://xguiden.dk/tag/open-source-project/" title="open source project" rel="tag">open source project</a>, <a href="http://xguiden.dk/tag/scenarios/" title="scenarios" rel="tag">scenarios</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/transparent/" title="Transparent" rel="tag">Transparent</a>, <a href="http://xguiden.dk/tag/tutorial/" title="tutorial" rel="tag">tutorial</a>, <a href="http://xguiden.dk/tag/webkit/" title="webkit" rel="tag">webkit</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/03/10/making-a-mosaic-slideshow-with-jquery-and-css/" title="Making a Mosaic Slideshow With jQuery and CSS (10/03/2010)">Making a Mosaic Slideshow With jQuery and CSS</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/" title="How to Code up a Web Design from PSD to HTML (15/02/2010)">How to Code up a Web Design from PSD to HTML</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/sweet-ajax-tabs-with-jquery-1-4-and-css3/" title="Sweet AJAX Tabs With jQuery 1.4 and CSS3 (13/02/2010)">Sweet AJAX Tabs With jQuery 1.4 and CSS3</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/making-a-photoshoot-effect-with-jquery-css/" title="Making a Photoshoot Effect With jQuery and CSS (13/02/2010)">Making a Photoshoot Effect With jQuery and CSS</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/03/how-we%e2%80%99ll-be-building-websites-in-5-years-html5-and-css3-layout/" title="How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout (03/03/2010)">How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/03/10/awesome-cssjs-form-styling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uncovering jQuery’s Hidden Features</title>
		<link>http://xguiden.dk/2010/03/09/uncovering-jquery%e2%80%99s-hidden-features/</link>
		<comments>http://xguiden.dk/2010/03/09/uncovering-jquery%e2%80%99s-hidden-features/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 12:22:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Cool]]></category>
		<category><![CDATA[element]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[Source]]></category>
		<category><![CDATA[valid]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=5533</guid>
		<description><![CDATA[jQuery is not always as it appears. There&#8217;s a lot of cool stuff going on under the surface, and there are many methods just waiting to be discovered, and many potential usages of jQuery&#8217;s API that you may not have considered before. In this article I&#8217;ll be taking you through a few of the not-so-obvious [...]]]></description>
			<content:encoded><![CDATA[<p>jQuery is not always as it appears. There&#8217;s a lot of cool stuff going on under the surface, and there are many methods just waiting to be discovered, and many potential usages of jQuery&#8217;s API that you may not have considered before. In this article I&#8217;ll be taking you through a few of the not-so-obvious things I&#8217;ve discovered about jQuery.</p>
<p><span> </span></p>
<h2><span>1. </span>Understand jQuery!</h2>
<p>When you call <em>&#8216;jQuery&#8217;</em> what happens?</p>
<p>The jQuery function itself is very simple:</p>
<pre>jQuery = function (selector, context) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init(selector, context);
};</pre>
<p>Under its skin, the jQuery function (commonly referred to as the &#8220;wrapper&#8221; function) simply returns an instantiated jQuery object — i.e. an instance of the <em>&#8216;jQuery.fn.init&#8217;</em> constructor.</p>
<p>This is useful to know; with this information we know that each time we call <em>&#8216;jQuery&#8217;</em> we&#8217;re actually creating a totally unique object with a set of properties. jQuery is clever in that it gives you an object that can be treated as an array. Each of your elements (all together, commonly known as the &#8220;collection&#8221;) is referenced within the object under a numerical index, just like within an array. And jQuery also gives this object a <em>&#8216;length&#8217;</em> property, just as you would expect from an array. This opens up a world of possibilities. For one, it means that we can borrow some functionality from <em>&#8216;Array.prototype&#8217;</em>. jQuery&#8217;s <em>&#8217;slice&#8217;</em> method is a good example of this — modified from the source:</p>
<pre>/* ... jQuery.fn.extend({ ... */
slice: function() {
    return this.pushStack(
        Array.prototype.slice.apply( this, arguments ),
        "slice",
        Array.prototype.slice.call(arguments).join(",")
    );
},
/* ... */</pre>
<p>The native <em>&#8217;slice&#8217;</em> method doesn&#8217;t care that <em>&#8216;this&#8217;</em> is not a real array– it&#8217;ll be fine with anything that&#8217;s got a <em>&#8216;length&#8217;</em> property and <em>[0]</em>, <em>[1]</em>, <em>[2]</em> etc.</p>
<p>There are some other interesting properties within this jQuery object — <em>&#8216;.selector&#8217;</em> and <em>&#8216;.context&#8217;</em> will, most of the time, reflect the arguments that you pass into <em>&#8216;jQuery(…)&#8217;</em>.</p>
<pre>var jqObject = jQuery('a');
jqObject.selector; // =&gt; "a"</pre>
<p>One thing that&#8217;s important to note is that jQuery will sometimes give you new jQuery objects to work with. If you run a method that changes the collection in some way, such as <em>&#8216;.parents()&#8217;</em>, then jQuery won&#8217;t modify the current object; it&#8217;ll simply pass you a brand new one:</p>
<pre>var originalObject = jQuery('a');
var anotherObject = originalObject.parents();

originalObject === anotherObject; // =&gt; false</pre>
<p>All methods that appear to mutate the collection in some way return a brand new jQuery object — you can still access the old object though, via <em>&#8216;.end()&#8217;</em>, or more verbosely, via <em>&#8216;.prevObject&#8217;</em>.</p>
<h2><span>2. </span>Bread-and-butter Element Creation</h2>
<p>Central to jQuery&#8217;s DOM capabilities, is its element creation syntax. 1.4 brought with it an entirely new way to create your elements quickly and succinctly. E.g.</p>
<pre>var myDiv = jQuery('&lt;div/&gt;', {
    id: 'my-new-element',
    class: 'foo',
    css: {
        color: 'red',
        backgrondColor: '#FFF',
        border: '1px solid #CCC'
    },
    click: function() {
        alert('Clicked!');
    },
    html: jQuery('&lt;a/&gt;', {
        href: '#',
        click: function() {
            // do something
            return false;
        }
    })
});</pre>
<p>As of 1.4 you can pass a second argument to the jQuery function when you&#8217;re creating an element — the object you pass will, for the most part, act as if you were passing it to <em>&#8216;.attr(…)&#8217;</em>. However, jQuery will map some of the properties to its own methods, for example, the <em>&#8216;click&#8217;</em> property maps to jQuery&#8217;s <em>&#8216;click&#8217;</em> method (which binds an event handler for the <em>&#8216;click&#8217;</em> event) and <em>&#8216;css&#8217;</em> maps to jQuery&#8217;s <em>&#8216;css&#8217;</em> method etc.</p>
<p>To check out what properties map to jQuery&#8217;s methods, open your console and type <em>&#8216;jQuery.attrFn&#8217;</em>.</p>
<h2><span>3. </span>Serialize your Inputs</h2>
<p>jQuery provides a method that you can use to serialize all of the inputs within one or more forms. This is useful when submitting data via XHR (&#8220;Ajax&#8221;). It&#8217;s been in jQuery for a long time but it&#8217;s not often talked about and so many developers don&#8217;t realise it&#8217;s there. Submitting an entire form via Ajax, using jQuery, couldn&#8217;t be simpler:</p>
<pre>var myForm = $('#my-form');
jQuery.post('submit.php', myForm.serialize(), function(){
    alert('Data has been sent!');
});</pre>
<p>jQuery also provides the <em>&#8217;serializeArray&#8217;</em> method, which is designed to be used with multiple forms, and the <em>&#8216;param&#8217;</em> helper function (under the jQuery namespace) which takes a regular object and returns a query string, e.g.</p>
<pre>var data = {
    name: 'Joe',
    age: 44,
    profession: 'Web Developer'
};

jQuery.param(data); // =&gt; "name=Joe&amp;age=44&amp;profession=Web+Developer"</pre>
<h2><span>4. </span>Animate Anything</h2>
<p>jQuery&#8217;s <em>&#8216;animate&#8217;</em> method is probably the most flexible of jQuery&#8217;s methods. It can be used to animate pretty much anything, not just CSS properties, and not just DOM elements. This is how you would normally use <em>&#8216;animate&#8217;</em>:</p>
<pre>jQuery('#box').animate({
    left: 300,
    top: 300
});</pre>
<p>When you specify a property to animate (e.g. <em>&#8216;top&#8217;</em>) jQuery checks to see if you&#8217;re animating something with a style property (<em>&#8216;element.style&#8217;</em>), and it checks if the specified property (<em>&#8216;top&#8217;</em>) is defined under <em>&#8217;style&#8217;</em> — if it&#8217;s not then jQuery simply updates <em>&#8216;top&#8217;</em> on the element itself. Here&#8217;s an example:</p>
<pre>jQuery('#box').animate({
    top: 123,
    foo: 456
});</pre>
<p><em>&#8216;top&#8217;</em> is a valid CSS property, so jQuery will update <em>&#8216;element.style.top&#8217;</em>, but <em>&#8216;foo&#8217;</em> is <strong>not</strong> a valid CSS property, so jQuery will simply update <em>&#8216;element.foo&#8217;</em>.</p>
<p>We can use this to our advantage. Let&#8217;s say, for example, that you want to animate a square on a canvas. First let&#8217;s define a simple constructor and a <em>&#8216;draw&#8217;</em> method that&#8217;ll be called on every step of the animation:</p>
<pre>function Square(cnvs, width, height, color) {

    this.x = 0;
    this.y = 0;
    this.width = width;
    this.height = height;
    this.color = color;

    this.cHeight = cnvs.height;
    this.cWidth = cnvs.width;
    this.cntxt = cnvs.getContext('2d');

}

Square.prototype.draw = function() {

    this.cntxt.clearRect(0, 0, this.cWidth, this.cHeight);
    this.cntxt.fillStyle = this.color;
    this.cntxt.fillRect(this.x, this.y, this.width, this.height);

};</pre>
<p>We&#8217;ve created our &#8216;Square&#8217; constructor, and one of its methods. Creating a canvas and then animating it couldn&#8217;t be simpler:</p>
<pre>// Create a &lt;canvas/&gt; element
var canvas = $('&lt;canvas/&gt;').appendTo('body')[0];
canvas.height = 400;
canvas.width = 600;

// Instantiate Square
var square = new Square(canvas, 70, 70, 'rgb(255,0,0)');

jQuery(square).animate({
    x: 300,
    y: 200
}, {
    // 'draw' should be called on every step
    // of the animation:
    step: jQuery.proxy(square, 'draw'),
    duration: 1000
});</pre>
<p>This is a very simple effect, but it does clearly demonstrate the possibilities. You can see it in action here: <a href="http://jsbin.com/ocida" target="_blank">http://jsbin.com/ocida</a> (this will only work in browsers that support the HTML5 canvas)</p>
<h2><span>5. </span>jQuery.ajax Returns the XHR Object</h2>
<p>jQuery&#8217;s Ajax utility functions (<em>&#8216;jQuery.ajax&#8217;</em>, <em>&#8216;jQuery.get&#8217;</em>, <em>&#8216;jQuery.post&#8217;</em>) all return an <em>&#8216;XMLHttpRequest&#8217;</em> object which you can use to perform subsequent operations on any request. For example:</p>
<pre>var curRequest;

jQuery('button.makeRequest').click(function(){
    curRequest = jQuery.get('foo.php', function(response){
        alert('Data: ' + response.responseText);
    });
});

jQuery('button.cancelRequest').click(function(){
    if (curRequest) {
        curRequest.abort(); // abort() is a method of XMLHttpRequest
    }
});</pre>
<p>Here we&#8217;re making a request whenever the <em>&#8216;makeRequest&#8217;</em> button is clicked — and we&#8217;re cancelling the active request if the user clicks the <em>&#8216;cancelRequest&#8217;</em> button.</p>
<p>Another potential usage is for synchronous requests:</p>
<pre>var myRequest = jQuery.ajax({
    url: 'foo.txt',
    async: false
});

console.log(myRequest.responseText);</pre>
<p>Read more about the <em><a href="https://developer.mozilla.org/en/XMLHttpRequest" target="_blank">&#8216;XMLHttpRequest&#8217;</a></em> object and also be sure to check out <a href="http://api.jquery.com/category/ajax/" target="_blank">jQuery&#8217;s Ajax utilities</a>.</p>
<h2><span>6. </span>Custom Queues</h2>
<p>jQuery has a built-in queuing mechanism that&#8217;s used by all of its animation methods (all of which use <em>&#8216;animate()&#8217;</em> really). This queuing can be illustrated easily with a simple animation:</p>
<pre>jQuery('a').hover(function(){
    jQuery(this).animate({paddingLeft:'+=15px'});
}, function(){
    jQuery(this).animate({paddingLeft:'-=15px'});
});</pre>
<p>Quickly hovering over a bunch of anchors and then hovering over them again will cause the animations to queue up and occur one at a time — I&#8217;m sure many of you have witnessed this queuing effect before. If not, check it out here: <a href="http://jsbin.com/aqaku" target="_blank"><strong>http://jsbin.com/aqaku</strong></a></p>
<p>The <em>&#8216;queue&#8217;</em> method is similar to the well-known <em>&#8216;each&#8217;</em> method in how it&#8217;s called. You pass a function, which will eventually be called for each of the elements in the collection:</p>
<pre>jQuery('a').queue(function(){
    jQuery(this).addClass('all-done').dequeue();
});</pre>
<p>Passing just a function to <em>&#8216;queue&#8217;</em> will cause that function to be added to the default <em>&#8216;fx&#8217;</em> queue, i.e. the queue used by all animations done by jQuery. Therefore, this function will not be called until all current animations occurring on each element in the collection (in this case, all anchors) have completed.</p>
<p>Notice that we&#8217;re adding a class of <em>&#8216;all-done&#8217;</em> in the function above. As outlined, this class will only be added when all current animations are complete. We&#8217;re also calling the <em>&#8216;dequeue&#8217;</em> method. <strong>This is very important</strong>, as it will allow jQuery to continue with the queue (i.e. it lets jQuery know that you&#8217;re finished with whatever you&#8217;re doing). jQuery 1.4 provides another way of continuing the queue; instead of calling <em>&#8216;dequeue&#8217;</em>, simply call the first argument passed to your function:</p>
<pre>jQuery('a').queue(function(nextItemInQueue){
    // Continue queue:
    nextItemInQueue();
});</pre>
<p>This does exactly the same, although it&#8217;s slightly more useful in that it can be called anywhere within your function, even within a mess of closures (that typically destroy the <em>&#8216;this&#8217;</em> keyword). Of course, pre-jQuery-1.4 you could just save a reference to <em>&#8216;this&#8217;</em>, but that would get a bit tiresome.</p>
<p>To add a function to a custom queue, simply pass your custom queue&#8217;s name as the first argument and the function as the second:</p>
<pre>jQuery('a').queue('customQueueName', function(){
    // Do stuff
    jQuery(this).dequeue('customQueueName');
});</pre>
<p>Notice that, since we&#8217;re not using the default <em>&#8216;fx&#8217;</em> queue, we also have to pass our queue&#8217;s name to the <em>&#8216;dequeue&#8217;</em> method, in order to allow jQuery to continue with our custom queue.</p>
<p>Read more about <a href="http://api.jquery.com/queue" target="_blank"><em>&#8216;queue&#8217;</em></a>, <a href="http://api.jquery.com/dequeue/" target="_blank"><em>&#8216;dequeue&#8217;</em></a> and <a href="http://api.jquery.com/jQuery.queue/" target="_blank"><em>&#8216;jQuery.queue&#8217;</em></a>.</p>
<h2><span>7. </span>Event Namespacing</h2>
<p>jQuery provides a way for you to namespace events, which can be very useful when authoring plugins and third-party components. If needed, the user of your plugin can effectively disable your plugin by unbinding all event handlers that it&#8217;s registered.</p>
<p>To add a namespace when registering an event handler, simply suffix the event name with a period and then your unique namespace (e.g. <em>&#8216;<span>.fooPlugin</span>&#8216;</em>):</p>
<pre>jQuery.fn.foo = function() {

    this.bind('click.fooPlugin', function() {
        // do stuff
    });

    this.bind('mouseover.fooPlugin', function() {
        // do stuff
    });

    return this;
};

// Use the plugin:
jQuery('a').foo();

// Destroy its event handlers:
jQuery('a').unbind('.fooPlugin');</pre>
<p>Passing just the namespace to <em>&#8216;unbind&#8217;</em> will unbind all event handlers with that namespace.</p>
<h2>Conclusion</h2>
<p>So which ones did I miss? Any helpful features that you feel jQuery doesn’t document well enough? Let’s discuss in the comments!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/WA01DphnOQdl0SzTX7fYcInH-q8/0/da"><img src="http://feedads.g.doubleclick.net/~a/WA01DphnOQdl0SzTX7fYcInH-q8/0/di" border="0" alt="" /></a><br />
<img src="http://feedads.g.doubleclick.net/~a/WA01DphnOQdl0SzTX7fYcInH-q8/1/di" border="0" alt="" /></p>
<p><img src="http://feeds.feedburner.com/~r/nettuts/~4/sNBgElc3bIw" alt="" width="1" height="1" /></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/cool/" title="Cool" rel="tag">Cool</a>, <a href="http://xguiden.dk/tag/element/" title="element" rel="tag">element</a>, <a href="http://xguiden.dk/tag/function/" title="function" rel="tag">function</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/html/" title="HTML" rel="tag">HTML</a>, <a href="http://xguiden.dk/tag/html5/" title="html5" rel="tag">html5</a>, <a href="http://xguiden.dk/tag/jquery/" title="jquery" rel="tag">jquery</a>, <a href="http://xguiden.dk/tag/php/" title="php" rel="tag">php</a>, <a href="http://xguiden.dk/tag/reference/" title="reference" rel="tag">reference</a>, <a href="http://xguiden.dk/tag/source/" title="Source" rel="tag">Source</a>, <a href="http://xguiden.dk/tag/valid/" title="valid" rel="tag">valid</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/18/make-your-mootools-code-shorter-faster-and-stronger/" title="Make your MooTools Code Shorter, Faster, and Stronger (18/02/2010)">Make your MooTools Code Shorter, Faster, and Stronger</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/jquery-ajax-validation-contact-form-with-modal-slide-in-transition/" title="jQuery AJAX Validation Contact Form with Modal + Slide-in Transition (13/02/2010)">jQuery AJAX Validation Contact Form with Modal + Slide-in Transition</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/" title="How to Code up a Web Design from PSD to HTML (15/02/2010)">How to Code up a Web Design from PSD to HTML</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/09/2-different-ways-for-getting-twitter-status-php-and-jquery/" title="2 Different Ways For Getting Twitter Status / PHP and jQuery (09/03/2010)">2 Different Ways For Getting Twitter Status / PHP and jQuery</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/protect-your-flash-files-from-decompilers-by-using-encryption/" title="Protect Your Flash Files From Decompilers by Using Encryption (13/02/2010)">Protect Your Flash Files From Decompilers by Using Encryption</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/03/09/uncovering-jquery%e2%80%99s-hidden-features/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Coding a CSS3 &amp; HTML5 One-Page Website Template</title>
		<link>http://xguiden.dk/2010/02/18/coding-a-css3-html5-one-page-website-template/</link>
		<comments>http://xguiden.dk/2010/02/18/coding-a-css3-html5-one-page-website-template/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 11:20:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[avi]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[DOCTYPE]]></category>
		<category><![CDATA[fil]]></category>
		<category><![CDATA[fix]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[Gradient]]></category>
		<category><![CDATA[Header]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[Internet Explorer]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[META]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[Photoshop]]></category>
		<category><![CDATA[png]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[standard]]></category>
		<category><![CDATA[Start]]></category>
		<category><![CDATA[table]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[tags]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[URL]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=5132</guid>
		<description><![CDATA[Web development is an area in which you have to keep up with the latest technologies and techniques, so that you are at the top of your game.  And no wonder – this is an area which changes with an amazing pace. What is the standard now will be obsolete in just a couple of [...]]]></description>
			<content:encoded><![CDATA[<p>Web development is an area in which you have to keep up with the latest technologies and techniques, so that you are at the top of your game.  And no wonder – this is an area which changes with an amazing pace. What is the standard now will be obsolete in just a couple of years.</p>
<p>But changes do not come from nowhere. The early adopters are already using what we are going to use day-to-day a few years from now. One of these technologies is <strong>HTML5</strong> – the new version of the fundamental language of the web.</p>
<p>Today we are making a <strong>HTML5</strong> web template, using some of the new features brought by CSS3 and jQuery with the <strong>scrollTo</strong> plug-in. As HTML5 is still a work in progress, you can optionally download a <strong>XHTML version </strong>of the template <a href="http://tutorialzine.com/2010/02/free-xhtml-css3-website-template/" target="_blank">here</a>.</p>
<h3>Step 1 – The Design</h3>
<p>Every design process starts with an initial idea which you later build upon. At this stage designers usually go with programs such as Photoshop to work on the details and see how it will all look.</p>
<div><a href="http://tutorialzine.com/wp-content/uploads/2010/02/i1.png"><img class="size-full wp-image-672" src="http://tutorialzine.com/wp-content/uploads/2010/02/i1.png" alt="Photoshop Design" width="620" height="460" /></a>Photoshop Design</div>
<p>After this, the design is hand coded with HTML and CSS going hand by hand, moving from designing the background, colors and fonts, to detail work on the content section.</p>
<h3>Step 2 – HTML</h3>
<p>It is a good time to note, that <strong>HTML5</strong> is still a work in progress. It will remain so probably till around <strong>2022</strong> (I am absolutely serious about this). However some parts of the standard are complete, and can be used <strong>today</strong>.</p>
<p>In this tutorial, we are using a few of the tags introduced with this new version of HTML:</p>
<ul>
<li><strong>header</strong> – wraps your page header;</li>
<li><strong>footer</strong> – wraps your page footer;</li>
<li><strong>section</strong> – groups content into sections (e.g. main area, sidebar etc);</li>
<li><strong>article</strong> – separates the individual articles from the rest of the page;</li>
<li><strong>nav</strong> – contains your navigation menu;</li>
<li><strong>figure</strong> – usually contains an image used as an illustration for your article.</li>
</ul>
<p>These are used exactly as you would use normal divs. With the difference being that these tags organizes your page semantically. In other words, you can present your content in such a way, that the subject matter of your page can be more easily determined. As a result services, such as search engines, will bring you more targeted visitors and thus boost your revenue (and theirs actually).</p>
<p>However, there are some <strong>implications</strong> in using HTML5 today. One of the most notable is the IE family of browsers, which does not support these tags (it can be fixed with a simple JavaScript include file though). This is why you should base your decision for moving to HTML5 on your site’s audience. And just for this purpose, we are releasing a <a href="http://tutorialzine.com/2010/02/free-xhtml-css3-website-template/" target="_blank">pure XHTML version</a> of this template as well.</p>
<h4>template.html – Head section</h4>
<pre>&lt;!DOCTYPE html&gt; &lt;!-- The new doctype --&gt;

&lt;html&gt;
&lt;head&gt;

	&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;

	&lt;title&gt;Coding A CSS3 &amp;amp; HTML5 One Page Template | Tutorialzine demo&lt;/title&gt;

	&lt;link rel="stylesheet" type="text/css" href="styles.css" /&gt;

	&lt;!-- Internet Explorer HTML5 enabling script: --&gt;

	&lt;!--[if IE]&gt;
		&lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
		&lt;style type="text/css"&gt;

			.clear {
				zoom: 1;
				display: block;
			}

		&lt;/style&gt;

	&lt;![endif]--&gt;

&lt;/head&gt;</pre>
<p>You can notice the new <strong>&lt;DOCTYPE&gt;</strong> at line one, which tells the browser that the page is created with the HTML5 standard. It is also much shorter and easier to remember than older doctypes.</p>
<p>After specifying the encoding of the document and the title, we move on to including a special JS file that will enable Internet Explorer (any version) to render HTML5 tags properly. Again, this means that if a visitor is using IE and has <strong>JavaScript disabled</strong>, the page is going to show up all <strong>messed up</strong>. This is why, depending on your audience, you should consider the regular XHTML version of this template, which works in <strong>any browser</strong> and is <a href="http://tutorialzine.com/2010/02/free-xhtml-css3-website-template/" target="_blank">released free for all our readers here</a>.</p>
<h4>template.html – Body Section</h4>
<pre>&lt;body&gt;

	&lt;section id="page"&gt; &lt;!-- Defining the #page section with the section tag --&gt;

	&lt;header&gt; &lt;!-- Defining the header section of the page with the appropriate tag --&gt;

		&lt;h1&gt;Your Logo&lt;/h1&gt;

		&lt;h3&gt;and a fancy slogan&lt;/h3&gt;

		&lt;nav class="clear"&gt; &lt;!-- The nav link semantically marks your main site navigation --&gt;

			&lt;ul&gt;

				&lt;li&gt;&lt;a href="#article1"&gt;Photoshoot&lt;/a&gt;&lt;/li&gt;
				&lt;li&gt;&lt;a href="#article2"&gt;Sweet Tabs&lt;/a&gt;&lt;/li&gt;
				&lt;li&gt;&lt;a href="#article3"&gt;Navigation Menu&lt;/a&gt;&lt;/li&gt;

			&lt;/ul&gt;

		&lt;/nav&gt;

	&lt;/header&gt;</pre>
<p>Here we use the new section tags, which divide your page into separate semantic sections. Outermost is the <strong>#page section</strong> which is set to a width of <strong>960px</strong> in the style sheet (a fairly standard width with older computer displays in mind). After this comes the header tag and the navigation tag.</p>
<p>Notice the <strong>href</strong> attributes of the links – the part after the hash symbol <strong>#</strong> corresponds to the <strong>ID</strong> of the <strong>article</strong> we want to scroll to.</p>
<h4>template.html – Article</h4>
<pre>	&lt;!-- Article 1 start --&gt;

	&lt;div class="line"&gt;&lt;/div&gt;  &lt;!-- Dividing line --&gt;

	&lt;article id="article1"&gt; &lt;!-- The new article tag. The id is supplied so it can be scrolled into view. --&gt;

		&lt;h2&gt;Photoshoot Effect&lt;/h2&gt;

		&lt;div class="line"&gt;&lt;/div&gt;

		&lt;div class="articleBody clear"&gt;

			&lt;figure&gt; &lt;!-- The figure tag marks data (usually an image) that is part of the article --&gt;

				&lt;a href="http://tutorialzine.com/2010/02/photo-shoot-css-jquery/"&gt;
					&lt;img src="http://tutorialzine.com/img/featured/641.jpg" width="620" height="340" /&gt;&lt;/a&gt;

			&lt;/figure&gt;

			&lt;p&gt;In this tutorial, we are creating a photo shoot effect with our just-released PhotoShoot jQuery plug-in. With it you can convert a regular div on the page into a photo shooting stage simulating a camera-like feel.&lt;/p&gt;

			&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer luctus quam quis .... &lt;/p&gt;

		&lt;/div&gt;

	&lt;/article&gt;

	&lt;!-- Article 1 end --&gt;</pre>
<p>The markup above is shared between all of the articles. First is the dividing line (the best solution semantically would be an <strong>&lt;hr&gt;</strong> line, which in HTML5 has the added role of a logical diving element, but unfortunately it is impossible to style in a cross-browser fashion, so we will stick with a <strong>DIV</strong>). After this we have the new <strong>article</strong> tag, with a <strong>unique ID</strong>, which is used by the navigation to<strong> scroll the page</strong>.</p>
<p>Inside we have the title of the article, two paragraphs and the new figure tag, which marks the use of images in the article.</p>
<h4>template.html – Footer</h4>
<pre>		&lt;footer&gt; &lt;!-- Marking the footer section --&gt;

			&lt;div class="line"&gt;&lt;/div&gt;

			&lt;p&gt;Copyright 2010 - YourSite.com&lt;/p&gt; &lt;!-- Change the copyright notice --&gt;
			&lt;a href="#" class="up"&gt;Go UP&lt;/a&gt;
			&lt;a href="http://tutorialzine.com/" class="by"&gt;Template by Tutorialzine&lt;/a&gt;

		&lt;/footer&gt;

	&lt;/section&gt; &lt;!-- Closing the #page section --&gt;

	&lt;!-- JavaScript Includes --&gt;

	&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
	&lt;script src="jquery.scrollTo-1.4.2/jquery.scrollTo-min.js"&gt;&lt;/script&gt;
	&lt;script src="script.js"&gt;&lt;/script&gt;

	&lt;/body&gt;

&lt;/html&gt;</pre>
<p>Lastly, we have the <strong>footer</strong> tag, which does exactly what you expect it to do. At the bottom of the page are the rest of the JavaScript  includes, which add the <strong>jQuery library</strong> and the <strong>scrollTo</strong> plug-in, which we are going to use in the next steps.</p>
<div><a href="http://tutorialzine.com/wp-content/uploads/2010/02/i2.png"><img class="size-full wp-image-673" src="http://tutorialzine.com/wp-content/uploads/2010/02/i2.png" alt="HTML5 CSS3 Website Template" width="620" height="460" /></a>An HTML5 &amp; CSS3 Website Template</div>
<h3>Step 3 – CSS</h3>
<p>As we are using HTML5, we have to take some extra measures with the styling. The tags that this new version of HTML introduces, are not yet provided with a default styling. This is however easily fixed with a couple of lines of CSS code and the page works and looks as it is supposed to:</p>
<h4>styles.css – Part 1</h4>
<pre>header,footer,
article,section,
hgroup,nav,
figure{
	/* Giving a display value to the HTML5 rendered elements: */
	display:block;
}

article .line{
	/* The dividing line inside of the article is darker: */
	background-color:#15242a;
	border-bottom-color:#204656;
	margin:1.3em 0;
}

footer .line{
	margin:2em 0;
}

nav{
	background:url(img/gradient_light.jpg) repeat-x 50% 50% #f8f8f8;
	padding:0 5px;
	position:absolute;
	right:0;
	top:4em;

	border:1px solid #FCFCFC;

	-moz-box-shadow:0 1px 1px #333333;
	-webkit-box-shadow:0 1px 1px #333333;
	box-shadow:0 1px 1px #333333;
}

nav ul li{
	display:inline;
}

nav ul li a,
nav ul li a:visited{
	color:#565656;
	display:block;
	float:left;
	font-size:1.25em;
	font-weight:bold;
	margin:5px 2px;
	padding:7px 10px 4px;
	text-shadow:0 1px 1px white;
	text-transform:uppercase;
}

nav ul li a:hover{
	text-decoration:none;
	background-color:#f0f0f0;
}

nav, article, nav ul li a,figure{
	/* Applying CSS3 rounded corners: */
	-moz-border-radius:10px;
	-webkit-border-radius:10px;
	border-radius:10px;
}</pre>
<p>We basically need to set the <strong>display</strong> value of the new tags to <strong>block</strong>, as you can see from the first couple of lines. After this we can style them as we would with regular divs.</p>
<p>We style the horizontal lines, the articles and the navigation buttons, with the latter organized as an unordered list inside of the <strong>nav</strong> tag. At the bottom we assign the border-radius property for four different types of elements of once, which saves a lot of code.</p>
<h4>styles.css – Part 2</h4>
<pre>/* Article styles: */

#page{
	width:960px;
	margin:0 auto;
	position:relative;
}

article{
	background-color:#213E4A;
	margin:3em 0;
	padding:20px;

	text-shadow:0 2px 0 black;
}

figure{
	border:3px solid #142830;
	float:right;
	height:300px;
	margin-left:15px;
	overflow:hidden;
	width:500px;
}

figure:hover{
	-moz-box-shadow:0 0 2px #4D7788;
	-webkit-box-shadow:0 0 2px #4D7788;
	box-shadow:0 0 2px #4D7788;
}

figure img{
	margin-left:-60px;
}

/* Footer styling: */

footer{
	margin-bottom:30px;
	text-align:center;
	font-size:0.825em;
}

footer p{
	margin-bottom:-2.5em;
	position:relative;
}

footer a,footer a:visited{
	color:#cccccc;
	background-color:#213e4a;
	display:block;
	padding:2px 4px;
	z-index:100;
	position:relative;
}

footer a:hover{
	text-decoration:none;
	background-color:#142830;
}

footer a.by{
	float:left;

}

footer a.up{
	float:right;
}</pre>
<p>In the second part we apply more detailed styling to the elements. A width for the page section, a hover property for the figure tag and styles for the links inside of the footer. There are also a few styles that are not included here, but you can see them in <strong>styles.css</strong>.</p>
<p>Now lets continue with the next step.</p>
<div><a href="http://tutorialzine.com/wp-content/uploads/2010/02/i3.png"><img class="size-full wp-image-674" src="http://tutorialzine.com/wp-content/uploads/2010/02/i3.png" alt="Structure Of The Page" width="620" height="460" /></a>Structure Of The Page &#8211; HTML5 Tags</div>
<h3>Step 4 – jQuery</h3>
<p>To enhance the template, we will create a smooth scrolling effect once a navigation link has been clicked using the <strong>scrollTo</strong> jQuery plug-in we included in the page earlier. To make it work we just need to loop through the links in the navigation bar (and the UP link in the footer) and assign an onclick event which will trigger the <strong>$.srollTo()</strong> function.</p>
<h4>script.js</h4>
<pre>$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */

	$('nav a,footer a.up').click(function(e){

		// If a link has been clicked, scroll the page to the link's hash target:

		$.scrollTo( this.hash || 0, 1500);
		e.preventDefault();
	});

});</pre>
<p><strong><em>With this our template is complete!</em></strong></p>
<h3>Wrapping it up</h3>
<p>In this tutorial we leveraged the new semantic features provided by HTML5 to design and code a one-page web template. You can use it for free both personally and commercially, providing you leave the back link intact.</p>
<p><img src="http://feeds.feedburner.com/~r/Tutorialzine/~4/y7bBsejKDeM" alt="" width="1" height="1" /></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/avi/" title="avi" rel="tag">avi</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/css3/" title="css3" rel="tag">css3</a>, <a href="http://xguiden.dk/tag/design/" title="design" rel="tag">design</a>, <a href="http://xguiden.dk/tag/doctype/" title="DOCTYPE" rel="tag">DOCTYPE</a>, <a href="http://xguiden.dk/tag/fil/" title="fil" rel="tag">fil</a>, <a href="http://xguiden.dk/tag/fix/" title="fix" rel="tag">fix</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/gradient/" title="Gradient" rel="tag">Gradient</a>, <a href="http://xguiden.dk/tag/header/" title="Header" rel="tag">Header</a>, <a href="http://xguiden.dk/tag/html/" title="HTML" rel="tag">HTML</a>, <a href="http://xguiden.dk/tag/html5/" title="html5" rel="tag">html5</a>, <a href="http://xguiden.dk/tag/image/" title="image" rel="tag">image</a>, <a href="http://xguiden.dk/tag/images/" title="images" rel="tag">images</a>, <a href="http://xguiden.dk/tag/internet/" title="internet" rel="tag">internet</a>, <a href="http://xguiden.dk/tag/internet-explorer/" title="Internet Explorer" rel="tag">Internet Explorer</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/meta/" title="META" rel="tag">META</a>, <a href="http://xguiden.dk/tag/over/" title="Over" rel="tag">Over</a>, <a href="http://xguiden.dk/tag/photoshop/" title="Photoshop" rel="tag">Photoshop</a>, <a href="http://xguiden.dk/tag/png/" title="png" rel="tag">png</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/standard/" title="standard" rel="tag">standard</a>, <a href="http://xguiden.dk/tag/start/" title="Start" rel="tag">Start</a>, <a href="http://xguiden.dk/tag/table/" title="table" rel="tag">table</a>, <a href="http://xguiden.dk/tag/tag/" title="tag" rel="tag">tag</a>, <a href="http://xguiden.dk/tag/tags/" title="tags" rel="tag">tags</a>, <a href="http://xguiden.dk/tag/text/" title="text" rel="tag">text</a>, <a href="http://xguiden.dk/tag/tutorial/" title="tutorial" rel="tag">tutorial</a>, <a href="http://xguiden.dk/tag/url/" title="URL" rel="tag">URL</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/" title="How to Code up a Web Design from PSD to HTML (15/02/2010)">How to Code up a Web Design from PSD to HTML</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/08/design-and-code-a-cool-iphone-app-website-in-html5/" title="Design and Code a Cool iPhone App Website in HTML5 (08/03/2010)">Design and Code a Cool iPhone App Website in HTML5</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/03/how-we%e2%80%99ll-be-building-websites-in-5-years-html5-and-css3-layout/" title="How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout (03/03/2010)">How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/personal-vcard-pt-2/" title="Personal vCard Pt.2 (13/02/2010)">Personal vCard Pt.2</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/03/design-a-prettier-web-form-with-css-3/" title="Design a Prettier Web Form with CSS 3 (03/03/2010)">Design a Prettier Web Form with CSS 3</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/18/coding-a-css3-html5-one-page-website-template/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Make your MooTools Code Shorter, Faster, and Stronger</title>
		<link>http://xguiden.dk/2010/02/18/make-your-mootools-code-shorter-faster-and-stronger/</link>
		<comments>http://xguiden.dk/2010/02/18/make-your-mootools-code-shorter-faster-and-stronger/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 11:09:12 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[avi]]></category>
		<category><![CDATA[counter]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[Gitter]]></category>
		<category><![CDATA[Header]]></category>
		<category><![CDATA[help]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[input]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[Internet Explorer]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[iso]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[LP]]></category>
		<category><![CDATA[Mod]]></category>
		<category><![CDATA[Mount]]></category>
		<category><![CDATA[Outline]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[rewrite]]></category>
		<category><![CDATA[Sand]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Source]]></category>
		<category><![CDATA[standard]]></category>
		<category><![CDATA[Start]]></category>
		<category><![CDATA[Sten]]></category>
		<category><![CDATA[switch]]></category>
		<category><![CDATA[system]]></category>
		<category><![CDATA[table]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[Tweening]]></category>
		<category><![CDATA[URL]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=5142</guid>
		<description><![CDATA[MooTools is one of the most flexible, modular, and well written JavaScript frameworks available. So many people use it but many of them don’t optimize their code. This post will provide you with fifteen simple tips for making your MooTools code shorter, faster, and stronger.
 
1. Create Your Own MooTools Build or Pull From Google AJAX [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://mootools.net/">MooTools</a> is one of the most flexible, modular, and well written JavaScript frameworks available. So many people use it but many of them don’t optimize their code. This post will provide you with fifteen simple tips for making your MooTools code shorter, faster, and stronger.</p>
<p><span> </span></p>
<h3>1. Create Your Own MooTools Build or Pull From Google AJAX Libraries</h3>
<p>One of the great advantages to using MooTools is that it’s incredibly modular. What does that mean?<br />
Almost nothing is required unless you need it. The advantage of MooTools’ modularity is that your<br />
limited, custom MooTools build can keep your JavaScript load time short.</p>
<p><img src="http://net.tutsplus.com/builder.jpg" alt="MooTools Core Builder" /></p>
<p>Want to create a custom MooTools build for your next project? Follow these steps:</p>
<ul>
<li>Go to <a href="http://mootools.net/core">http://mootools.net/core</a> (and/or <a href="http://mootools.net/more">http://mootools.net/more</a> if you’d like additional plugins)</li>
<li>Select the plugins of your choosing. Don’t worry about accounting for dependencies — the plugin builder does that for you!</li>
<li>Select the compression option of your choosing — the YUI Compressor will provide the you with the smallest possible build of MooTools</li>
</ul>
<p>That’s it! Sometimes, however, your project requires the entire MooTools Core library. In that case, your website can save itself thousands<br />
of requests per day by using the Google AJAX Libraries complete build of MooTools. You may do this two ways:</p>
<pre>&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js"&gt;&lt;/script&gt;</pre>
<p>This first method simply includes MooTools into the page per normal. The second method allows more functionality and performance:</p>
<pre>&lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
google.load("mootools", "1.2.4"); //older versions also available
&lt;/script&gt;</pre>
<p>What’s great about using the Google AJAX Libraries API is that if another website uses the AJAX Library API, that version of MooTools is already cached<br />
within their browser and the site will load faster!</p>
<h3>2. Use jQuery and MooTools Together</h3>
<p>While it’s best to stick to one library in a given page to avoid a bunch of overhead, sometimes you can’t avoid needing multiple frameworks.<br />
Luckily MooTools can coexist with any non-prototype-based JavaScript frameworks. Here’s how you can use jQuery and MooTools in the same page:</p>
<pre>&lt;!-- jquery gets the "$" method --&gt;
&lt;script type="text/javascript" src="jquery-1.4.js" /&gt;
&lt;!-- mootools doesn't steal the "$" method; instead, document.id will be used --&gt;
&lt;script type="text/javascript" src="mootools.js" /&gt;
&lt;!-- lets use them --&gt;
&lt;script type="text/javascript"&gt;
//with jquery, grab all links, make then red
$('a').css('color','red');
//with mootools, get the content div, set it's background color to pink
document.id('content').setStyle('background','pink');
//with mootools, get the content div, set it's background color to pink
//this time, we'll give mootools the "$" method
(function($) {
	$('content').setStyle('background','pink');
})(document.id);
&lt;/script&gt;</pre>
<p>Thanks to <a href="http://mootools.net/blog/2009/06/22/the-dollar-safe-mode/">MooTools’ Dollar Safe Mode</a>, MooTools no longer assumes the “$” method if it’s already taken!</p>
<h3>3. Save Elements and Element Collections</h3>
<p>Developers often need to collect one element or a collection of elements. For example, you may need to grab all A elements within the page, change their color, and create tooltips from them.</p>
<pre>//grab links, change color */
$$('#footer a').setStyle('color','#f00');
//make links tooltips
var tippers = new Tips($$('#footer a'));</pre>
<p>The code above is grossly inefficient. Why query the DOM twice (with $$) if you can collect all of the elements once? Let’s make this more efficient:</p>
<pre>//"save" links into a variable
var links = $$('#footer a');
//grab links, change color */
links.setStyle('color','#f00');
//make links tooltips
var tippers = new Tips(links);</pre>
<p>You could make this even shorter, but it’s not as readable:</p>
<pre>var tippers = new Tips($$('#footer a').setStyle('color','#f00'));</pre>
<p>Readability is important, so I wouldn’t recommend coding this way if you work with a team.</p>
<h3>4. Use Element Methods on Element Collections</h3>
<p>Cycling through an array of elements is not unique to any JavaScript framework:</p>
<pre>//for every link...
$$('a').each(function(a) {
	//add link nudging to the element
	a.addEvents({
		mouseenter: function() { //animate to the right
			if(!a.retrieve('oPad')) { a.store('oPad',a.getStyle('padding-left')); }
			a.tween('padding-left',30);
		},
		mouseleave: function() { //animate back to the left
			a.tween('padding-left',a.retrieve('oPad'));
		}
	});
});</pre>
<p>What many developers aren’t aware that Element collections have the same methods as Elements,<br />
so there’s no need to cycle through them — simply apply the desired functionality to the collection:</p>
<pre>$$('a').addEvents({
	mouseenter: function() { //animate to the right
		if(!this.retrieve('oPad')) { this.store('oPad',this.getStyle('padding-left')); }
		this.tween('padding-left',30);
	},
	mouseleave: function() { //animate back to the left
		this.tween('padding-left',this.retrieve('oPad'));
	}
});</pre>
<p>Note that the “this” keyword is used to reference the “current” element within the collection, not the collection itself.</p>
<h3>5. Use MooTools Alias</h3>
<p>MooTools’ “alias” method allows you to rename or alias an existing method. Take the following snippet of code which is currently in the MooTools Core source:</p>
<pre>Array.alias('forEach', 'each');</pre>
<p>The above code lets you call the “each” method instead of “forEach”. Using “each” is more readable, a quiet standard between most JavaScript frameworks, and<br />
it even saves you a few bytes in your code. If you prefer to give MooTools’ Native or Class methods a custom name, feel free to!</p>
<p>For example, the Element Class’ method for removing an Element form the DOM is:</p>
<pre>$('myElement').dispose();</pre>
<p>Suppose your web app is about a given topic and you’d like to stay within that terminology for your code. Here are a few examples:</p>
<pre>Element.alias('dispose','can'); //career site?
Element.alias('dispose','shank'); //prison site?</pre>
<p>Whatever your reasons are for calling a method by a different name, just don’t be afraid to do so!</p>
<h3>6. Create Custom Pseudo Selectors</h3>
<p>Accessing a collection of Elements in the DOM is a core responsibility of any JavaScript framework. Unfortunately it can also be taxing and<br />
the pseudo selectors you want aren’t always available. Luckily MooTools allows you to easily implement your own pseudo selectors! Let’s<br />
create a pseudo selector named “disabled” that returns an element if it’s disabled.</p>
<pre>//grab disabled elements
Selectors.Pseudo.disabled = function() {
	return this.disabled;
}

//how you use it
var disabledInputs = $$('input:disabled');</pre>
<p>Simply add your selector to the Selectors.Pseudo object. If the new pseudo’s function returns “true”, the element is a match and will be returned.</p>
<p>Defining you own pseudo selectors is a great way to take control of your selectors!</p>
<h3>7. Implement Methods on Existing Objects</h3>
<p>MooTools’ philosophy is that it’s acceptable, even encouraged, to modify Native (String, Function, Number, etc.) prototypes when needed.<br />
Implementing new methods on these Natives will empower them even more. Let’s create a String method that will turn any string of text into<br />
“tweet” format (add links for @reply’s, links, etc.):</p>
<pre>String.implement({
	toTweet: function() {
		 return this.replace(/(https?:\/\/\S+)/gi,'&lt;a href="$1"&gt;$1&lt;/a&gt;').replace(/(^|\s)@(\w+)/g,'$1&lt;a href="http://twitter.com/$2"&gt;@$2&lt;/a&gt;').replace(/(^|\s)#(\w+)/g,'$1&lt;a href="http://search.twitter.com/search?q=%23$2"&gt;#$2&lt;/a&gt;');
	}
});</pre>
<p>Now you can call “toTweet” on any string and you’ll get the string back as a “tweet”. Here are a few examples:</p>
<pre>//set an element's html to a tweet value
var el = $('myElement');
el.set('html',el.get('html').toTweet()); //sets the element's html to a linked, tweet value.

//alert the tweeted value
alert('Yo @NetTuts, check out my #MooTools website: http://davidwalsh.name'.toTweet());
//alerts:  Yo &lt;a href="http://twitter.com/nettuts"&gt;@NetTuts&lt;/a&gt;, check out my &lt;a href="http://search.twitter.com/search?q=%23MooTools"&gt;MooTools&lt;/a&gt; website: &lt;a href="http://davidwalsh.name"&gt;http://davidwalsh.name&lt;/a&gt;</pre>
<p>Implementing custom methods on Objects strengthens every existing and future instance of that object.</p>
<h3>8. Extend Existing Classes</h3>
<p>MooTools’ OOP philosophy allows for a super-powerful inheritance model. Extending existing classes<br />
allows you to avoid repeating code, empower existing objects, and leverage existing functionality.<br />
MooTools Core, More, and your custom classes extend existing functionality. Consider the Request class:</p>
<pre>var Request = new Class({

	Implements: [Chain, Events, Options],

	options: {/*
		onRequest: $empty,
		onComplete: $empty,
		onCancel: $empty,
		onSuccess: $empty,
		onFailure: $empty,
		onException: $empty,*/
		url: '',
		data: '',
		headers: {
			'X-Requested-With': 'XMLHttpRequest',
			'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
		},
		async: true,
		format: false,
		method: 'post',
		link: 'ignore',
		isSuccess: null,
		emulation: true,
		urlEncoded: true,
		encoding: 'utf-8',
		evalScripts: false,
		evalResponse: false,
		noCache: false
	},

	initialize: function(options){
		this.xhr = new Browser.Request();
		this.setOptions(options);
		this.options.isSuccess = this.options.isSuccess || this.isSuccess;
		this.headers = new Hash(this.options.headers);
	},

	onStateChange: function(){
		if (this.xhr.readyState != 4 || !this.running) return;
		this.running = false;
		this.status = 0;
		$try(function(){
			this.status = this.xhr.status;
		}.bind(this));
		this.xhr.onreadystatechange = $empty;
		if (this.options.isSuccess.call(this, this.status)){
			this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML};
			this.success(this.response.text, this.response.xml);
		} else {
			this.response = {text: null, xml: null};
			this.failure();
		}
	},

	isSuccess: function(){
		return ((this.status &gt;= 200) &amp;&amp; (this.status &lt; 300));
	},

	processScripts: function(text){
		if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text);
		return text.stripScripts(this.options.evalScripts);
	},

	success: function(text, xml){
		this.onSuccess(this.processScripts(text), xml);
	},

	onSuccess: function(){
		this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
	},

	failure: function(){
		this.onFailure();
	},

	onFailure: function(){
		this.fireEvent('complete').fireEvent('failure', this.xhr);
	},

	setHeader: function(name, value){
		this.headers.set(name, value);
		return this;
	},

	getHeader: function(name){
		return $try(function(){
			return this.xhr.getResponseHeader(name);
		}.bind(this));
	},

	check: function(){
		if (!this.running) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
		}
		return false;
	},

	send: function(options){
		if (!this.check(options)) return this;
		this.running = true;

		var type = $type(options);
		if (type == 'string' || type == 'element') options = {data: options};

		var old = this.options;
		options = $extend({data: old.data, url: old.url, method: old.method}, options);
		var data = options.data, url = String(options.url), method = options.method.toLowerCase();

		switch ($type(data)){
			case 'element': data = document.id(data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(data);
		}

		if (this.options.format){
			var format = 'format=' + this.options.format;
			data = (data) ? format + '&amp;' + data : format;
		}

		if (this.options.emulation &amp;&amp; !['get', 'post'].contains(method)){
			var _method = '_method=' + method;
			data = (data) ? _method + '&amp;' + data : _method;
			method = 'post';
		}

		if (this.options.urlEncoded &amp;&amp; method == 'post'){
			var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
			this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding);
		}

		if (this.options.noCache){
			var noCache = 'noCache=' + new Date().getTime();
			data = (data) ? noCache + '&amp;' + data : noCache;
		}

		var trimPosition = url.lastIndexOf('/');
		if (trimPosition &gt; -1 &amp;&amp; (trimPosition = url.indexOf('#')) &gt; -1) url = url.substr(0, trimPosition);

		if (data &amp;&amp; method == 'get'){
			url = url + (url.contains('?') ? '&amp;' : '?') + data;
			data = null;
		}

		this.xhr.open(method.toUpperCase(), url, this.options.async);

		this.xhr.onreadystatechange = this.onStateChange.bind(this);

		this.headers.each(function(value, key){
			try {
				this.xhr.setRequestHeader(key, value);
			} catch (e){
				this.fireEvent('exception', [key, value]);
			}
		}, this);

		this.fireEvent('request');
		this.xhr.send(data);
		if (!this.options.async) this.onStateChange();
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.xhr.abort();
		this.xhr.onreadystatechange = $empty;
		this.xhr = new Browser.Request();
		this.fireEvent('cancel');
		return this;
	}

});</pre>
<p>Then consider Request.JSONP, which extends Request:</p>
<pre>Request.JSON = new Class({

	Extends: Request,

	options: {
		secure: true
	},

	initialize: function(options){
		this.parent(options);
		this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
	},

	success: function(text){
		this.response.json = JSON.decode(text, this.options.secure);
		this.onSuccess(this.response.json, text);
	}

});</pre>
<p>You see how small the Request.JSONP class is? By adding “Extends: Request”, the Request.JSONP class gets all<br />
of the Request Class’ methods. Essentially, this small snippet of code becomes a powerhouse because it extends<br />
Request. You can even add extensions to extensions. Now consider Request.JSONP and then <a href="http://net.tutsplus.com">Scott Kyle’s</a> Request.Twitter<br />
class:</p>
<pre>//Request.JSONP
/*
---

script: Request.JSONP.js

description: Defines Request.JSONP, a class for cross domain JavaScript via script injection.

license: MIT-style license

authors:
- Aaron Newton
- Guillermo Rauch

requires:
- core:1.2.4/Element
- core:1.2.4/Request
- /Log

provides: [Request.JSONP]

...
*/

Request.JSONP = new Class({

	Implements: [Chain, Events, Options, Log],

	options: {/*
		onRetry: $empty(intRetries),
		onRequest: $empty(scriptElement),
		onComplete: $empty(data),
		onSuccess: $empty(data),
		onCancel: $empty(),
		log: false,
		*/
		url: '',
		data: {},
		retries: 0,
		timeout: 0,
		link: 'ignore',
		callbackKey: 'callback',
		injectScript: document.head
	},

	initialize: function(options){
		this.setOptions(options);
		if (this.options.log) this.enableLog();
		this.running = false;
		this.requests = 0;
		this.triesRemaining = [];
	},

	check: function(){
		if (!this.running) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
		}
		return false;
	},

	send: function(options){
		if (!$chk(arguments[1]) &amp;&amp; !this.check(options)) return this;

		var type = $type(options),
				old = this.options,
				index = $chk(arguments[1]) ? arguments[1] : this.requests++;
		if (type == 'string' || type == 'element') options = {data: options};

		options = $extend({data: old.data, url: old.url}, options);

		if (!$chk(this.triesRemaining[index])) this.triesRemaining[index] = this.options.retries;
		var remaining = this.triesRemaining[index];

		(function(){
			var script = this.getScript(options);
			this.log('JSONP retrieving script with url: ' + script.get('src'));
			this.fireEvent('request', script);
			this.running = true;

			(function(){
				if (remaining){
					this.triesRemaining[index] = remaining - 1;
					if (script){
						script.destroy();
						this.send(options, index).fireEvent('retry', this.triesRemaining[index]);
					}
				} else if(script &amp;&amp; this.options.timeout){
					script.destroy();
					this.cancel().fireEvent('failure');
				}
			}).delay(this.options.timeout, this);
		}).delay(Browser.Engine.trident ? 50 : 0, this);
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.fireEvent('cancel');
		return this;
	},

	getScript: function(options){
		var index = Request.JSONP.counter,
				data;
		Request.JSONP.counter++;

		switch ($type(options.data)){
			case 'element': data = document.id(options.data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(options.data);
		}

		var src = options.url +
			 (options.url.test('\\?') ? '&amp;' :'?') +
			 (options.callbackKey || this.options.callbackKey) +
			 '=Request.JSONP.request_map.request_'+ index +
			 (data ? '&amp;' + data : '');
		if (src.length &gt; 2083) this.log('JSONP '+ src +' will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs');

		var script = new Element('script', {type: 'text/javascript', src: src});
		Request.JSONP.request_map['request_' + index] = function(){ this.success(arguments, script); }.bind(this);
		return script.inject(this.options.injectScript);
	},

	success: function(args, script){
		if (script) script.destroy();
		this.running = false;
		this.log('JSONP successfully retrieved: ', args);
		this.fireEvent('complete', args).fireEvent('success', args).callChain();
	}

});

Request.JSONP.counter = 0;
Request.JSONP.request_map = {};</pre>
<p>…and now Request.Twitter:</p>
<pre>Request.Twitter = new Class({

	Extends: Request.JSONP,

	options: {
	  linkify: true,
	  url: 'http://twitter.com/statuses/user_timeline/{term}.json',
	  data: {
	    count: 5
	  }
	},

	initialize: function(term, options){
	  this.parent(options);
	  this.options.url = this.options.url.substitute({term: term});
	},

	success: function(data, script){
	  if (this.options.linkify) data.each(function(tweet){
	    tweet.text = this.linkify(tweet.text);
	  }, this);

	  // keep subsequent calls newer
	  if (data[0]) this.options.data.since_id = data[0].id;

	  this.parent(data, script);
	},

	linkify: function(text){
	  // modified from TwitterGitter by David Walsh (davidwalsh.name)
	  // courtesy of Jeremy Parrish (rrish.org)
	  return text.replace(/(https?:\/\/[\w\-:;?&amp;=+.%#\/]+)/gi, '&lt;a href="$1"&gt;$1&lt;/a&gt;')
	             .replace(/(^|\W)@(\w+)/g, '$1&lt;a href="http://twitter.com/$2"&gt;@$2&lt;/a&gt;')
	             .replace(/(^|\W)#(\w+)/g, '$1#&lt;a href="http://search.twitter.com/search?q=%23$2"&gt;$2&lt;/a&gt;');
	}

});</pre>
<p>You see how a waterfall effect of extending objects can make the smallest of classes an absolute beast of a class?<br />
Experiment with MooTools’ inheritance model and don’t repeat code!</p>
<h3>9. Create Custom Events</h3>
<p>I’ve already explained how flexible the MooTools selector engine is, the class system is, and how modular the framework is.<br />
Why would you expect anything different from MooTools’ event system? Creating custom events within MooTools is as simple<br />
as it gets. Here’s a basic outline of your MooTools custom event:</p>
<pre>Element.Events.altClick = {
	base: 'click', //the "base" event
	condition: function(event) {
		return event.alt; // alt key?
	},
	onAdd: function() {
		//do something when the event is added
	},
	onRemove: function() {
		//do something when the event is removed
	}
};</pre>
<p>Here’s a great example of a custom event — listening for “alt” and “click” at the same time:</p>
<pre>//alt click
Element.Events.altClick = {
	base: 'click',
	condition: function(event) {
		return event.alt; // alt key?
	}
};

//usage
$(document.body).addEvent('altClick',function() {
	alert('You alt-clicked me!');
});</pre>
<p>Or you can simply define a custom event so that a specific function executes any time that type of event is assigned.<br />
In my next example, any time a click event is assigned to an element, that element’s cursor will be automatically changed<br />
to the “pointer” cursor.</p>
<pre>/* update cursor on add/remove click event */
Element.Events.click = {
	base:'click',
	onAdd: function() {
		if(this.setStyle) {
			this.store('original-cursor',this.getStyle('cursor'));
			this.setStyle('cursor','pointer');
		}
	},
	onRemove: function() {
		if(this.setStyle) {
			this.setStyle('cursor',this.retrieve('original-cursor'));
		}
	}
};</pre>
<p>You’ll notice that if the click event is removed, the original cursor will be restored.</p>
<h3>10. jQuery-Style Events</h3>
<p>While the MooTools event sytax is different from jQuery’s, it doesn’t have to be! With a minimal amount of<br />
javascript you can make MooTools’ event syntax reflect jQuery’s.</p>
<p>MooTools holds all of its events in the Element.NativeElements object:</p>
<pre>Element.NativeEvents = {
	click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
	mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
	mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
	keydown: 2, keypress: 2, keyup: 2, //keyboard
	focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements
	load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
	error: 1, abort: 1, scroll: 1 //misc
};</pre>
<p>Essentially all you need to do is cycle through each element type and implement a method on the Element class, named like the event type,<br />
that simulates what addEvent does:</p>
<pre>//hash the element.natives so you can do stuff with it
var hash = new Hash(Element.NativeEvents);
//remove items that need to be replaced, add their replacements
hash.erase('mouseover').erase('mouseout').erase('DOMMouseScroll');
hash.include('mouseenter',1).include('mouseleave',1);
//initialize this
var eventHash = new Hash({});
//for every event type, add to the hash
hash.getKeys().each(function(event){
	eventHash[event] = function(fn) {
		this.addEvent(event,fn);
		return this;
	};
});
//make it happen
Element.implement(eventHash);</pre>
<p>Now you can listen for events like:</p>
<pre>$('myElement').click(function() {
	//do stuff
});</pre>
<h3>11. Add Events During Element Creation</h3>
<p>If you have experience coding with MooTools, at some point you’ve no doubt created an element and subsequently added events to it:</p>
<pre>var myElement = new Element('a',{
	href: 'mypage.php',
	text: 'Click here!'
});

myElement.addEvent('click',function(e) {
	//stop the event
	if(e) e.stop();
	//do stuff
});</pre>
<p>There’s nothing wrong with the above, per say, but you could just add those events during element creation:</p>
<pre>var myElement = new Element('a',{
	href: 'mypage.php',
	text: 'Click here!',
	events: {
		click: function() {
			//stop the event
			if(e) e.stop();
			//do stuff
		}
	}
});</pre>
<h3>12. Implement Events Within Classes</h3>
<p>Extending classes was discussed in tip #8 above. Now lets explore the *implement* functionality within MooTools classes.<br />
What’s the difference? MooTools contributor Mark Obcena says it best in his article titled<br />
<a href="http://keetology.com/blog/2009/10/27/up-the-moo-herd-iv-theres-a-class-for-this">Up The Moo Herd IV: There’s A Class For This</a>:</p>
<blockquote><p>MooTools has two built-in mutators: Extends and Implements. The Extends mutator takes the class name passed on to it and makes the new class inherit directly from it, while Implements takes the class (or classes) passed and adds their methods to the new class (or mixes them in—thus mixin).</p></blockquote>
<p>With the difference between extending and implementing, lets get back to it. Implementing events within your MooTools classes<br />
can make your classes much more flexible. Consider the following simple Overlay class:</p>
<pre>var Overlay = new Class({

	Implements: [Options,Events],

	options:  {
		id: 'overlay',
		color: '#000',
		duration: 500,
		opacity: 0.5,
		zIndex: 5000
	},

	initialize: function(container,options) {
		this.setOptions(options);
		this.container = document.id(container);
		this.overlay = new Element('div',{
			id: this.options.id,
			opacity: 0,
			styles: {
				position: 'absolute',
				background: this.options.color,
				left: 0,
				top: 0,
				'z-index': this.options.zIndex
			},
		}).inject(this.container);
		this.tween = new Fx.Tween(this.overlay,{
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onStart: function() {
				this.overlay.setStyles({
					width: '100%',
					height: this.container.getScrollSize().y
				});
			}.bind(this)
		});
	},
	open: function() {
		this.tween.start(this.options.opacity);
		return this;
	},
	close: function() {
		this.tween.start(0);
		return this;
	}
});</pre>
<p>Sure the class does what it’s supposed to but it isn’t nearly as flexible it could be. Now lets implement<br />
onClick, onClose, onHide, onOpen, and onShow events:</p>
<pre>var Overlay = new Class({

	Implements: [Options,Events],  // EVENTS IMPLEMENTED HERE!

	options:  {
		id: 'overlay',
		color: '#000',
		duration: 500,
		opacity: 0.5,
		zIndex: 5000/*,
		onClick: $empty,
		onClose: $empty,
		onHide: $empty,
		onOpen: $empty,
		onShow: $empty
		*/
	},

	initialize: function(container,options) {
		this.setOptions(options);
		this.container = document.id(container);
		this.overlay = new Element('div',{
			id: this.options.id,
			opacity: 0,
			styles: {
				position: 'absolute',
				background: this.options.color,
				left: 0,
				top: 0,
				'z-index': this.options.zIndex
			},
			events: {
				click: function() {    // CLICK EVENT
					this.fireEvent('click');
				}.bind(this)
			}
		}).inject(this.container);
		this.tween = new Fx.Tween(this.overlay,{
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onStart: function() {
				this.overlay.setStyles({
					width: '100%',
					height: this.container.getScrollSize().y
				});
			}.bind(this),
			onComplete: function() {
				this.fireEvent(this.overlay.get('opacity') == this.options.opacity ? 'show' : 'hide');  // SHOW OR HIDE EVENT
			}.bind(this)
		});
	},
	open: function() {
		this.fireEvent('open');  // OPEN EVENT
		this.tween.start(this.options.opacity);
		return this;
	},
	close: function() {
		this.fireEvent('close');  // CLOSE EVENT
		this.tween.start(0);
		return this;
	}
});</pre>
<p>What’s great about adding events to a class is that events allow your to give more options and trigger functionality when<br />
our class methods execute. In the above example, you can execute any functionality when the overlay opens, closes, shows, hides, or gets clicked.<br />
Essentially you added two tiny snippets of code to the class:</p>
<pre>Implements: [Events]</pre>
<p>…and the following wherever you’d like an event to be signaled…</p>
<pre>this.fireEvent('someEvent',[argument1, argument2]);</pre>
<p>So how can you control these events when you create an instance of the class? Add them in the options like this:</p>
<pre>var overlay = new Overlay({
	onClick: function() {
		this.hide();
	},
	onOpen: function() {
		alert('Thank you for opening!');
	}
});</pre>
<p>You’d be hard pressed to find a class that wouldn’t benefit from implementing events!</p>
<h3>13. Use Event Delegation</h3>
<p>Event delegation is the process of adding an event to a parent for all of its children instead of assigning the<br />
event to each individual child. The advantage of event delegation is that you may add child elements to the<br />
parent element without needing to assign the event to that new element. If you choose to remove the event,<br />
you need only remove it from one element.</p>
<p>So, instead of:</p>
<pre>$$('a').addEvent('click',function() {
	//do stuff -- individually assigned
});</pre>
<p>…you do this:</p>
<pre>$('myContainer').addEvent('click:relay(a)',function() {
	//assigned to the parent of all A elements (in this case, #myContainer), to listen to A element click event
})/</pre>
<p>Don’t let the “:relay()” pseudo-syntax fool you; Element.Delegation rewrites the event methods to accommodate for :relay.</p>
<h3>14. Use Class.toElement</h3>
<p>One hidden gem within MooTools’ Class is the Class.toElement method. Class.toElement plays a small role but can help you out<br />
when it comes to accessing the primary element within a class, especially if you don’t know what that element is otherwise.<br />
Implementing toElement on your class is easy:</p>
<pre>var myClass = new Class({

	Implements: [Options],

	initialize: function(container,options) {
		this.container = $(container);
	},

	toElement: function() {
		return this.container;
	}
});</pre>
<p>Once you have toElement defined, you can use your class just like an element:</p>
<pre>var myInstance = new MyClass('myElement');
myInstance.setStyle('color','#f00').set('html','This is my element!');</pre>
<p>Look at that — a class virtually manipulated by Element methods.</p>
<h3>15. “return this” Within Methods For Chainability</h3>
<p>So we’ve all seen how the JavaScript frameworks allow you to chain the hell out of methods. Chaining looks like this:</p>
<pre>$('myElement').setStyles('color','#f00').set('html','Click Here').fade('out').addClass('cssClass').addEvent('click',function(e) {
	if(e) e.stop();
	alert('Clicked'!);
});</pre>
<p>Holy chaining Batman! Want your classes to chain forever? No problem — all you need to do is return “this”:</p>
<pre>var myClass = new Class({

	//options, initialize, implements, etc.

	doSomething: function() {
		//do a whole bunch of functionality here and...
		return this;
	},
	doAnotherThing: function() {
		//do a whole bunch of functionality here and...
		return this;
	},
	doYetAnotherThing: function() {
		//do a whole bunch of functionality here and...
		return this.
	}
});</pre>
<p>Since you placed “return this” in each method, now you can do:</p>
<pre>var klass = new myClass();
klass.doSomething().doAnotherThing().doYetAnotherThing();</pre>
<p>Make sure to return “this” wherever it makes sense. Doing so can make your Class much easier to work with and your code will be shorter!</p>
<h3>BONUS! 16. Use Fx Shortcuts on Elements</h3>
<p>MooTools effects are unarguably the smoothest of any JavaScript framework. The Fx library also provides loads of control through numerous options.<br />
Lets take a look at a basic Tween which fades an element to 50%:</p>
<pre>var myTween = new Fx.Tween('myElement',{
	duration: 500,
	fps: 200,
	//a bunch of options here
});
//fade to 50%
$('myElement').addEvent('click',function() {
	myTween.start('opacity',0.5);
});</pre>
<p>Did you know you didn’t need to type out all of this? You could use element shortcuts like:</p>
<pre>$('myElement').fade(0.5); //fading: Fx.Tween
$('myElement').tween('width',300); //tweening: Fx.Tween
$('myElement').morph({
	width: 200,
	height: 300
}); //morph:  Fx.Morph</pre>
<p>The above snippets, of course, rely on you wanting to use the default options. You can actually set custom options for these shortcut methods per element:</p>
<pre>$('myElement').set('tween',{ duration:500, fps: 200 }).tween('width',300);</pre>
<p>Save your self a few bytes by using Fx shortcuts!</p>
<h3>MooTools FTW!</h3>
<p>Hopefully I’ve given you some tips to improve your MooTools JavaScript code, making it shorter, faster, and stronger. Have some of your own tips to share?<br />
Place them in the comments below!</p>
<p><img src="http://feeds.feedburner.com/~r/nettuts/~4/zf6K2myv5JM" alt="" width="1" height="1" /></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/avi/" title="avi" rel="tag">avi</a>, <a href="http://xguiden.dk/tag/counter/" title="counter" rel="tag">counter</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/gitter/" title="Gitter" rel="tag">Gitter</a>, <a href="http://xguiden.dk/tag/header/" title="Header" rel="tag">Header</a>, <a href="http://xguiden.dk/tag/help/" title="help" rel="tag">help</a>, <a href="http://xguiden.dk/tag/html/" title="HTML" rel="tag">HTML</a>, <a href="http://xguiden.dk/tag/input/" title="input" rel="tag">input</a>, <a href="http://xguiden.dk/tag/internet/" title="internet" rel="tag">internet</a>, <a href="http://xguiden.dk/tag/internet-explorer/" title="Internet Explorer" rel="tag">Internet Explorer</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/iso/" title="iso" rel="tag">iso</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/lp/" title="LP" rel="tag">LP</a>, <a href="http://xguiden.dk/tag/mod/" title="Mod" rel="tag">Mod</a>, <a href="http://xguiden.dk/tag/mount/" title="Mount" rel="tag">Mount</a>, <a href="http://xguiden.dk/tag/outline/" title="Outline" rel="tag">Outline</a>, <a href="http://xguiden.dk/tag/over/" title="Over" rel="tag">Over</a>, <a href="http://xguiden.dk/tag/php/" title="php" rel="tag">php</a>, <a href="http://xguiden.dk/tag/post/" title="POST" rel="tag">POST</a>, <a href="http://xguiden.dk/tag/reference/" title="reference" rel="tag">reference</a>, <a href="http://xguiden.dk/tag/rewrite/" title="rewrite" rel="tag">rewrite</a>, <a href="http://xguiden.dk/tag/sand/" title="Sand" rel="tag">Sand</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/source/" title="Source" rel="tag">Source</a>, <a href="http://xguiden.dk/tag/standard/" title="standard" rel="tag">standard</a>, <a href="http://xguiden.dk/tag/start/" title="Start" rel="tag">Start</a>, <a href="http://xguiden.dk/tag/sten/" title="Sten" rel="tag">Sten</a>, <a href="http://xguiden.dk/tag/switch/" title="switch" rel="tag">switch</a>, <a href="http://xguiden.dk/tag/system/" title="system" rel="tag">system</a>, <a href="http://xguiden.dk/tag/table/" title="table" rel="tag">table</a>, <a href="http://xguiden.dk/tag/tag/" title="tag" rel="tag">tag</a>, <a href="http://xguiden.dk/tag/text/" title="text" rel="tag">text</a>, <a href="http://xguiden.dk/tag/tweening/" title="Tweening" rel="tag">Tweening</a>, <a href="http://xguiden.dk/tag/url/" title="URL" rel="tag">URL</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/13/protect-your-flash-files-from-decompilers-by-using-encryption/" title="Protect Your Flash Files From Decompilers by Using Encryption (13/02/2010)">Protect Your Flash Files From Decompilers by Using Encryption</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/03/how-we%e2%80%99ll-be-building-websites-in-5-years-html5-and-css3-layout/" title="How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout (03/03/2010)">How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/how-to-make-a-css-sprite-powered-menu/" title="How to Make a CSS Sprite Powered Menu (13/02/2010)">How to Make a CSS Sprite Powered Menu</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/" title="How to Build an Unobtrusive Login System in Rails (16/02/2010)">How to Build an Unobtrusive Login System in Rails</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/08/design-and-code-a-cool-iphone-app-website-in-html5/" title="Design and Code a Cool iPhone App Website in HTML5 (08/03/2010)">Design and Code a Cool iPhone App Website in HTML5</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/18/make-your-mootools-code-shorter-faster-and-stronger/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Build an Unobtrusive Login System in Rails</title>
		<link>http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/</link>
		<comments>http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 18:37:12 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[CD]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[fil]]></category>
		<category><![CDATA[fix]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[help]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[LP]]></category>
		<category><![CDATA[Mod]]></category>
		<category><![CDATA[OSX]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[png]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Server]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[Source]]></category>
		<category><![CDATA[standard]]></category>
		<category><![CDATA[Start]]></category>
		<category><![CDATA[Sten]]></category>
		<category><![CDATA[system]]></category>
		<category><![CDATA[table]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[tags]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[valid]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=5091</guid>
		<description><![CDATA[An unobtrusive login system is one that gets out of the user’s way. It will make your application nicer and more polished. This article will guide you through the process of setting up user logins, then ajaxifying the process by moving the form into a modal box that communicates with the server. Additionally, this article [...]]]></description>
			<content:encoded><![CDATA[<p>An unobtrusive login system is one that gets out of the user’s way. It will make your application nicer and more polished. This article will guide you through the process of setting up user logins, then ajaxifying the process by moving the form into a modal box that communicates with the server. Additionally, this article will show you how to create the setup using jQuery and Prototype so you can choose your favorite library. This article assumes that you have experience with Rails and jQuery or Prototype.</p>
<p><span> </span></p>
<div><a href="http://github.com/Adman65/Unobtrusive-Login/"><img src="http://net.tutsplus.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg" alt="" /></a><a href="http://nettuts-unobtrusive-login.heroku.com/"><img src="http://net.tutsplus.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg" alt="" /></a></div>
<p>You can use Adman65/nettuts for a successful login. Be sure to use bad credentials so you can see how everything works.</p>
<h3>What We’re Making</h3>
<div><a href="http://nettuts-unobtrusive-login.heroku.com/"><br />
<img src="http://nettuts.s3.cdn.plus.org/568_login/login4.png" alt="Final Project" /><br />
</a></div>
<h3>Getting Started</h3>
<p>We’re going to start by creating a dummy application that has a public and private page. The root url is the public page. There’s a login link on the public page. If the user logs in successfully, they’re redirected to the private page. If not, they’re redirected back to the login form. The private page shows the user name. We’ll use this as the starting point for ajaxifying the site.</p>
<p>The first step is using the rails command to generate a new application, then install and setup up authlogic.</p>
<pre>$ cd into-a-directory
$ rails unobtrusive-login
</pre>
<p>Add authlogic.</p>
<pre># /config/environment.rb
config.gem 'authlogic'
</pre>
<p>Now install the gems.</p>
<pre>$ sudo gem install gemcutter
$ sudo gem tumble
$ sudo rake gems:install
</pre>
<p>Next create a user model and add the required authlogic columns to the migration.</p>
<pre>$ ./script/generate model User
exists  app/models/
exists  test/unit/
exists  test/fixtures/
create  app/models/user.rb
create  test/unit/user_test.rb
create  test/fixtures/users.yml
create  db/migrate
create  db/migrate/20100102082657_create_users.rb
</pre>
<p>Now, add the columns to the new migration.</p>
<pre>class CreateUsers &lt; ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string    :login,               :null =&gt; false
      t.string    :crypted_password,    :null =&gt; false
      t.string    :password_salt,       :null =&gt; false
      t.string    :persistence_token,   :null =&gt; false
      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end
</pre>
<p>Migrate the database.</p>
<pre>$ rake db:migrate
</pre>
<p>Include authlogic in the user model.</p>
<pre># /app/models/user.rb
class User &lt; ActiveRecord::Base
  acts_as_authentic
end
</pre>
<p>Now we can create a user. Since this is a demo app, web based functionality for signing up isn’t required. So open up the console and create a user:</p>
<pre>$ ./script/console
&gt;&gt; me = User.create(:login =&gt; 'Adman65', :password =&gt; 'nettuts', :password_confirmation =&gt; 'nettuts')
</pre>
<p>Now we have a user in the system, but we have no way to login or logout. We need to create the models, controllers, and views for this. Authlogic has its own class for tracking logins. We can use the generator for that:</p>
<pre># create the user session
$ ./script/generate UserSession
</pre>
<p>Next we need to generate the controller that will login/logout users. You can create sessions just like any other resource in Rails.</p>
<pre># create the session controller
$ ./script/generate controller UserSessions
</pre>
<p>Now set its contents to:</p>
<pre># /app/controllers/user_sessions_controller.rb
class UserSessionsController &lt; ApplicationController
  def new
    @user_session = UserSession.new
  end

  def create
    @user_session = UserSession.new(params[:user_session])
    if @user_session.save
      flash[:notice] = "Login successful!"
      redirect_back_or_default user_path
    else
      render :action =&gt; :new
    end
  end
end
</pre>
<p>It looks exactly the same as a controller that was generated via scaffolding. Now create the users controller which has public and private content. Generate a users controller. Inside the controller we’ll use a before filter to limit access to the private areas. The index action is public and show is private.</p>
<pre># create the users controller
$ ./script/generate controller users
</pre>
<p>Update its contents:</p>
<pre># /app/controllers/users_controller.rb
class UsersController &lt; ApplicationController
  before_filter :login_required, <img class="wp-smiley" src="http://net.tutsplus.cdn.plus.org/wp-includes/images/smilies/icon_surprised.gif" alt=":o" /> nly =&gt; :show

  def index
  end

  def show
    @user = current_user
  end

  private
  def login_required
    unless current_user
      flash[:error] = 'You must be logged in to view this page.'
      redirect_to new_user_session_path
    end
  end
end
</pre>
<p>You should notice that current_user is an undefined method at this point. Define these methods in ApplicationController. Open up application_controller.rb and update its contents:</p>
<pre># application controller
class ApplicationController &lt; ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # From authlogic
  filter_parameter_logging :password, :password_confirmation
  helper_method :current_user_session, :current_user

  private
  def current_user_session
    @current_user_session ||= UserSession.find
  end

  def current_user
    @current_user ||= current_user_session &amp;&amp; current_user_session.user
  end
end
</pre>
<p>At this point the models and controllers are complete, but views aren’t. We need to create views for a login form and the public and private content. We’ll use the nifty-generators gem to create a basic layout.</p>
<pre>$ sudo gem install nifty-generators
$ ./script/generate nifty_layout
</pre>
<p>Time to create the login form. We’re going to use a partial for this because in the future we’ll use the partial to render just the login form in the modal box. Here’s the code to create the login form. It’s exactly the same as if you were creating a blog post or any other model.</p>
<pre># create the login views
# /app/views/user_sessions/_form.html.erb
&lt;% form_for(@user_session, :url =&gt; user_session_path) do |form| %&gt;
  &lt;%= form.error_messages %&gt;

  &lt;p&gt;
    &lt;%= form.label :login %&gt;
    &lt;%= form.text_field :login %&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;%= form.label :password %&gt;
    &lt;%= form.password_field :password %&gt;
  &lt;/p&gt;

  &lt;%= form.submit 'Login' %&gt;
&lt;% end %&gt;
</pre>
<p>Render the partial in the new view:</p>
<pre># /app/views/user_sessions/new.html.erb
&lt;% title 'Login Please' %&gt;
&lt;%= render :partial =&gt; 'form' %&gt;
</pre>
<p>Create some basic pages for the public and private content. The index action shows public content and show displays private content.</p>
<pre># create the dummy public page
# /app/views/users/index.html.erb
&lt;% title 'Unobtrusive Login' %&gt;

&lt;p&gt;Public Facing Content&lt;/p&gt;

&lt;%= link_to 'Login', new_user_session_path %&gt;
</pre>
<p>And for the private page:</p>
<pre># create the dummy private page
# /app/views/users/show.html.erb
&lt;% title 'Welcome' %&gt;
&lt;h2&gt;Hello &lt;%=h @user.login %&gt;&lt;/h2&gt;

&lt;%= link_to 'Logout', user_session_path, :method =&gt; :delete %&gt;
</pre>
<p>Delete the file /public/index.html and start the server. You can now log in and logout of the application.</p>
<pre>$ ./script/server
</pre>
<p>Here are some screenshots of the demo application. The first one is the public page.</p>
<div><img id="publicpage" src="http://nettuts.s3.cdn.plus.org/568_login/login1.png" alt="Public Page" /></div>
<p>Now the login form</p>
<div><img id="loginpage" src="http://nettuts.s3.cdn.plus.org/568_login/login2.png" alt="Login Page" /></div>
<p>And the private page</p>
<div><img id="privatepage" src="http://nettuts.s3.cdn.plus.org/568_login/login3.png" alt="Private Page" /></div>
<p>And finally, access denied when you try to visit http://localhost:3000/user</p>
<div><img id="accessdenied" src="http://nettuts.s3.cdn.plus.org/568_login/login4.png" alt="Access Denied" /></div>
<h3>The AJAX Login Process</h3>
<p>Before continuing, we need to understand how the server and browser are going to work together to complete this process. We know that we’ll need to use some JavaScript for the modal box and the server to validate logins. Let’s be clear on how this is going to work. The user clicks the login link, then a modal box appears with the login form. The user fills in the form and is either redirected to the private page, or the modal box is refreshed with a new login form. The next question is how do you refresh the modal box or tell the browser what to do after the user submits the form? Rails has respond_to blocks. With respond_to, you can tell the controller to render different content if the user requested XML, HTML, JavaScript, YAML etc. So when the user submits the form, the server can return some JavaScript to execute in the browser. We’ll use this render a new form or a redirect. Before diving any deeper, let’s go over the process in order.</p>
<ol>
<li>User goes to the public page</li>
<li>User clicks the login link</li>
<li>Modal box appears</li>
<li>User fills in the form</li>
<li>Form is submitted to the server</li>
<li>Server returns JavaScript for execution</li>
<li>Browser executes the JavaScript which either redirects or updates the modal box.</li>
</ol>
<p>That’s the high level. Here’s the low level implementation.</p>
<ol>
<li>User visits the public page</li>
<li>The public page has some JavaScript that runs when the DOM is ready that attaches JavaScript to the login link. That javscript does an XMLHTTPRequest (XHR from now on) to the server for some JavaScript. The JavaScript sets the modal box’s content to the form HTML. The JavaScript also does something very important. It binds the form’s submit action to an XHR with POST data to the form’s action. This allows the user to keep filling the login form in inside the modal box.</li>
<li>Modal box now has the form and required JavaScript</li>
<li>User clicks ‘Login’</li>
<li>The submit() function is called which does a POST XHR to the form’s action with its data.</li>
<li>Server either generates the JavaScript for the form or the redirect</li>
<li>Browser receives the JavaScript and executes it. The browser will either update the modal box, or redirect the user through window.location.</li>
</ol>
<h2>Taking a Peak at the AJAX Ready Controller</h2>
<p>Let’s take a look at the new structure for the UserSessions controller.</p>
<pre>class UserSessionsController &lt; ApplicationController
  layout :choose_layout

  def new
    @user_session = UserSession.new
  end

  def create
    @user_session = UserSession.new(params[:user_session])

    if @user_session.save
      respond_to do |wants|
        wants.html { redirect_to user_path(@user_session.user) }
        wants.js { render :action =&gt; :redirect } # JavaScript to do the redirect
      end
    else
      respond_to do |wants|
        wants.html { render :new }
        wants.js # defaults to create.js.erb
      end
    end
  end

  private
  def choose_layout
    (request.xhr?) ? nil : 'application'
  end
end
</pre>
<p>As you can see the structure is different. Inside the if save, else conditional, respond_to is used to render the correct content. want.xx where xx is a content type. By default Prototype and jQuery request text/JavaScript. This corresponds to wants.js. We’re about ready to get started on the AJAX part. We won’t use any plugins except ones for modal boxes. We’ll use Facebox for jQuery and ModalBox for Prototype.</p>
<h3>Prototype</h3>
<p>Rails has built in support for Prototype. The Rail’s JavaScript helpers are Ruby functions that generate JavaScript that use Prototype. This technique is known as RJS (Ruby JavaScript). One example is remote_form_for which works like the standard for_for adds some JS bound to onsubmit that submits to the form to its action using its method with its data. I won’t use RJS in this article since I want to demonstrate vanilla JS. I think by using pure JS and eliminating the JS helpers the article will be more approachable by less experienced developers. That being said, you could easily accomplish these steps using RJS/Prototype helpers if you choose.</p>
<p>Adding Prototype to the application is very easy. When you use the rails command, it creates the Prototype and scriptaculous files in /public/JavaScripts. Including them is easy. Open up /app/views/layouts/application.erb and add this line inside the head tag:</p>
<pre>&lt;%= JavaScript_include_tag :defaults %&gt;
</pre>
<p>JavaScript_include_tag creates script tags for default files in /public/JavaScripts, most importantly prototype.js, effects.js, and application.js. effects.js is scriptaculous. application.js is a file you can use to keep application specific JS. Now we need a modal box plugin. We’re going to use <a href="http://okonet.ru/projects/modalbox/">this</a>. Its a very nice modal box plugin inspired by OSX. The source is hosted on GitHub, so you’ll have to clone and move the files in your project directory. For example:</p>
<pre>$ cd code
$ git clone git://github.com/okonet/modalbox.git
$ cd modalbox
# move the files in the correct directories.
# move modalbox.css into /public/stylesheets
# move modalbox.js into /public/JavaScripts
# move spinner.gif into /public/images
</pre>
<p>Now include the stylesheets and JavaScript in your application.</p>
<pre>  &lt;%= stylesheet_link_tag ‘application’ %&gt;
  &lt;%= stylesheet_link_tag ‘modalbox’ %&gt;
  &lt;%= JavaScript_include_tag :defaults %&gt;
  &lt;%= JavaScript_include_tag ‘modalbox’%&gt;</pre>
<p>Now let’s get our login link to open a modalbox. In order to do this we need to add some JavaScript that runs when the DOM is ready that attaches the modalbox to our link. When the user clicks the login link, the browser will do a GET to /user_sessions/new which contains the login form. The login link uses the #login-link selector. Update the login link to use the new id in /app/views/users/index.html.erb. Modify the link_to function like this:</p>
<pre>&lt;%= link_to 'Login', new_user_session_path, :id =&gt; 'login-link' %&gt;
</pre>
<p>That gives us a#login-link. Now for the JavaScript to attach a modalbox. Add this JS in /public/JavaScripts/application.js</p>
<pre>document.observe('dom:loaded', function() {
    $('login-link').observe('click', function(event) {
        event.stop();
        Modalbox.show(this.href,
            {title: 'Login',
            width: 500}
        );
    });
})
</pre>
<p>There’s some simple JS for when the user clicks the link a modal box opens up with the link’s href. Refer to the modalbox documentation if you’d like more customization. Here’s a screenshot:</p>
<div><img id="initialmodalbox" src="http://nettuts.s3.cdn.plus.org/568_login/prototype/step1.png" alt="Initial Modalbox" /></div>
<p>Notice that inside the modal box looks very similar to our standard page. Rails is using our application layout for all HTML responses. Since our XHR’s want HTML fragments, it make sense to render without layouts. Refer back to the example controller. I introduced a method for determining the layout. Add that to UserSessionsController to disable layout for XHR’s.</p>
<pre>class UserSessionsController &lt; ApplicationController
  layout :choose_layout

  def new
    @user_session = UserSession.new
  end

  def create
    @user_session = UserSession.new(params[:user_session])
    if @user_session.save
      flash[:notice] = "Login successful!"
      redirect_to user_path
    else
      render :action =&gt; :new
    end
  end

  def destroy
    current_user_session.destroy
    flash[:notice] = "Logout successful!"
    redirect_to root_path
  end

  private
  def choose_layout
    (request.xhr?) ? nil : 'application'
  end
end
</pre>
<p>Refresh the page and click the link you should get something like this:</p>
<div><img id="withoutlayout" src="http://nettuts.s3.cdn.plus.org/568_login/prototype/step1-1.png" alt="Without Layout" /></div>
<p>Fill in the form and see what happens. If you fill in the from with bad info, you’re redirected outside the modal box. If you login correctly you’re redirected normally. According the requirements the user should be able to fill out the form over and over again inside the modal box until they login correctly. How can we accomplish this? As described before we need to use AJAX to submit data to the server, then use JavaScript to update the modal box with the form or do a redirection. We know that the modalbox does a GET for HTML. After displaying the initial modalbox, we need to write JS that makes the form submits itself AJAX style. This allows the form to submit itself inside the modal box. Simply adding this code after the modal box is called won’t work because the XHR might not have finished. We need to use Modalbox’s afterLoad callback. Here’s the new code:</p>
<pre>document.observe('dom:loaded', function() {
    $('login-link').observe('click', function(event) {
        event.stop();
        Modalbox.show(this.href,
            {title: 'Login',
            width: 500,
            afterLoad: function() {
                $('new_user_session').observe('submit', function(event) {
                    event.stop();
                    this.request();
                })
            }}
        );
    });
})
</pre>
<p>Form#request is a convenience method for serializing and submitting the form via an Ajax.Request to the URL of the form’s action attribute—which is exactly what we want. Now you can fill in the form inside the modal without it closing. The client side is now complete. What about the server side? The client is submitting a POST wanting JS back. The server needs to decide to either return JavaScript to update the form or render a redirect. In the UserSessionsController we’ll use respond_to to handle the JS request and a conditional to return the correct JS. Let’s begin by handling the failed login case. The server needs to return JS that updates the form, and tells the new form to submit over ajax. We’ll place this template in /app/views/users_sessions/create.js.erb. Here’s the structure for the new create action:</p>
<pre>def create
  @user_session = UserSession.new(params[:user_session])
  if @user_session.save
    flash[:notice] = "Login successful!"
    redirect_to user_path
  else
    respond_to do |wants|
      wants.html { render :new }
      wants.js # create.js.erb
    end
  end
end
</pre>
<p>Now let’s fill in create.js.erb:</p>
<pre>$('MB_content').update("&lt;%= escape_JavaScript(render :partial =&gt; 'form') %&gt;");
Modalbox.resizeToContent();
$('new_user_session').observe('submit', function(event) {
    event.stop();
    this.request();
});
</pre>
<p>First we update the content to include the new form. Then we resize the modal box. Next we ajaxify the form just as before. Voilla, you can fill in the form as many times as you want.</p>
<div><img id="badinfo" src="http://nettuts.s3.cdn.plus.org/568_login/prototype/step2.png" alt="Bad Info" /></div>
<div><img id="updatedform" src="http://nettuts.s3.cdn.plus.org/568_login/prototype/step2-1.png" alt="Updated Form" /></div>
<p>Next we need to handle the redirection case. Create a new file in /app/views/users_sessions/redirect.js.erb:</p>
<pre>  window.location=”&lt;%= user_path %&gt;”;
</pre>
<p>Now, update the create action to handle the redirection process:</p>
<pre>def create
  @user_session = UserSession.new(params[:user_session])
  if @user_session.save
    respond_to do |wants|
      wants.html do
        flash[:notice] = "Login successful!"
        redirect_to user_path
      end

      wants.js { render :redirect }
    end
  else
    respond_to do |wants|
      wants.html { render :new }
      wants.js # create.js.erb
    end
  end
end
</pre>
<p>And that’s it! Now try login with correct credentials and you’re redirected to the private page. For further learning, try to add a spinner and notification telling the user the form is submitting or they’re being redirect. The application still works if the user has JavaScript disabled too.</p>
<h1>jQuery</h1>
<p>Since I’ve already covered the Prototype process, so I won’t go into the same detail as before. Instead, I will move quickly describing the alternate JavaScript to add to the application. The jQuery vesion will have the exact same structure as the Prototype version. All we need to change is what’s in application.js, create.js.erb, and the JavaScript/css includes.</p>
<p>First thing we need to do is download <a href="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">jQuery</a> and <a href="http://famspam.com/facebox/releases/facebox-1.2.tar.gz">Facebox</a>. Move jQuery into /public/JavaScripts as jquery.js. For facebox move the images into /public/images/, stylesheets into /public/stylesheets, and finally the JS into /public/JavaScripts. Now update /app/views/layouts/application.html.erb to reflect the changes:</p>
<pre>&lt;head&gt;
  &lt;title&gt;&lt;%= h(yield(:title) || "Untitled") %&gt;&lt;/title&gt;
  &lt;%= stylesheet_link_tag 'facebox' %&gt;
  &lt;%= stylesheet_link_tag 'application' %&gt;
  &lt;%= JavaScript_include_tag 'jquery' %&gt;
  &lt;%= JavaScript_include_tag 'facebox' %&gt;
  &lt;%= JavaScript_include_tag 'application' %&gt;
&lt;/head&gt;
</pre>
<p>Facebox comes with a default stylesheet which assumes you have your images in /facebox. You’ll need to update these selectors in facebox.css like so:</p>
<pre>#facebox .b {
  background:url(/images/b.png);
}

#facebox .tl {
  background:url(/images/tl.png);
}

#facebox .tr {
  background:url(/images/tr.png);
}

#facebox .bl {
  background:url(/images/bl.png);
}

#facebox .br {
  background:url(/images/br.png);
}
</pre>
<p>Now we attach facebox to the login link. Open up /public/JavaScripts/application.js and use this:</p>
<pre>$(document).ready(function() {
    $('#login-link').facebox({
        loadingImage : '/images/loading.gif',
    closeImage   : '/images/closelabel.gif',
    });
});
</pre>
<p>I override the default settings for the images to reflect the new image path. Start the sever and head over to the index page. You should see a nice facebox with the login form:</p>
<div><img id="facebox" src="http://nettuts.s3.cdn.plus.org/568_login/jquery/step1.png" alt="Facebox" /></div>
<p>Next thing we have to do is set the form to submit itself via AJAX. Just like before, we’ll have to use callbacks to execute code after the modal box is ready. We’ll use jQuery’s post method for the XHR request. Facebox has an after reveal hook we can use. application.js:</p>
<pre>$(document).ready(function() {
    $('#login-link').facebox({
        loadingImage : '/images/loading.gif',
        closeImage   : '/images/closelabel.gif',
    });

    $(document).bind('reveal.facebox', function() {
        $('#new_user_session').submit(function() {
            $.post(this.action, $(this).serialize(), null, "script");
            return false;
        });
    });
});
</pre>
<p>Updating create.js.erb should be easy enough. We have to update the facebox’s contents and re-ajaxify the form. Here’s the code:</p>
<pre>$('#facebox .content').html("&lt;%= escape_JavaScript(render :partial =&gt; 'form') %&gt;");
$('#new_user_session').submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
});
</pre>
<p>And that’s it! Here’s the final product:</p>
<div><img id="loggingin" src="http://nettuts.s3.cdn.plus.org/568_login/jquery/step2.png" alt="Logging In" /></div>
<div><img id="badlogin" src="http://nettuts.s3.cdn.plus.org/568_login/jquery/step2-1.png" alt="Bad Login" /></div>
<div><img id="redirected" src="http://nettuts.s3.cdn.plus.org/568_login/jquery/step2-2.png" alt="Redirected" /></div>
<p><img src="http://feeds.feedburner.com/~r/nettuts/~4/snw0jxkP2Kk" alt="" width="1" height="1" /></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/cd/" title="CD" rel="tag">CD</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/database/" title="database" rel="tag">database</a>, <a href="http://xguiden.dk/tag/fil/" title="fil" rel="tag">fil</a>, <a href="http://xguiden.dk/tag/fix/" title="fix" rel="tag">fix</a>, <a href="http://xguiden.dk/tag/flash/" title="Flash" rel="tag">Flash</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/guide/" title="guide" rel="tag">guide</a>, <a href="http://xguiden.dk/tag/help/" title="help" rel="tag">help</a>, <a href="http://xguiden.dk/tag/html/" title="HTML" rel="tag">HTML</a>, <a href="http://xguiden.dk/tag/image/" title="image" rel="tag">image</a>, <a href="http://xguiden.dk/tag/images/" title="images" rel="tag">images</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/login/" title="login" rel="tag">login</a>, <a href="http://xguiden.dk/tag/lp/" title="LP" rel="tag">LP</a>, <a href="http://xguiden.dk/tag/mod/" title="Mod" rel="tag">Mod</a>, <a href="http://xguiden.dk/tag/osx/" title="OSX" rel="tag">OSX</a>, <a href="http://xguiden.dk/tag/over/" title="Over" rel="tag">Over</a>, <a href="http://xguiden.dk/tag/png/" title="png" rel="tag">png</a>, <a href="http://xguiden.dk/tag/post/" title="POST" rel="tag">POST</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/server/" title="Server" rel="tag">Server</a>, <a href="http://xguiden.dk/tag/session/" title="Session" rel="tag">Session</a>, <a href="http://xguiden.dk/tag/source/" title="Source" rel="tag">Source</a>, <a href="http://xguiden.dk/tag/standard/" title="standard" rel="tag">standard</a>, <a href="http://xguiden.dk/tag/start/" title="Start" rel="tag">Start</a>, <a href="http://xguiden.dk/tag/sten/" title="Sten" rel="tag">Sten</a>, <a href="http://xguiden.dk/tag/system/" title="system" rel="tag">system</a>, <a href="http://xguiden.dk/tag/table/" title="table" rel="tag">table</a>, <a href="http://xguiden.dk/tag/tag/" title="tag" rel="tag">tag</a>, <a href="http://xguiden.dk/tag/tags/" title="tags" rel="tag">tags</a>, <a href="http://xguiden.dk/tag/text/" title="text" rel="tag">text</a>, <a href="http://xguiden.dk/tag/url/" title="URL" rel="tag">URL</a>, <a href="http://xguiden.dk/tag/valid/" title="valid" rel="tag">valid</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/" title="How to Code up a Web Design from PSD to HTML (15/02/2010)">How to Code up a Web Design from PSD to HTML</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/ajax-enabled-sticky-notes-with-php-and-jquery/" title="AJAX-enabled Sticky Notes With PHP and jQuery (13/02/2010)">AJAX-enabled Sticky Notes With PHP and jQuery</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/jquery-ajax-validation-contact-form-with-modal-slide-in-transition/" title="jQuery AJAX Validation Contact Form with Modal + Slide-in Transition (13/02/2010)">jQuery AJAX Validation Contact Form with Modal + Slide-in Transition</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/protect-your-flash-files-from-decompilers-by-using-encryption/" title="Protect Your Flash Files From Decompilers by Using Encryption (13/02/2010)">Protect Your Flash Files From Decompilers by Using Encryption</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/25/php-and-mysql-file-download-counter/" title="PHP and MySQL File Download Counter (25/02/2010)">PHP and MySQL File Download Counter</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Code up a Web Design from PSD to HTML</title>
		<link>http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/</link>
		<comments>http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 11:03:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[avi]]></category>
		<category><![CDATA[Cool]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[DOCTYPE]]></category>
		<category><![CDATA[fil]]></category>
		<category><![CDATA[fix]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[Gradient]]></category>
		<category><![CDATA[Header]]></category>
		<category><![CDATA[help]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[LP]]></category>
		<category><![CDATA[META]]></category>
		<category><![CDATA[Mod]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[Photoshop]]></category>
		<category><![CDATA[png]]></category>
		<category><![CDATA[porte]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Server]]></category>
		<category><![CDATA[standard]]></category>
		<category><![CDATA[Start]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[tags]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[textur]]></category>
		<category><![CDATA[Transparent]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[valid]]></category>
		<category><![CDATA[Wanted]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=5047</guid>
		<description><![CDATA[A couple of weeks back we went through the process of creating a gnarly snowboarding themed website design concept in Photoshop. The tutorial covered the process of designing our site concept from sketch to finished PSD design. Now, let’s take the design to the next step and code up a complete mockup in HTML and [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks back we went through the process of creating a gnarly snowboarding themed website design concept in Photoshop. The tutorial covered the process of designing our site concept from sketch to finished PSD design. Now, let’s take the design to the next step and code up a complete mockup in HTML and CSS, ensuring our code is semantic and standards compliant. We’ll then add some finishing touches with a spot of jQuery.</p>
<p><span> </span></p>
<h3>To refresh your memory</h3>
<p><a href="http://line25.com/tutorials/create-a-gnarly-snowboarding-themed-web-design"><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/concept.jpg" alt="See the making of the concept" /></a></p>
<p>Cast your mind back and you’ll remember we left off at the end of the post titled Create a Gnarly Snowboarding Themed Web Design with a finished PSD sporting a textured background, large feature area and a mix of text, images and video making up the main content area.</p>
<h3>Cutting up the PSD concept</h3>
<p>With our design being pretty design heavy, there’s a good selection of elements that will need exporting from the PSD. The first is the large textured background.</p>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/export-select-bg.jpg" alt="Select the background texture" /></p>
<p>Disable all other layers then draw a large marquee across the design that includes all the textured elements and blue gradient. Press CMD+Shift+C to copy this selection, then paste in into a new document.</p>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/export-bg.jpg" alt="Extend the background to accommodate large monitors" /></p>
<p>To take into consideration larger monitors, we need to make sure our design is wide enough not to be cropped off. A width of 2200px should be more than sufficient to accommodate even the larger of monitor setups. Select a portion of the gradient and press CMD-T to transform and stretch the background to fill the white space. Save this large image for the web, but take care to balance between file size and quality. With the image being super-sized, it’s important to carefully select the appropriate compression settings. My final file weighs in at 220kb, which is pretty heavy in normal circumstances, but considering that the rest of the design is quite lightweight, it’s a sacrifice that can be justified. <em>We could have made things much easier for ourselves by not including a gradient as well as a texture, this way we could set a smaller graphic in the center that fades out to a flat colour. (Or wait until the multiple backgrounds CSS3 property is more widely supported!)</em></p>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/export-logo.jpg" alt="Selecting the logo graphic" /></p>
<p>Continue selecting individual page elements with the marquee tool, pressing CMD-Shift-C to copy-merged then paste in a new document and export. Elements such as the logo, feature graphics, profile shots and every small icon needs saving as an individual graphic.</p>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/export-button.jpg" alt="Exporting individual page items" /></p>
<p>Remember to choose the most appropriate file type and compression setting for each item. An element that is made up of flat colours will be more suited to PNG format. Elements that require a transparent background can be exported using the PNG-24 option.</p>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/images.jpg" alt="Overview of all image files" /></p>
<p>Once all of the images have been saved, you’re ready to move onto the HTML section of the website build.</p>
<h3>Building the HTML structure</h3>
<p>It’s always important to build the house before decorating the rooms, so we’ll begin by writing out the HTML structure of the website. We’ll base the HTML on the XHTML Strict Doctype and add the initial link to the stylesheet and a containing div to hold the content.</p>
<div>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;title&gt;Snow Candy&lt;/title&gt;

&lt;link href="style.css" rel="stylesheet" type="text/css" media="screen" /&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;div id="container"&gt;

&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
</div>
<h4>The header</h4>
<p>The structure for the header is pretty simple. We have our logo, which is set in a H1 and links back to the homepage. Our navigation is perfect for an unordered list, and each contains an anchor to the relevant page. A class of active will then allow us to target an individual page for highlighting the active page.</p>
<div>
<pre>&lt;div id="header"&gt;
	&lt;h1&gt;&lt;a href="#"&gt;Snow Candy&lt;/a&gt;&lt;/h1&gt;
	&lt;ul id="nav"&gt;
		&lt;li&gt;&lt;a href="#" class="active"&gt;Home&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href="#"&gt;Apparel&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href="#"&gt;Team&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href="#"&gt;Shop&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt;
</pre>
</div>
<h4>The content</h4>
<p>Next we flesh out the bulk of the page content. The whole main area can be contained within a div with an ID of content. Within this we’ll start with the large feature graphics, an unordered list will once again be a handy element to use, as it allows us to easily list them out in sequence. Inside each list element is each image graphic, complete with a descriptive alt attribute.</p>
<div>
<pre>&lt;div id="content"&gt;
&lt;div id="features"&gt;
	&lt;ul&gt;
		&lt;li&gt;&lt;a href="#"&gt;&lt;img src="images/feature-1.jpg" alt="5th Annual Big Air Jam. 5th January 2010" /&gt;&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href="#"&gt;&lt;img src="images/feature-2.jpg" alt="Salomon Shred Round One" /&gt;&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href="#"&gt;&lt;img src="images/feature-3.jpg" alt="Snow Candy in S&amp;auml;len" /&gt;&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt;
</pre>
</div>
<p>The design then splits into two columns, so we can add a div with a class of column ready for floating with CSS later. Within the featured video section I’ve embedded a cool snowboarding video from <a href="http://vimeo.com/3155182">Vimeo</a>, followed by the title and description, both set in natural header and paragraph tags. A paragraph tag with a class of “btn” will allow us to set up a global style for any button style objects, allowing some unique styling to be added. The actual Vimeo embedding code has been modified slightly to keep it valid within our Strict doctype.<em> </em></p>
<div>
<pre>&lt;div class="column"&gt;
	&lt;h2 class="featured-video"&gt;Featured Video&lt;/h2&gt;
	&lt;div class="video"&gt;
		&lt;object width="379" height="213" type="application/x-shockwave-flash" data="http://vimeo.com/moogaloop.swf?clip_id=3155182&amp;amp;server=vimeo.com&amp;amp;show_title=0&amp;amp;show_byline=0&amp;amp;show_portrait=0&amp;amp;color=00adef&amp;amp;fullscreen=1"&gt;
			&lt;param name="allowfullscreen" value="true" /&gt;
			&lt;param name="allowscriptaccess" value="always" /&gt;
			&lt;param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=3155182&amp;amp;server=vimeo.com&amp;amp;show_title=0&amp;amp;show_byline=0&amp;amp;show_portrait=0&amp;amp;color=00adef&amp;amp;fullscreen=1" /&gt;
		&lt;/object&gt;
	&lt;/div&gt;

	&lt;h3&gt;&lt;a href="#"&gt;Snow Candy in S&amp;auml;len&lt;/a&gt;&lt;/h3&gt;
	&lt;p&gt;The Snow Candy team head to S&amp;auml;len to experience the local snow, attractions and lifestyle.&lt;/p&gt;
	&lt;p class="btn"&gt;&lt;a href="#"&gt;See more videos&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
</pre>
</div>
<p>In the second column, the list of events has a layout that lends itself well to being rendered as a definition list, with the date and event description being relative to each other. The date can be set as the definition title, and the definition description as the content, which will help us target these tags to style up the fancy layout we’ve got going on. With the dates being laid out vertically at different type sizes, adding a span around the month will help provide that extra hook needed for the CSS styling.</p>
<div>
<pre>&lt;div class="column"&gt;
	&lt;h2 class="events"&gt;Upcoming Events&lt;/h2&gt;
	&lt;dl&gt;
		&lt;dt&gt;5 &lt;span&gt;Feb&lt;/span&gt;&lt;/dt&gt;
		&lt;dd&gt;
			&lt;h4&gt;5th Annual BigAir Jam&lt;/h4&gt;
			&lt;p&gt;Elite riders compete for the title of 2010 BigAir champion in the 5th annual running of the event in Sallback, Austria. Last year’s winner Nate Bailey is returning to defend his crown against some of the most elite names from Europe and the USA.&lt;/p&gt;
		&lt;/dd&gt;

		&lt;dt&gt;3 &lt;span&gt;Mar&lt;/span&gt;&lt;/dt&gt;
		&lt;dd&gt;
			&lt;h4&gt;Salomon Shred Round 1&lt;/h4&gt;
			&lt;p&gt;Elite riders compete for the title of 2010 BigAir champion in the 5th annual running of the event in Sallback, Austria. Last year’s winner Nate Bailey is returning to defend his crown against some of the most elite names from Europe and the USA.&lt;/p&gt;
		&lt;/dd&gt;
	&lt;/dl&gt;
	&lt;p class="btn"&gt;&lt;a href="#"&gt;See more events&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
</pre>
</div>
<p>The last portion of content is the list of team members. Again, this list of objects is tailored nicely to be written as an unordered list element. Within each list element is an anchor link that will head off to the relevant page. Each anchor also has a class to help identify each team member when styling them up.</p>
<div>
<pre>&lt;h2 class="team"&gt;Meet the Team&lt;/h2&gt;

&lt;ul id="team"&gt;
	&lt;li&gt;&lt;a href="#" class="joe"&gt;Joe&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href="#" class="charlie"&gt;Charlie&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href="#" class="lars"&gt;Lars&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href="#" class="marco"&gt;Marco&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</pre>
</div>
<h4>The footer</h4>
<p>The HTML is then closed out with the footer, containing a simple back-to-top link, and the body and HTML tags closed to finish off the document. A quick validation ensures there’s no errors, meaning it’s time to move onto some CSS styling.</p>
<div>
<pre>	&lt;div id="footer"&gt;
		&lt;p&gt;&lt;a href="#header" class="back-top"&gt;Back to top&lt;/a&gt;&lt;/p&gt;
	&lt;/div&gt;

&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
</div>
<h3>Styling the CSS</h3>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/body.jpg" alt="Body styling complete" /></p>
<p>The first line of CSS that’s written is to quickly reset any browser specific styling. Ensuring that we’re starting from a clean slate when it comes to margins, padding and borders. Next, the sans-serif font-family is set on the body tag, to render the Helvetica font throughout the design. A line-height of 24px will help us stick to our 24px baseline grid from the design, and will help fix any differences between browsers.</p>
<p>The main background of the site is then added. First the flat blue colour is specified, then the large textured background. This is positioned at the top center, and told not to repeat. Unlike inline images, background images don’t create scrollbars if they are larger than the content window, so despite our graphic being a huge 2200 pixels wide, a portion of the edges will be hidden according to how large the viewer’s monitor is.</p>
<div>
<pre>body, div, h1, h2, h3, h4, h5, h6, p, ul, ol, li, dl, dt, dd, img, form, fieldset, blockquote {
	margin: 0; padding: 0; border: 0;
}

body {
	font-family: Helvetica, Arial, Sans-Serif; line-height: 24px;
	background: #b9d2f8 url(images/body-bg.jpg) center top no-repeat;
}
</pre>
</div>
<h4>The header</h4>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/head.jpg" alt="Styling the header section" /></p>
<p>Next up for styling is the main container div, which is simply given a 980px width and set to appear centrally. This is followed by the header and its sub-elements. The header div is given some padding to create the spacing at the top and sides according to the PSD concept, and is given an overflow:hidden property to clear itself and correctly calculate its height after the floated navigation elements.</p>
<p>The header one tag is given specific dimensions in order to properly display the logo as a background image, and a negative text-indent shifts the standard header text out of the way off-screen. The navigation is then floated alongside it, with a little margin to help align the elements. Each anchor inside the list items is styled to give the appropriate appearance according to the PSD concept, which includes setting the font-size and gaps between each element. They are then finished off with the addition of the transparent brush stroke graphic as a background image for links that have the active class, or are being hovered by the mouse.</p>
<div>
<pre>#container {
	width: 980px; margin: 0 auto;
}

#header {
	padding: 48px 16px 0 16px; overflow: hidden;
}
	#header h1 a {
		display: block; width: 221px; height: 107px; float: left;
		background: url(images/logo.jpg); text-indent: -9999px;
	}

	#header ul#nav {
		width: 720px; float: right; margin: 42px 0 0 0;
	}
		#header ul#nav li {
			float: left; list-style: none;
		}
			#header ul#nav li a {
				display: block; width: 155px; height: 34px; margin: 0 0 0 25px; padding: 12px 0 0 0;
				font-size: 24px; text-transform: lowercase; color: #fff; text-decoration: none; text-align: center;
				text-shadow: 0 3px 3px #333;
			}
				#header ul#nav li a:hover, #header ul#nav li a.active {
					background: url(images/active-nav.png);
				}
</pre>
</div>
<h4>General content styling</h4>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/content.jpg" alt="Styling the content background" /></p>
<p>The main central content area can then be styled to mimic the original PSD concept. First it’s given a specific width, with padding to push the content away from the edges. It’s set to overflow:hidden because it will contain some floated elements, and is given a transparent-white background PNG to create the translucent effect. Other options to create the white transparency could have been the opacity property, or the CSS3 RGBa property, but a good old PNG-24 graphic is the most cross-browser friendly, with just IE6 requiring extra work to enable the alpha transparency.</p>
<p>To finish off the content area, a small radius is added to the corners using the border-radius property. Because this isn’t fully supported yet, browser specific code can tell individual browsers to add the novelty effect.</p>
<div>
<pre>#content {
	width: 938px; padding: 16px 16px 60px 16px; overflow: hidden;
	background: url(images/white-trans.png);
	border-radius: 3px;
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
}
</pre>
</div>
<h4>Styling the feature section</h4>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/features.jpg" alt="Styling the features section" /></p>
<p>The large features section in the design currently holds three slides, but the aim is to only display one at a time. When Javascript is added, these can be tweaked to transitionally fade between each one, but we also need the section to work without Javascript being enabled. To do this, the features section is given the specific dimensions of one slide. The overflow:scroll property will then add scrollbars to allow the user to manually navigation between slides. The UL is given a width of 2820px (3x the width of the slides), and they’re floated side by side. Without limiting the features container to a specific size, the slides would simply fill up the whole page, which ruins the usability of the site. This way, the user can experience the features slideshow, albeit in a much more low-tech way.</p>
<div>
<pre>#content #features {
	width: 940px; height: 457px; margin: 0 0 48px 0;
	overflow: scroll; /* Changed to hidden if javascript enabled */
}
	#content #features ul {
		width: 2820px;
	}

	#content #features ul li {
		float: left;
	}
</pre>
</div>
<h4>Styling the columns and their content</h4>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/columns.jpg" alt="Styling the columns content" /></p>
<p>Remember those two columns we wrote out in the HTML? They need floating side by side, so a width is calculated that will fit inside the content div, and the float:left property added. Inside these columns the video and upcoming events sections are styled. The video div simply has an image background to style up the embedded video, and some padding quickly aligns everything up. The definition list for the events section requires some extra CSS to manipulate the basic definition list element into the fancy layout we have planned. The date of each event is contained within the definition title, so that can be floated to the side and set to a large font-size. The extra span we added then comes in handy to render the  month text at a smaller font-size, and as a block element so that it drops down below the number.</p>
<p>The definition description and its header h4 tags can then be given the appropriate typographic treatment once the DD is floated alongside the DT. With all styling complete it matches the original concept perfectly.</p>
<div>
<pre>#content .column {
	width: 409px; float: left; padding: 0 30px 0 30px; margin: 0 0 24px 0;
}
	#content .column .video {
		width: 387px; height: 222px; padding: 13px 0 0 17px; margin: 0 0 24px 0;
		background: url(images/video-bg.jpg) no-repeat;
	}

	#content .column dl dt {
		width: 55px; float: left; padding: 10px 0 0 0;  overflow: auto;
		color: #fff; font-size: 64px; line-height: 34px;
	}
		#content .column dl dt span {
			font-size: 16px; text-transform: uppercase; display: block;;
		}
		#content .column dl dd {
			float: left; width: 354px;
		}

		#content .column dl h4 {
			font-size: 32px; font-weight: normal; color: #fff; margin: 0 0 5px 0;
		}
</pre>
</div>
<h4>Styling the team list</h4>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/team.jpg" alt="Styling the team section" /></p>
<p>The last part of the content styling is to flesh out the list of team members. Earlier each team member photo was exported, so these can now be set to each individual anchor tag. Each list item is set to float left, and is given the appropriate margin to space them out across the page. Anchor elements are by default inline elements, so to allow a specific width and height to be set, they need to be converted to display:block. Each individual team member can then be targeted through the class names on each anchor, with each photo graphic and image dimensions being added as a background.</p>
<div>
<pre>#content ul#team {
	list-style: none; overflow: hidden;
}
	#content ul#team li {
		float: left; margin: 0 0 0 27px;
	}
		#content ul#team li a {
			display: block; text-indent: -9999px;
		}
			#content ul#team li a.joe {
				width: 199px; height: 229px;
				background: url(images/joe.jpg);
			}
			#content ul#team li a.charlie {
				width: 199px; height: 229px;
				background: url(images/charlie.jpg);
			}
			#content ul#team li a.lars {
				width: 205px; height: 233px;
				background: url(images/lars.jpg);
			}
			#content ul#team li a.marco {
				width: 198px; height: 229px;
				background: url(images/marco.jpg);
			}
</pre>
</div>
<h4>Styling the footer</h4>
<p><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/footer.jpg" alt="Styling the footer" /></p>
<p>The footer area can be quickly finished up by adding the subtle texture background, and the back-to-top link floated over to the right, styled up and positioned into place.</p>
<div>
<pre>#footer {
	min-height: 159px; overflow: hidden;
	background: url(images/footer-bg.jpg) center 0 no-repeat;
}
	#footer p a.back-top {
		float: right; margin: 14px 24px 0 0;
		font-size: 12px; text-decoration: none; color: #4d74bb;
	}
		#footer p a.back-top:hover {
			color: #234c97;
		}
</pre>
</div>
<h3>Adding the Javascript</h3>
<p>Let’s not forget the extra Javascript effects we had planned for that features section. With the help of some <a href="http://jquery.com/">jQuery</a>, and the super cool <a href="http://malsup.com/jquery/cycle/">Cycle plugin</a>, we can easily transform that basic features list into a fully working slideshow.</p>
<div>
<pre>&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="js/scripts.js" type="text/javascript"&gt;&lt;/script&gt;
</pre>
</div>
<p>First, the jQuery library and our own scripts file is referenced in the HTML. The cycle plugin is included in the scripts.js, then some of our own Javascript can put it all into practice. First the overflow:scroll on the features list needs changing to hidden to remove those ugly scrollbars, then the cycle plugin is initiated on the features list. By default the plugin will place a simple fading transition between each element, but there’s plenty more options that could be configured.</p>
<div>
<pre>$(document).ready(function() {

/* Change the overflow:scroll to overflow hidden on the Features list */

	$('#features').css('overflow','hidden');

/* Initiate the cycle on the Features list */
	$('#features ul').cycle();
});
</pre>
</div>
<h3>The final concept</h3>
<p><a href="http://line25.com/wp-content/uploads/2010/snowboard-design-code/demo/index.html"><img src="http://line25.com/wp-content/uploads/2010/snowboard-design-code/final.jpg" alt="View the final demo" /></a></p>
<p>So here we have the complete mockup in live HTML and CSS format. Our HTML is clean and valid, and the CSS renders everything how we wanted according to the original PSD concept.</p>
<p><a href="http://line25.com/wp-content/uploads/2010/snowboard-design-code/demo/index.html">View the demo</a></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/avi/" title="avi" rel="tag">avi</a>, <a href="http://xguiden.dk/tag/cool/" title="Cool" rel="tag">Cool</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/css3/" title="css3" rel="tag">css3</a>, <a href="http://xguiden.dk/tag/design/" title="design" rel="tag">design</a>, <a href="http://xguiden.dk/tag/doctype/" title="DOCTYPE" rel="tag">DOCTYPE</a>, <a href="http://xguiden.dk/tag/fil/" title="fil" rel="tag">fil</a>, <a href="http://xguiden.dk/tag/fix/" title="fix" rel="tag">fix</a>, <a href="http://xguiden.dk/tag/flash/" title="Flash" rel="tag">Flash</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/gradient/" title="Gradient" rel="tag">Gradient</a>, <a href="http://xguiden.dk/tag/header/" title="Header" rel="tag">Header</a>, <a href="http://xguiden.dk/tag/help/" title="help" rel="tag">help</a>, <a href="http://xguiden.dk/tag/html/" title="HTML" rel="tag">HTML</a>, <a href="http://xguiden.dk/tag/image/" title="image" rel="tag">image</a>, <a href="http://xguiden.dk/tag/images/" title="images" rel="tag">images</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/lp/" title="LP" rel="tag">LP</a>, <a href="http://xguiden.dk/tag/meta/" title="META" rel="tag">META</a>, <a href="http://xguiden.dk/tag/mod/" title="Mod" rel="tag">Mod</a>, <a href="http://xguiden.dk/tag/over/" title="Over" rel="tag">Over</a>, <a href="http://xguiden.dk/tag/photoshop/" title="Photoshop" rel="tag">Photoshop</a>, <a href="http://xguiden.dk/tag/png/" title="png" rel="tag">png</a>, <a href="http://xguiden.dk/tag/porte/" title="porte" rel="tag">porte</a>, <a href="http://xguiden.dk/tag/post/" title="POST" rel="tag">POST</a>, <a href="http://xguiden.dk/tag/reference/" title="reference" rel="tag">reference</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/server/" title="Server" rel="tag">Server</a>, <a href="http://xguiden.dk/tag/standard/" title="standard" rel="tag">standard</a>, <a href="http://xguiden.dk/tag/start/" title="Start" rel="tag">Start</a>, <a href="http://xguiden.dk/tag/tag/" title="tag" rel="tag">tag</a>, <a href="http://xguiden.dk/tag/tags/" title="tags" rel="tag">tags</a>, <a href="http://xguiden.dk/tag/text/" title="text" rel="tag">text</a>, <a href="http://xguiden.dk/tag/textur/" title="textur" rel="tag">textur</a>, <a href="http://xguiden.dk/tag/transparent/" title="Transparent" rel="tag">Transparent</a>, <a href="http://xguiden.dk/tag/tutorial/" title="tutorial" rel="tag">tutorial</a>, <a href="http://xguiden.dk/tag/url/" title="URL" rel="tag">URL</a>, <a href="http://xguiden.dk/tag/valid/" title="valid" rel="tag">valid</a>, <a href="http://xguiden.dk/tag/wanted/" title="Wanted" rel="tag">Wanted</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/03/08/design-and-code-a-cool-iphone-app-website-in-html5/" title="Design and Code a Cool iPhone App Website in HTML5 (08/03/2010)">Design and Code a Cool iPhone App Website in HTML5</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/03/how-we%e2%80%99ll-be-building-websites-in-5-years-html5-and-css3-layout/" title="How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout (03/03/2010)">How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/18/coding-a-css3-html5-one-page-website-template/" title="Coding a CSS3 &amp; HTML5 One-Page Website Template (18/02/2010)">Coding a CSS3 &amp; HTML5 One-Page Website Template</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/jquery-ajax-validation-contact-form-with-modal-slide-in-transition/" title="jQuery AJAX Validation Contact Form with Modal + Slide-in Transition (13/02/2010)">jQuery AJAX Validation Contact Form with Modal + Slide-in Transition</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/" title="How to Build an Unobtrusive Login System in Rails (16/02/2010)">How to Build an Unobtrusive Login System in Rails</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX User Poll Using jQuery and PHP</title>
		<link>http://xguiden.dk/2010/02/13/ajax-user-poll-using-jquery-and-php/</link>
		<comments>http://xguiden.dk/2010/02/13/ajax-user-poll-using-jquery-and-php/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 17:04:25 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[avi]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[fil]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[input]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MYSQL]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[png]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Server]]></category>
		<category><![CDATA[Source]]></category>
		<category><![CDATA[Start]]></category>
		<category><![CDATA[table]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=3760</guid>
		<description><![CDATA[
Today, we’ll be creating a nice user poll script using jQuery and PHP utilizing AJAX and animation effects of jQuery to spice up the user interface and provide a rich user experience. Let’s get started.
Set up the database
For storing poll questions, options and votes, we’ll be using a MySQL database. Here is the database structure [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-495" title="AJAX User Poll Using jQuery, PHP" src="http://webdeveloperplus.com/wp-content/uploads/2009/10/ajax-poll-jquery.png" alt="AJAX User Poll Using jQuery, PHP" width="599" height="376" /><br />
Today, we’ll be creating a nice user poll script using jQuery and PHP utilizing AJAX and animation effects of jQuery to spice up the user interface and provide a rich user experience. Let’s get started.</p>
<h3>Set up the database</h3>
<p>For storing poll questions, options and votes, we’ll be using a MySQL database. Here is the database structure required.<br />
<img class="alignnone size-full wp-image-496" title="Database Structure" src="http://webdeveloperplus.com/wp-content/uploads/2009/10/ajax-poll-database-structure.jpg" alt="Database Structure" width="460" height="192" /><br />
There are three tables:</p>
<ul>
<li><strong>questions</strong> table stores the poll questions.</li>
<li><strong>options</strong> table stores the options of a particular question.</li>
<li><strong>votes</strong> table stores information about each vote cast by the user.</li>
</ul>
<p>The required SQL code with sample data is provided in source code(below).</p>
<h3>The PHP Code</h3>
<h4>Displaying the poll form</h4>
<p>We’ll display the most recent poll question from the database and allow the user to vote for it. Here’s the required PHP code to generate poll form for latest poll question.</p>
<pre>$conn=mysql_connect('localhost', 'root', 'password') or die("Can't connect to mysql host");
mysql_select_db("polls");
$query=mysql_query("SELECT id, ques FROM questions ORDER BY id DESC LIMIT 1");
while($row=mysql_fetch_assoc($query)){
	//display question
	echo "&lt;p class=\"pollques\" &gt;".$row["ques"]."&lt;/p&gt;";
	$poll_id=$row["id"];
}
//display options with radio buttons
$query=mysql_query("SELECT id, value FROM options WHERE ques_id=$poll_id");
if(mysql_num_rows($query)){
		echo '&lt;div id="formcontainer" &gt;&lt;form method="post" id="pollform" action="'.$_SERVER['PHP_SELF'].'" &gt;';
		echo '&lt;input type="hidden" name="pollid" value="'.$poll_id.'" /&gt;';
		while($row=mysql_fetch_assoc($query)){
			echo '&lt;p&gt;&lt;input type="radio" name="poll" value="'.$row['id'].'" id="option-'.$row['id'].'" /&gt;
			&lt;label for="option-'.$row['id'].'" &gt;'.$row['value'].'&lt;/label&gt;&lt;/p&gt;';
		}
		echo '&lt;p&gt;&lt;input type="submit"  value="Submit" /&gt;&lt;/p&gt;&lt;/form&gt;';
}</pre>
<h4>Processing the Submitted Vote</h4>
<p>When user selects an answer and submits the form, we add the information to the <em>votes</em> table about the option selected and also set a cookie in user’s browser to identify that he has voted for the poll.</p>
<pre>$query=mysql_query("SELECT * FROM options WHERE id='".intval($_POST["poll"])."'");
if(mysql_num_rows($query)){
	$query="INSERT INTO votes(option_id, voted_on, ip) VALUES('".$_POST["poll"]."', '".date('Y-m-d H:i:s')."', '".$_SERVER['REMOTE_ADDR']."')";
	if(mysql_query($query))
	{
		//Vote added to database
		setcookie("voted".$_POST['pollid'], 'yes', time()+86400*300);
	}
	else
		echo "There was some error processing the query: ".mysql_error();
}</pre>
<p>In this case we first check to see if the answer to poll question has been provided and whether the user hasnot already voted(<em>code omitted for simplicity</em>) the selected option is there in database or not. Also here we are using <code>intval()</code> function to make sure only integer value for selected option passes through. After checking the information, the user vote is added to the <em>votes</em> table.</p>
<h4>Displaying the Results</h4>
<p>Once the user has voted, it’s time to display the results to him. We’ll be using the easy way out to display the result using CSS. Here’s the code for that.</p>
<pre>$query=mysql_query("SELECT COUNT(*) as totalvotes FROM votes WHERE option_id IN(SELECT id FROM options WHERE ques_id='$poll_id')");
while($row=mysql_fetch_assoc($query))
	$total=$row['totalvotes'];
$query=mysql_query("SELECT options.id, options.value, COUNT(*) as votes FROM votes, options WHERE votes.option_id=options.id AND votes.option_id IN(SELECT id FROM options WHERE ques_id='$poll_id') GROUP BY votes.option_id");
while($row=mysql_fetch_assoc($query)){
	$percent=round(($row['votes']*100)/$total);
	echo '&lt;div class="option" &gt;&lt;p&gt;'.$row['value'].' (&lt;em&gt;'.$percent.'%, '.$row['votes'].' votes&lt;/em&gt;)&lt;/p&gt;';
	echo '&lt;div class="bar ';
	if($_POST['poll']==$row['id']) echo ' yourvote';
	echo '" style="width: '.$percent.'%; " &gt;&lt;/div&gt;&lt;/div&gt;';
}
echo '&lt;p&gt;Total Votes: '.$total.'&lt;/p&gt;';</pre>
<p>To display the results from the information we have in <strong>votes</strong> table, we will use a <strong>GROUP BY</strong> query to find out votes per option and then set the width of display bar based on percentage of votes each option received.</p>
<p>All the PHP code is in <strong>poll.php</strong> file.</p>
<h3>HTML Structure</h3>
<p>HTML structure is quite simple as jQuery will do the heavy lifting. We only need to define a container that will hold the poll form or display the results.</p>
<pre>&lt;div id="container" &gt;
	&lt;h1&gt;User Poll&lt;/h1&gt;
	&lt;div id="pollcontainer" &gt;
	&lt;/div&gt;
	&lt;p id="loader" &gt;Loading...&lt;/p&gt;
&lt;/div&gt;</pre>
<h3>The JavaScript Code</h3>
<h4>Loading the Poll Form</h4>
<p>On page load, we will load and display the poll form to user and if user has already voted, then results will be displayed.</p>
<pre>var loader=$('#loader');
	var pollcontainer=$('#pollcontainer');
	loader.fadeIn();
	//Load the poll form
	$.get('poll.php', '', function(data, status){
		pollcontainer.html(data);
		animateResults(pollcontainer);
		pollcontainer.find('#viewresult').click(function(){
			//if user wants to see result
			loader.fadeIn();
			$.get('poll.php', 'result=1', function(data,status){
				pollcontainer.fadeOut(1000, function(){
					$(this).html(data);
					animateResults(this);
				});
				loader.fadeOut();
			});
			//prevent default behavior
			return false;
		})</pre>
<h4>Processing User Vote</h4>
<p>To process the user vote, we first check to see if user has selected one of the options and then post the form data to <strong>poll.php</strong> and then display the results to the user in a nice animated way using the function <code>animateResults</code>.</p>
<pre>('#pollform').submit(function(){
			var selected_val=$(this).find('input[name=poll]:checked').val();
			if(selected_val!=''){
				//post data only if a value is selected
				loader.fadeIn();
				$.post('poll.php', $(this).serialize(), function(data, status){
					$('#formcontainer').fadeOut(100, function(){
						$(this).html(data);
						animateResults(this);
						loader.fadeOut();
					});
				});
			}
			//prevent form default behavior
			return false;
		});</pre>
<p>Download the complete source code and try it out for yourself.</p>
<div><a href="http://demo.webdeveloperplus.com/source-code/ajax-poll.zip">Download</a></div>
<p><strong>Remember to set up database and tables using <em>polls.sql</em> file provided in source code and update database information in the <em>poll.php</em> file</strong> before trying out.</p>
<p><strong>Note:</strong> In this tutorial, i have only covered the user interface part of the user poll script. You’ll have to code the user interface for creating new polls or manually have to add questions and options in the tables. The sample database file provided with the source code contains a sample poll question along with some sample data.</p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/animation/" title="animation" rel="tag">animation</a>, <a href="http://xguiden.dk/tag/avi/" title="avi" rel="tag">avi</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/database/" title="database" rel="tag">database</a>, <a href="http://xguiden.dk/tag/fil/" title="fil" rel="tag">fil</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/html/" title="HTML" rel="tag">HTML</a>, <a href="http://xguiden.dk/tag/image/" title="image" rel="tag">image</a>, <a href="http://xguiden.dk/tag/input/" title="input" rel="tag">input</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/mysql/" title="MYSQL" rel="tag">MYSQL</a>, <a href="http://xguiden.dk/tag/over/" title="Over" rel="tag">Over</a>, <a href="http://xguiden.dk/tag/php/" title="php" rel="tag">php</a>, <a href="http://xguiden.dk/tag/png/" title="png" rel="tag">png</a>, <a href="http://xguiden.dk/tag/post/" title="POST" rel="tag">POST</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/server/" title="Server" rel="tag">Server</a>, <a href="http://xguiden.dk/tag/source/" title="Source" rel="tag">Source</a>, <a href="http://xguiden.dk/tag/start/" title="Start" rel="tag">Start</a>, <a href="http://xguiden.dk/tag/table/" title="table" rel="tag">table</a>, <a href="http://xguiden.dk/tag/tag/" title="tag" rel="tag">tag</a>, <a href="http://xguiden.dk/tag/tutorial/" title="tutorial" rel="tag">tutorial</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/13/ajax-enabled-sticky-notes-with-php-and-jquery/" title="AJAX-enabled Sticky Notes With PHP and jQuery (13/02/2010)">AJAX-enabled Sticky Notes With PHP and jQuery</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/25/php-and-mysql-file-download-counter/" title="PHP and MySQL File Download Counter (25/02/2010)">PHP and MySQL File Download Counter</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/jquery-ajax-validation-contact-form-with-modal-slide-in-transition/" title="jQuery AJAX Validation Contact Form with Modal + Slide-in Transition (13/02/2010)">jQuery AJAX Validation Contact Form with Modal + Slide-in Transition</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/" title="How to Build an Unobtrusive Login System in Rails (16/02/2010)">How to Build an Unobtrusive Login System in Rails</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/big-html-tutorial-reference/" title="Big HTML Tutorial &amp; Reference (13/02/2010)">Big HTML Tutorial &amp; Reference</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/13/ajax-user-poll-using-jquery-and-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick and Easy Way to Implement Drag n Share With jQuery</title>
		<link>http://xguiden.dk/2010/02/13/quick-and-easy-way-to-implement-drag-n-share-with-jquery/</link>
		<comments>http://xguiden.dk/2010/02/13/quick-and-easy-way-to-implement-drag-n-share-with-jquery/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 17:03:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[fil]]></category>
		<category><![CDATA[fix]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[META]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[png]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[URL]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=3765</guid>
		<description><![CDATA[
You must have seen the drag to share functionality on Mashable that lets visitors share the content on popular social networks intuitively. Just drag one of the images in an article and you’ll be able to share the article on your favorite social network by dropping the dragged image over its icon. Even, Nettuts has [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-627" title="Drag to Share with jQuery" src="http://webdeveloperplus.com/wp-content/uploads/2009/11/drag-n-share-jquery.jpg" alt="Drag to Share with jQuery" width="500" height="278" /><br />
You must have seen the drag to share functionality on <a href="http://mashable.com">Mashable</a> that lets visitors share the content on popular social networks intuitively. Just drag one of the images in an article and you’ll be able to share the article on your favorite social network by dropping the dragged image over its icon. Even, Nettuts has written a nice <a href="http://net.tutsplus.com/tutorials/javascript-ajax/drag-to-share/">tutorial</a> on how to implement this functionality into your website using jQuery. But here is a much elegant solution to achieve the drag n share effect using jQuery with just a line or two of JavaScript code.<br />
<span> </span></p>
<h3>Get the prettySociable Plugin</h3>
<p>To implement this functionality, you will need the <a href="http://www.no-margin-for-errors.com/projects/prettySociable/"><strong>prettySociable jQuery plugin</strong></a> written by Stéphane Caron. Download and extract the plugin, it contains everything you need to get up and running with drag n share.</p>
<h3>Include the Required Files</h3>
<p>To add drag n share to a page, add reference to jquery and prettySociable in your page’s <code>head</code> tag. The plugin folder also includes <em>images and css</em> folders in addition to <em>js</em> folder. You’ll need them too as <em>css</em> folder contains styles necessary for drag n share elements and <em>images</em> folder contains icons for various social networks.<br />
Here’s the complete code you need to add into the <code>head</code> tag.</p>
<pre>&lt;link rel="stylesheet" href="css/prettySociable.css" type="text/css" media="screen" charset="utf-8" /&gt;
&lt;script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;
&lt;!--[if lte IE 6]&gt;&lt;script src="js/DD_belatedPNG.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;&lt;![endif]--&gt;
&lt;script src="js/jquery.prettySociable.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;</pre>
<p>The <em>js</em> folder also includes <em>DD_belatedPNG.js</em> which is used to fix PNG transparency issues in IE6 or older. You need to include that too.</p>
<h3>Define Draggable Links</h3>
<p>Now to add drag n share to your web page, add an anchor tag <code>&lt;a href="#" &gt;</code> with another attribute <code>rel="prettySociable"</code>.</p>
<h3>Initialize prettySociable</h3>
<p>After you have added the <strong>rel</strong> attribute, you need to initialize the script. Add this single line of code, just above the <code>&lt;/body&gt;</code></p>
<pre>&lt;script type="text/javascript" charset="utf-8"&gt;
	// Init prettySociable
	$.prettySociable();
&lt;/script&gt;</pre>
<p>Check out your page in browser and you should get drag to share functionality working nicely.</p>
<h3>Customizing the Default Settings</h3>
<h4>Customizing the Shared Information</h4>
<p>When you add <strong>rel=&#8221;prettySociable&#8221;</strong> on an anchor tag with its <strong>href=&#8221;#&#8221;</strong>, this will share the URL of the current web page and use the title and meta description in <code>head</code> tag to display the tooltip on drag.</p>
<p>But if you need to share a different URL instead of the current web page, specify a URL in the <strong>href</strong> attribute. Also you can customize the tooltip information which is shown on dragging. You can specify custom title and description in the <strong>rel</strong> attribute in this way.<br />
<code>rel="prettySociable;title:custom title;excerpt:custom excerpt;"</code></p>
<h4>Customizing the Sharing Panel</h4>
<p>By default prettySociable supports eight social networks but you can customize the social networks and their icons to your requirement. For that you’ll need to pass a settings object to <em>prettySociable</em> function.</p>
<p>Here’s the complete settings object</p>
<pre>$.prettySociable({
				animationSpeed: 'fast', /* fast/slow/normal */
				opacity: 0.90, /* Value between 0 and 1 */
				share_label: 'Drag to share', /* Text displayed when a user rollover an item */
				share_on_label: 'Share on ', /* Text displayed when a user rollover a website to share */
				hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettySociable */
				hover_padding: 0,
				websites: {
					facebook : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Facebook',
						'url': 'http://www.facebook.com/share.php?u=',
						'icon':'images/prettySociable/large_icons/facebook.png',
						'sizes':{'width':70,'height':70}
					},
					twitter : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Twitter',
						'url': 'http://twitter.com/home?status=',
						'icon':'images/prettySociable/large_icons/twitter.png',
						'sizes':{'width':70,'height':70}
					},
					delicious : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Delicious',
						'url': 'http://del.icio.us/post?url=',
						'icon':'images/prettySociable/large_icons/delicious.png',
						'sizes':{'width':70,'height':70}
					},
					digg : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Digg',
						'url': 'http://digg.com/submit?phase=2&amp;amp;url=',
						'icon':'images/prettySociable/large_icons/digg.png',
						'sizes':{'width':70,'height':70}
					}
					//add more social networks here
				},
				tooltip: {
						offsetTop:0,
						offsetLeft: 10
					},
				popup: {
					width: 900,
					height: 500
				},
				callback: function(){} /* Called when prettySociable is closed */
			});</pre>
<p>The settings object is self explaining. You can specify which websites to use and also the icons to use for each website in the websites parameter.</p>
<p>You can enhance this drag n share script even further by using a shortened URL in the anchor tag’s <strong>href</strong> attribute.</p>
<p><a title="View Demo" href="http://demo.webdeveloperplus.com/drag-n-share-jquery/"><strong>View Demo</strong></a> or <a title="Download prettySociable Plugin" href="http://www.no-margin-for-errors.com/projects/prettySociable/"><strong>Download prettySociable jQuery plugin</strong></a>.</p>
<p><em>P.S.</em>: To get this script to work correctly in IE, you will need to set <strong>margin and padding values</strong> in the style-sheet for anchor elements which are draggable.</p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/animation/" title="animation" rel="tag">animation</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/fil/" title="fil" rel="tag">fil</a>, <a href="http://xguiden.dk/tag/fix/" title="fix" rel="tag">fix</a>, <a href="http://xguiden.dk/tag/flash/" title="Flash" rel="tag">Flash</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/image/" title="image" rel="tag">image</a>, <a href="http://xguiden.dk/tag/images/" title="images" rel="tag">images</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/meta/" title="META" rel="tag">META</a>, <a href="http://xguiden.dk/tag/over/" title="Over" rel="tag">Over</a>, <a href="http://xguiden.dk/tag/php/" title="php" rel="tag">php</a>, <a href="http://xguiden.dk/tag/png/" title="png" rel="tag">png</a>, <a href="http://xguiden.dk/tag/post/" title="POST" rel="tag">POST</a>, <a href="http://xguiden.dk/tag/reference/" title="reference" rel="tag">reference</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/tag/" title="tag" rel="tag">tag</a>, <a href="http://xguiden.dk/tag/text/" title="text" rel="tag">text</a>, <a href="http://xguiden.dk/tag/tutorial/" title="tutorial" rel="tag">tutorial</a>, <a href="http://xguiden.dk/tag/url/" title="URL" rel="tag">URL</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/15/how-to-code-up-a-web-design-from-psd-to-html/" title="How to Code up a Web Design from PSD to HTML (15/02/2010)">How to Code up a Web Design from PSD to HTML</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/jquery-ajax-validation-contact-form-with-modal-slide-in-transition/" title="jQuery AJAX Validation Contact Form with Modal + Slide-in Transition (13/02/2010)">jQuery AJAX Validation Contact Form with Modal + Slide-in Transition</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/animated-sharing-bar-with-jquery-and-css/" title="Animated Sharing Bar With jQuery and CSS (13/02/2010)">Animated Sharing Bar With jQuery and CSS</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/03/03/how-we%e2%80%99ll-be-building-websites-in-5-years-html5-and-css3-layout/" title="How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout (03/03/2010)">How We’ll be Building Websites in 5 years: HTML5 and CSS3 layout</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/" title="How to Build an Unobtrusive Login System in Rails (16/02/2010)">How to Build an Unobtrusive Login System in Rails</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/13/quick-and-easy-way-to-implement-drag-n-share-with-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Resize iFrame to Fit Content (Same Domain Only)</title>
		<link>http://xguiden.dk/2010/02/13/resize-iframe-to-fit-content-same-domain%c2%a0only/</link>
		<comments>http://xguiden.dk/2010/02/13/resize-iframe-to-fit-content-same-domain%c2%a0only/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 17:02:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[fix]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[iso]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Source]]></category>
		<category><![CDATA[text]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=3729</guid>
		<description><![CDATA[Normally you set and width and height for iframes. If the content inside is bigger, scrollbars have to suffice. The script below attempts to fix that by dynamically resizing the iframe to fit the content it loads.
&#60;script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'&#62;&#60;/script&#62;
&#60;script type='text/javascript'&#62; $(function(){ var iFrames = $('iframe'); function iResize() { for (var i = 0, j = [...]]]></description>
			<content:encoded><![CDATA[<p>Normally you set and width and height for iframes. If the content inside is bigger, scrollbars have to suffice. The script below attempts to fix that by dynamically resizing the iframe to fit the content it loads.</p>
<pre><code>&lt;script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'&gt;&lt;/script&gt;
&lt;script type='text/javascript'&gt; $(function(){ var iFrames = $('iframe'); function iResize() { for (var i = 0, j = iFrames.length; i &lt; j; i++) { iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';} } if ($.browser.safari || $.browser.opera) { iFrames.load(function(){ setTimeout(iResize, 0); }); for (var i = 0, j = iFrames.length; i &lt; j; i++) { var iSource = iFrames[i].src; iFrames[i].src = ''; iFrames[i].src = iSource; } } else { iFrames.load(function() { this.style.height = this.contentWindow.document.body.offsetHeight + 'px'; }); } }); &lt;/script&gt;</code></pre>
<p>Will resize an iframe like this:</p>
<pre><code>&lt;iframe src="content.html" class="iframe" scrolling="no" frameborder="0"&gt;&lt;/iframe&gt;</code></pre>
<p> </p>
<p><a rel="nofollow" href="http://css-tricks.com/examples/iFrameResize/" target="_blank">View Demo</a></p>
<h3>Still problematic…</h3>
<ol>
<li>The source of the iframe content must reside on the same domain</li>
<li>if the content inside the iframe changes height, this won’t adapt</li>
<li>I left Google Analytics code off the demo above, as when I added it in it seems to interfere and not resize the iframe, despite seemingly generating no errors.</li>
</ol>
<p><img src="http://feeds.feedburner.com/~r/CSS-TricksSnippets/~4/BcmFy5Qp1SA" alt="" width="1" height="1" /></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/fix/" title="fix" rel="tag">fix</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/html/" title="HTML" rel="tag">HTML</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/iso/" title="iso" rel="tag">iso</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/source/" title="Source" rel="tag">Source</a>, <a href="http://xguiden.dk/tag/text/" title="text" rel="tag">text</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/13/making-a-sleek-feed-widget-with-yql-jquery-and-css3/" title="Making a Sleek Feed Widget With YQL, jQuery and CSS3 (13/02/2010)">Making a Sleek Feed Widget With YQL, jQuery and CSS3</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/18/make-your-mootools-code-shorter-faster-and-stronger/" title="Make your MooTools Code Shorter, Faster, and Stronger (18/02/2010)">Make your MooTools Code Shorter, Faster, and Stronger</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/jquery-ajax-validation-contact-form-with-modal-slide-in-transition/" title="jQuery AJAX Validation Contact Form with Modal + Slide-in Transition (13/02/2010)">jQuery AJAX Validation Contact Form with Modal + Slide-in Transition</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/16/how-to-build-an-unobtrusive-login-system-in-rails/" title="How to Build an Unobtrusive Login System in Rails (16/02/2010)">How to Build an Unobtrusive Login System in Rails</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/sweet-ajax-tabs-with-jquery-1-4-and-css3/" title="Sweet AJAX Tabs With jQuery 1.4 and CSS3 (13/02/2010)">Sweet AJAX Tabs With jQuery 1.4 and CSS3</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/13/resize-iframe-to-fit-content-same-domain%c2%a0only/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scroll Page Horizontally With Mouse Wheel</title>
		<link>http://xguiden.dk/2010/02/13/scroll-page-horizontally-with-mouse%c2%a0wheel/</link>
		<comments>http://xguiden.dk/2010/02/13/scroll-page-horizontally-with-mouse%c2%a0wheel/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 17:01:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Engelske guides]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[text]]></category>

		<guid isPermaLink="false">http://xguiden.dk/?p=3731</guid>
		<description><![CDATA[1) Load jQuery and the Mouse Wheel plugin
Mouse Wheel plugin is here.
&#60;script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'&#62;&#60;/script&#62;
&#60;script type='text/javascript' src='/js/jquery.mousewheel.min.js'&#62;&#60;/script&#62;
2) Attach mousewheel event to body
The “30″ represents speed. preventDefault ensures the page won’t scroll down.
$(function() { $("body").mousewheel(function(event, delta) { this.scrollLeft -= (delta * 30); event.preventDefault(); }); });


	Tags: AJAX, CSS, GET, IP, Java, JavaScript, script, text

	Related posts
	
	Sweet AJAX Tabs With [...]]]></description>
			<content:encoded><![CDATA[<h4>1) Load jQuery and the Mouse Wheel plugin</h4>
<p>Mouse Wheel plugin <a rel="nofollow" href="http://plugins.jquery.com/project/mousewheel" target="_blank">is here</a>.</p>
<pre><code>&lt;script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'&gt;&lt;/script&gt;
&lt;script type='text/javascript' src='/js/jquery.mousewheel.min.js'&gt;&lt;/script&gt;</code></pre>
<h4>2) Attach mousewheel event to body</h4>
<p>The “30″ represents speed. preventDefault ensures the page won’t scroll down.</p>
<pre><code>$(function() { $("body").mousewheel(function(event, delta) { this.scrollLeft -= (delta * 30); event.preventDefault(); }); });</code></pre>
<p><img src="http://feeds.feedburner.com/~r/CSS-TricksSnippets/~4/uZLuLvJdzzg" alt="" width="1" height="1" /></p>

	Tags: <a href="http://xguiden.dk/tag/ajax/" title="AJAX" rel="tag">AJAX</a>, <a href="http://xguiden.dk/tag/css/" title="CSS" rel="tag">CSS</a>, <a href="http://xguiden.dk/tag/get/" title="GET" rel="tag">GET</a>, <a href="http://xguiden.dk/tag/ip/" title="IP" rel="tag">IP</a>, <a href="http://xguiden.dk/tag/java/" title="Java" rel="tag">Java</a>, <a href="http://xguiden.dk/tag/javascript/" title="JavaScript" rel="tag">JavaScript</a>, <a href="http://xguiden.dk/tag/script/" title="script" rel="tag">script</a>, <a href="http://xguiden.dk/tag/text/" title="text" rel="tag">text</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://xguiden.dk/2010/02/13/sweet-ajax-tabs-with-jquery-1-4-and-css3/" title="Sweet AJAX Tabs With jQuery 1.4 and CSS3 (13/02/2010)">Sweet AJAX Tabs With jQuery 1.4 and CSS3</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/resize-iframe-to-fit-content-same-domain%c2%a0only/" title="Resize iFrame to Fit Content (Same Domain Only) (13/02/2010)">Resize iFrame to Fit Content (Same Domain Only)</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/quick-and-easy-way-to-implement-drag-n-share-with-jquery/" title="Quick and Easy Way to Implement Drag n Share With jQuery (13/02/2010)">Quick and Easy Way to Implement Drag n Share With jQuery</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/13/making-a-sleek-feed-widget-with-yql-jquery-and-css3/" title="Making a Sleek Feed Widget With YQL, jQuery and CSS3 (13/02/2010)">Making a Sleek Feed Widget With YQL, jQuery and CSS3</a> (0)</li>
	<li><a href="http://xguiden.dk/2010/02/18/make-your-mootools-code-shorter-faster-and-stronger/" title="Make your MooTools Code Shorter, Faster, and Stronger (18/02/2010)">Make your MooTools Code Shorter, Faster, and Stronger</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://xguiden.dk/2010/02/13/scroll-page-horizontally-with-mouse%c2%a0wheel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
