<?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>Digging into WordPress &#187; JavaScript</title>
	<atom:link href="http://digwp.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://digwp.com</link>
	<description>Take your WordPress skills to the next level.</description>
	<lastBuildDate>Thu, 09 Feb 2012 19:03:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using &#8216;$&#8217; instead of &#8216;jQuery&#8217; in WordPress</title>
		<link>http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/</link>
		<comments>http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 18:57:29 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[functions.php]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=5240</guid>
		<description><![CDATA[Writing out 'jQuery' a billion times in a script makes it harder to read and bloats its size. Let's stop doing that and start writing '$' like you see in the vast majority of jQuery code in the world.]]></description>
			<content:encoded><![CDATA[<p>WordPress ships with jQuery (for longevity&#8217;s sake, as I write this WordPress is v3.2.1). To use jQuery in your plugins and themes <a href="http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/">&#8220;The Right Way&#8221;</a> all you need to do is <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script">enqueue it</a> (probably in your functions.php file):</p>
<pre><code>wp_enqueue_script("jquery");</code></pre>
<p>The tricky thing is this particular copy of jQuery is in <a href="http://docs.jquery.com/Using_jQuery_with_Other_Libraries">compatibility mode</a> by default.<span id="more-5240"></span> That means that the typical &#8216;$&#8217; shortcut for jQuery doesn&#8217;t work, so it doesn&#8217;t conflict with any other JavaScript libraries that use the dollar sign also, like MooTools or Prototype. </p>
<p>Many plugin authors and theme developers are aware of this, and they use &#8216;jQuery&#8217; instead of &#8216;$&#8217; to be safe. </p>
<pre><code>/* Normal jQuery you see everywhere */
$("#some-element").yaddaYaddaYadda();

/* "Safe" jQuery you see in WordPress */
jQuery("#some-element").yaddaYaddaYadda();</code></pre>
<p><strong>Here&#8217;s the thing&#8230; writing out &#8216;jQuery&#8217; a billion times in a script makes it harder to read and bloats its size.</strong> Let&#8217;s stop doing that. </p>
<p>If the script is being loaded in the footer (which you should be doing in the vast majority of cases) you can wrap the code in an anonymous function (technically any <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE</a>) where you pass in jQuery to be mapped to $. </p>
<pre><code>(function($) {
	
	// $ Works! You can test it with next line if you like
	// console.log($);
	
})( jQuery );</code></pre>
<p>If you absolutely need to load the scripts in the header, you&#8217;ll probably need to use a document ready function anyway, so you can just pass in $ there.</p>
<pre><code>jQuery(document).ready(function( $ ) {
	
	// $ Works! You can test it with next line if you like
	// console.log($);
	
});</code></pre>
<p>Go forth and write nice looking jQuery!</p>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/">Permalink</a> | <a href="http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/#comments">9 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/&title=Using &#8216;$&#8217; instead of &#8216;jQuery&#8217; in WordPress">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/functions-php/" rel="tag">functions.php</a>, <a href="http://digwp.com/tag/jquery/" rel="tag">jquery</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Ajax Requested Page Return Only Content</title>
		<link>http://digwp.com/2011/02/ajax-requested-page-return-only-content/</link>
		<comments>http://digwp.com/2011/02/ajax-requested-page-return-only-content/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 15:42:32 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[pages]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=3623</guid>
		<description><![CDATA[I posted a little tip on CSS-Tricks the other day about how you can load only parts of other pages on a site via Ajax, and how to do that without needing additional HTML wrapping elements to keep it clean. A common criticism of this is that the Ajax request still loads the entire page, [...]]]></description>
			<content:encoded><![CDATA[<p>I posted <a href="http://css-tricks.com/ajax-load-container-contents/">a little tip</a> on CSS-Tricks the other day about how you can load only parts of other pages on a site via Ajax, and how to do that without needing additional HTML wrapping elements to keep it clean. A common criticism of this is that the Ajax request still loads the entire page, using all that bandwidth, it&#8217;s just that it only places onto the page the part you specify via CSS selector.</p>
<p>Sometimes it&#8217;s hard to have discussions like this without looking at specific use case, but I see where they are coming from. Loading content you aren&#8217;t going to use is a waste of bandwidth. It does make progressive Ajax enhancements a lot easier though. And in fact, that&#8217;s how the ALL AJAX theme here on this site works. </p>
<p>This had me thinking though&#8230; if WordPress pages could be smart enough to know if they are being requested normally or via Ajax, they could return only the appropriate content. <span id="more-3623"></span> Turns out <a href="http://davidwalsh.name/detect-ajax">PHP can detect this</a>. So here is the basic idea:</p>
<pre><code>&lt;?php 

/* Page template, or single.php, or any other typical 
    theme file in charge of displaying a whole page */

the_post();

/* Ajax check  */
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { ?&gt;

  /* This is Ajax: Return ONLY content */
  &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;
  &lt;?php the_content(); ?&gt;

&lt;?php } else { ?&gt;

  /* Normal request: Return everything (header, sidebar, content, etc) */

  &lt;?php get_header(); ?&gt;

  &lt;section id="main-content"&gt;
  	&lt;article class="post" id="post-&lt;?php the_ID(); ?&gt;"&gt;
  		&lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;
  		&lt;?php the_content(); ?&gt;
  	&lt;/article&gt;
  &lt;/section&gt;

  &lt;?php get_sidebar(); ?&gt;
  &lt;?php get_footer(); ?&gt;

&lt;?php } ?&gt;</code></pre>
<p>I haven&#8217;t tested this but it seems like a reasonable solution to me. Anyone have any experience trying something like this?</p>
<hr />
<p><small>© 2011 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2011/02/ajax-requested-page-return-only-content/">Permalink</a> | <a href="http://digwp.com/2011/02/ajax-requested-page-return-only-content/#comments">16 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2011/02/ajax-requested-page-return-only-content/&title=Ajax Requested Page Return Only Content">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/ajax/" rel="tag">ajax</a>, <a href="http://digwp.com/tag/pages/" rel="tag">pages</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2011/02/ajax-requested-page-return-only-content/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Dynamic Archives</title>
		<link>http://digwp.com/2010/10/dynamic-archives/</link>
		<comments>http://digwp.com/2010/10/dynamic-archives/#comments</comments>
		<pubDate>Fri, 29 Oct 2010 17:29:59 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[archives]]></category>
		<category><![CDATA[dropdown]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=3063</guid>
		<description><![CDATA[Have you ever seen WordPress archives where you select something (usually a month/year) from a dropdown and it takes you to a page where you can view that? It&#8217;s fairly common. WordPress almost has built in functionality for it, since you can specifically tell the wp_get_archives() function that you want the values to be returned [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever seen WordPress archives where you select something (usually a month/year) from a dropdown and it takes you to a page where you can view that? It&#8217;s fairly common. WordPress almost has built in functionality for it, since you can specifically tell the wp_get_archives() function that you want the values to be returned as <code>&lt;option&gt;</code>s. We can kick it up a notch though, and make the results show dynamically on the same page as the dropdowns through some Ajaxy JavaScript. We&#8217;ll even allow for multiple dropdowns (include the category as well) and make sure it&#8217;s flexible for your own alterations.</p>
<p><a href="http://digwp.com/archives/" class="button">View Demo</a></p>
<p><span id="more-3063"></span></p>
<div class="image-wrap">
<img src="http://digwp.com/wp-content/uploads/archives.png" alt="" title="archives" width="590"  class="alignnone size-full wp-image-3069" />
</div>
<h3>Step 1) Building the Dropdowns</h3>
<p>The dropdowns are pretty easy to create. Here I&#8217;ll make a div wrapper for both of them, then include a dropdown for month/year, and for category:</p>
<pre><code>&lt;div id="archive-browser"&gt;
	&lt;div&gt;
		&lt;h4&gt;Month&lt;/h4&gt;
		&lt;select id="month-choice"&gt;
			&lt;option val="no-choice"&gt; &amp;mdash; &lt;/option&gt;
			&lt;?php wp_get_archives(array(
			
				'type'    =&gt; 'monthly',
				'format'  =&gt; 'option'
			
			)); ?&gt;
		&lt;/select&gt;
	&lt;/div&gt;
	&lt;div&gt;
		&lt;h4&gt;Category&lt;/h4&gt;
		&lt;?php 

			wp_dropdown_categories('show_option_none= -- ');
					
		?&gt; 
	&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>Note that the WordPress functions for the two dropdowns are a bit different. wp_get_archives requires you to bring your own select wrapper, which wp_dropdown_categories does not. For the former, you&#8217;ll also need to include your own &#8220;no-choice&#8221; option. I&#8217;m sure the WordPress gang has their reasons for this kind of thing, but I&#8217;d prefer to see it standardized over time. </p>
<h3>Step 2) Let&#8217;s get ourselves a getter.php</h3>
<p>We&#8217;re going to be dynamically grabbing our archives and plunking them on the screen. That means JavaScript, and as usual with me, that means jQuery. But jQuery can&#8217;t do a WordPress query all by itself. JavaScript is a client-side technology and database stuff is a server-side activity. So we&#8217;re going to need an intermediary. A URL that our JavaScript can call to return to us exactly what we need. That&#8217;s what I&#8217;m calling a getter.php file. </p>
<p>Since we&#8217;re working with WordPress here, a great way to do this is to create a template of what we need, then publish a page using that template. That gives us a nice URL we can hit. So in our active theme, I have greated a file called &#8220;archive-getter.php&#8221;, and this is that code:</p>
<pre><code>&lt;?php

    /*
        Template Name: Archives Getter
    */
    
    $year = htmlspecialchars(trim($_POST['digwp_y']));
    $month = htmlspecialchars(trim($_POST['digwp_m']));
    $cat = htmlspecialchars(trim($_POST['digwp_c']));
    
    $querystring = "year=$year&amp;monthnum=$month&amp;cat=$cat&amp;posts_per_page=-1";
    
    query_posts($querystring); 
    
?&gt;

&lt;?php if (($year == '') &amp;&amp; ($month == '') &amp;&amp; ($cat == '-1')) { ?&gt;

	&lt;table id="archives-table"&gt;&lt;tr&gt;&lt;td style='text-align: center; font-size: 15px; padding: 5px;'&gt;Please choose from above.&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
	
&lt;?php } else { ?&gt;

	&lt;table id="archives-table"&gt;
	    &lt;?php    
	        if (have_posts()) : while (have_posts()) : the_post(); ?&gt;
	            &lt;tr&gt;
	            	&lt;td&gt;&lt;img src="&lt;?php echo get_post_meta($post-&gt;ID, 'PostThumb', true); ?&gt;" alt="" style="width: 35px;" /&gt;&lt;/td&gt;
	            	&lt;td&gt;&lt;a href='&lt;?php the_permalink(); ?&gt;'&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/td&gt;
	            	&lt;td&gt;&lt;?php comments_popup_link(' ', '1 Comment', '% Comments'); ?&gt;&lt;/td&gt;
	            	&lt;td&gt;&lt;?php the_date('m/j/Y'); ?&gt;&lt;/td&gt;
	            &lt;/tr&gt;
	    &lt;?php 
	        endwhile; else:
	        
	        	echo "&lt;tr&gt;&lt;td style='text-align: center; font-size: 15px; padding: 5px;'&gt;Nothing found.&lt;/td&gt;&lt;/tr&gt;";
	        
	        endif; 
	    ?&gt;
	&lt;/table&gt;

&lt;?php } ?&gt;</code></pre>
<p>Let&#8217;s go through it top to bottom:</p>
<ol>
<li>Special comment to tell WordPress this is an Template file</li>
<li>Set variables from three POST parameters. Clean them up in the process</li>
<li>Create a $query string in the format WordPress likes them in</li>
<li>Run a query_posts from that query string</li>
<li>If none of the variables are set, return a message telling the user to please select values.</li>
<li>If at least one variable is set&#8230;</li>
<li>Run &#8220;The Loop&#8221;</li>
<li>Output a table of the results, containing the post image, content, date, comments, etc.</li>
<li>If nothing is found, tell the user so</li>
</ol>
<h3>Step 3) Watching for Dropdown Menu Changes</h3>
<p>We&#8217;re going to be using jQuery, so <a href="http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/">make sure jQuery is loaded in your theme</a>. Then we&#8217;ll need a JavaScript file from which to work. So I&#8217;ve created a file called archives.js in the js folder of my theme. I similarly made a CSS file for styling this, and then conditionally load both of them in the header.php file:</p>
<pre><code>&lt;?php if (is_page_template("archives.php")) { ?&gt;
   &lt;link rel="stylesheet" href="&lt;?php bloginfo('template_url'); ?&gt;/css/archives.css" type="text/css" /&gt;
   &lt;script src="&lt;?php bloginfo('template_url'); ?&gt;/js/archives.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;?php } ?&gt;</code></pre>
<p>Now that we have a working JavaScript enviornment, we can watch those select dropdown menus we built for changes:</p>
<pre><code>jQuery(function() {
  jQuery("#archive-browser select").change(function() {
     // dynamically load the archives
  });
});</code></pre>
<h3>Step 4) Dynamically Load New Archives</h3>
<p>Using the great base we already have going here, let&#8217;s write out all the code we need to dynamically load in those archives. One thing we haven&#8217;t covered yet is, where on the page do we load in these said archives? We&#8217;ll need a target. We could append it with JavaScript, but what they hey, I just stuck it into the template itself instead:</p>
<div id="archive-wrapper">
<div id='archive-pot'></div>
</div>
<p>The <code>#archive-pot</code> is where we&#8217;ll load in new markup as we get it. The wrapper is there because that way we can dynamically adjust the height and do it really nice and smoothly.</p>
<p>Now here&#8217;s the complete JavaScript:</p>
<pre><code>jQuery(function() {

	jQuery("#archive-wrapper").height(jQuery("#archive-pot").height());

	jQuery("#archive-browser select").change(function() {
	
		jQuery("#archive-pot")
			.empty()
			.html("&lt;div style='text-align: center; padding: 30px;'&gt;&lt;img src='/wp-content/themes/DiggingIntoWordPress-2/images/ajax-loader.gif' /&gt;&lt;/div&gt;");
	
		var dateArray = jQuery("#month-choice").val().split("/");
		var y = dateArray[3];
		var m = dateArray[4];
		var c = jQuery("#cat").val();
		
		jQuery.ajax({
		
			url: "/archives-getter/",
			dataType: "html",
			type: "POST",
			data: ({
				"digwp_y": y,
				"digwp_m" : m,
				"digwp_c" : c
			}),
			success: function(data) {
				jQuery("#archive-pot").html(data);
				
				jQuery("#archive-wrapper").animate({
					height: jQuery("#archives-table tr").length * 50
				});
			
			}
			
		});
			
	});

});</code></pre>
<ol>
<li>Set height of wrapper to height of inside. Seems weird, but now that the wrapper has a static height and hidden overflow, it won&#8217;t blast open when new content is added, we can animate it&#8217;s heigh accordingly.</li>
<li>Watch for dropdown changes</li>
<li>When a change happens, empty out the current showing archives and add an Ajax spinner graphic</li>
<li>Figure out the year and date that we need by tinkering with the default WordPress values in the <code>&lt;option&gt;</code></li>
<li>Grab the selected category</li>
<li>Launch an Ajax request to our getter file, POSTING the values we just collected</li>
<li>Upon success, drop the markup into the #archive-pot</li>
<li>Animate the wrapper to the new height needed</li>
</ol>
<h3>Little Important Note</h3>
<p>Notice how the data that we POST is prefixed with &#8220;digwp_&#8221;? I had a little brainbender on this, while I was trying to POST data as like &#8220;m&#8221; and &#8220;month&#8221; and things like that. Apparently WordPress doesn&#8217;t like that. It can 404 an otherwise perfectly good URL for you when you pass it parameters (GET or POST) in that format. <a href="http://digwp.com/?m=2007&#038;y=3849&#038;cat=w34we">Check it out</a>. So anyway, using your own prefixed parameters will save you that headache.</p>
<h3>Taking it further</h3>
<p>This is by no means limited to what we have done here. All were are doing it passing a getter file parameters that we want built into a query string. We could make checkboxes so you could pick multiple categories. We could include authors. We could include tags. The sky is the limit really.</p>
<h3>Demo</h3>
<p>I just did it right on this site, so you can see <a href="http://digwp.com/archives/">our own archives</a>.</p>
<hr />
<p><small>© 2010 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2010/10/dynamic-archives/">Permalink</a> | <a href="http://digwp.com/2010/10/dynamic-archives/#comments">23 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2010/10/dynamic-archives/&title=Dynamic Archives">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/archives/" rel="tag">archives</a>, <a href="http://digwp.com/tag/dropdown/" rel="tag">dropdown</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2010/10/dynamic-archives/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Make an Infinite More-Posts Section</title>
		<link>http://digwp.com/2009/11/make-an-infinite-more-posts-section/</link>
		<comments>http://digwp.com/2009/11/make-an-infinite-more-posts-section/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 20:32:23 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[pages]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=949</guid>
		<description><![CDATA[The goal here is to make a list of posts in the sidebar that show a number of recent posts. There will be a button you can click which will replaces those links to recent posts with older posts, AJAX style. You can keep clicking the button and keep getting older and older posts. On [...]]]></description>
			<content:encoded><![CDATA[<p>The goal here is to make a list of posts in the sidebar that show a number of recent posts. There will be a button you can click which will replaces those links to recent posts with older posts, AJAX style. You can keep clicking the button and keep getting older and older posts. On this site, we currently show 5 recent posts. So this little section shows the 5 posts <em>after that</em>, then clicking the button once will show 5 more older than that, and so on. </p>
<p><span id="more-949"></span></p>
<h3>1. Create a Page Template for &#8220;Additional Posts&#8221;</h3>
<p>All this page template does is display a list of 5 posts. Totally raw and unstyled. No DOCTYPE, no footer, no nothing.</p>
<pre><code>&lt;?php
    /*
        Template Name: Additional Posts
    */
        
    $offset = htmlspecialchars(trim($_GET['offset']));
    if ($offset == '') {
        $offset = 5;
    }
   
    query_posts('showposts=5&amp;offset='.$offset); 
?&gt;

&lt;ul&gt;
    &lt;?php    
        if (have_posts()) : while (have_posts()) : the_post(); ?&gt;
            &lt;li&gt;&lt;a href='&lt;?php the_permalink(); ?&gt;'&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;?php 
        endwhile; endif; 
    ?&gt;
&lt;/ul&gt;</code></pre>
<p>The only thing special about this template is that it pulls down the URL parameter &#8220;offset&#8221; and scrubs it. The query_posts function will use that offset number to return posts older than that number.</p>
<h3>2. Make sure jQuery is loaded.</h3>
<p>We&#8217;re going to use the powers of jQuery to do this, so make sure it&#8217;s loaded. Here is a simple way to get that done, make sure this is above the wp_head() function.</p>
<pre><code>&lt;?php wp_enqueue_script('jquery'); ?&gt;</code></pre>
<p>I often like to load it directly from Google. To do that, <a href="http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/">see here.</a></p>
<h3>3. Make a new script (or append to your already exisiting script)</h3>
<p>We&#8217;re going to write a little JavaScript here, so this is where we&#8217;ll do that. Call this AFTER the wp_head() call so it will surely run after jQuery is loaded.</p>
<pre><code>&lt;script type="text/javascript" src="&lt;?php bloginfo('template_url') ?&gt;/js/YOUR-SCRIPT.js"&gt;&lt;/script&gt;</code></pre>
<h3>4. Make a home for the list of posts</h3>
<p>On our site, we are putting this in our sidebar (sidebar.php file). </p>
<pre><code>&lt;h4&gt;More Posts&lt;/h4&gt;
&lt;div id="postContainer"&gt;... loading ...&lt;/div&gt;
&lt;p&gt;&lt;a href="#" id="another"&gt;Get more!&lt;/a&gt;&lt;/p&gt;</code></pre>
<p>The #postContainer div will be the target for loading up the new list of articles. The #another link will have a click handler tied to it which will trigger the AJAX load.</p>
<h3>5. Create a new page with your new page template</h3>
<p>Go ahead and publish a new page. It doesn&#8217;t matter what the title is, just select your new page template from the page template dropdown menu. Click the View button to make sure it loads up a list of posts OK. Note the URL of this page.</p>
<h3>6. Write JavaScript to do AJAX load</h3>
<p>We&#8217;ll put jQuery in noConflict mode here just to be super safe.</p>
<pre><code>var $j = jQuery.noConflict(); 

$j(function(){

    var offset = 5;

    $j("#postContainer").load("/additional-posts/?offset="+offset);
    $j("#another").click(function(){
        
        offset = offset+5;
    
        $j("#postContainer")
            .slideUp()
            .load("/additional-posts/?offset="+offset, function() {
                $j(this).slideDown();
            });
            
        return false;
    });

});</code></pre>
<p>In plain English:</p>
<ol>
<li>When the DOM is ready&#8230;</li>
<li>Set variable offset to 5</li>
<li>Load the contents of the URL /additional-posts/?offset=5 into the element with ID postContainer</li>
<li>When the &#8220;more&#8221; button is clicked&#8230;</li>
<li>Increment the offset variable by 5</li>
<li>Slide up the container</li>
<li>Load the URL again, with a new offset parameter</li>
<li>When done, slide the container back down</li>
</ol>
<h3>That&#8217;s it!</h3>
<p>For a demo, check out our current sidebar on <a href="http://digwp.com">Digging Into WordPress</a>. Thanks to Erik Lundmark for the idea.</p>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/11/make-an-infinite-more-posts-section/">Permalink</a> | <a href="http://digwp.com/2009/11/make-an-infinite-more-posts-section/#comments">9 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/11/make-an-infinite-more-posts-section/&title=Make an Infinite More-Posts Section">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/jquery/" rel="tag">jquery</a>, <a href="http://digwp.com/tag/pages/" rel="tag">pages</a>, <a href="http://digwp.com/tag/php/" rel="tag">PHP</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/11/make-an-infinite-more-posts-section/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Integrating Fading Button Navigation</title>
		<link>http://digwp.com/2009/09/integrating-fading-button-navigation/</link>
		<comments>http://digwp.com/2009/09/integrating-fading-button-navigation/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 12:32:58 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[button]]></category>
		<category><![CDATA[pages]]></category>
		<category><![CDATA[Theme]]></category>

		<guid isPermaLink="false">http://digwp.com/?p=760</guid>
		<description><![CDATA[I was talking with Darren Hoyt recently about building a better interactive button. The goal of the button was to provide three states: regular, hover, and active (pressed). That is standard of any good button, but we were going to integrate some fading effects into it to really making the button satisfying to interact with. [...]]]></description>
			<content:encoded><![CDATA[<p>I was talking with Darren Hoyt recently about <a href="http://www.darrenhoyt.com/2009/09/20/better-button-and-nav-interactions/">building a better interactive button</a>. The goal of the button was to provide three states: regular, hover, and active (pressed). That is standard of any good button, but we were going to integrate some fading effects into it to really making the button satisfying to interact with. <a href="http://digwp.com/examples/FadingButtonNav/">Here is a demo</a>, and now we are going to show you how to integrate it into WordPress.</p>
<p><span id="more-760"></span></p>
<p>I&#8217;ve said (loudly) before, that <a href="http://digwp.com/2009/08/will-this-work-with-wordpress/">yes, this will work with WordPress</a>. I wasn&#8217;t referring to anything in particular, but just any old technique. WordPress doesn&#8217;t care what you use within it. Any ol&#8217; jQuery plugin you can find will work just fine. This time, I&#8217;m going to walk through the process. It will be specific to this technique, but this series of steps can be applied to incorporating just about any other JavaScript &#8220;thingy&#8221; you find and want to use on the web.</p>
<h3>What do we have here?</h3>
<ol>
<li><strong>Markup</strong> &#8211; we have some HTML that needs to be in place for the menu to work.</li>
<li><strong>CSS</strong> &#8211; we have some CSS in place that the markup needs</li>
<li><strong>Images</strong> &#8211; where should they go?</li>
<li><strong>jQuery dependency</strong> &#8211; this technique is going to rely on jQuery, so we need to ensure that is available</li>
<li><strong>jQuery plugin</strong> &#8211; we need a particular plugin loaded that our buttons will use</li>
<li><strong>Script</strong> &#8211; we have our own JavaScript we need to run</li>
</ol>
<p>We&#8217;d better just take this bit by bit.</p>
<h3>1. Markup</h3>
<p>Like any good semantic navigation markup, we&#8217;re shooting for markup like this:</p>
<pre><code>&lt;ul id="nav"&gt;
   &lt;li&gt;&lt;a href="#"&gt;Take a Tour&lt;/a&gt;&lt;/li&gt;
   &lt;li&gt;&lt;a href="#"&gt;Contact Us&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</code></pre>
<p>That is hard-coded though, and that&#8217;s no good. With WordPress, we can have this navigation be dynamic easily, by using a function to create it instead. Assuming this navigation is going to be a list of pages, we&#8217;ll use the appropriate function:</p>
<pre><code>&lt;ul id="nav"&gt;
   &lt;?php wp_list_pages("title_li=");
&lt;/ul&gt;</code></pre>
<p>This function can be customized a ton, so check the Codex if you need to add pages, exclude pages, only go one level deep, etc. </p>
<h3>2. CSS</h3>
<p>We have some CSS that makes this menu look the way it does:</p>
<pre><code>#nav {
    list-style: none;
}

#nav li  {
    display: inline; 
}

#nav li a {
	display: block;
	padding: 10px 0;
	text-decoration: none;
	width: 200px;
	text-align: center;
	text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.8);
	font-weight: bold;
	text-transform: uppercase;
	color: #FFF;
	font: bold .8em 'Lucida Grande',Arial;
	background:	#90b339 url(../images/button-bg.png) 0 -183px repeat-x;
	-moz-border-radius: 5px;  
 	-webkit-border-radius: 5px;
 	border: 1px solid #608925;
	float: left;
	margin: 0 10px 10px 0;
}</code></pre>
<p>Now we need to consider where this CSS is needed. Is this going to be shown on every page of the site? If yes, then it should go into the main CSS that your theme <em>already uses</em>. Loading an additional CSS file just for this is probably overkill. If this is special navigation only being used on one (or very few) pages on the site, then you probably should <em>not</em> put it in the main stylesheet, but leave it seperate and load that CSS file with <a href="http://codex.wordpress.org/Conditional_Tags">conditional tags</a> in your header.</p>
<h3>3. Images</h3>
<p>We need images for our button. Obviously in WordPress we have &#8220;themes&#8221;. Navigation is definitely a part of a theme, so the images belong there. If you are blogging, and you use photos in your articles, I&#8217;d argue those images don&#8217;t belong in your theme images folder but in an images folder in the root. Those aren&#8217;t dependent on the current theme of your blog, whereas something like navigation is. </p>
<p>There is probably already an images folder in your theme folder, so put the images in there. If not, make one and put them in that. In the previous step, we referenced a background image on our anchor links. Notice the URL began with &#8220;../&#8221;. That is the relative path <em>from the CSS file to the image file</em>. If the CSS for your theme is also in a subdirectory in your theme (e.g. a &#8220;css&#8221; folder), then starting with the dot-dot-slash to back up one directory first makes sense. If your CSS is laying straight in your theme folder, just start the reference to that image with &#8220;images/&#8221;.</p>
<p>In this demo, we use a single image with a gradient. This is an efficient way to go about the technique, as all we do is shift the image up and down to accomplish the different states of the button. </p>
<p><img src="http://digwp.com/wp-content/blog-images/button-bg.png" width="50" height="400" alt="" title="" /></p>
<h3>4. jQuery Dependency</h3>
<p>All we need to do here is <a href="http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/">make sure that jQuery is loaded</a>. Do not hard-code a new direct link to jQuery. As the article linked to above goes into, you need to let WordPress know you are using a JavaScript library so that other stuff that also intends to use it doesn&#8217;t go and load their own copy too and cause conflicts. In short: do this before your wp_head(); hook:</p>
<pre><code>&lt;?php wp_enqueue_script("jquery"); ?&gt;</code></pre>
<h3>5. jQuery Plugin</h3>
<p>Now we need to link up a plugin file that isn&#8217;t bundled with WordPress. Technically you can use <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script">wp_enqueue_script</a> here as well, but the benefits to doing so this time are pretty minimal since no naming convention exists for every obscure plugin out there. In this case, just toss the plugin file in a &#8220;js&#8221; folder inside your theme and link it up like this:</p>
<pre><code>&lt;script type='text/javascript' src='&lt;?php bloginfo('stylesheet_directory'); ?&gt;/js/plugin.js'&gt;&lt;/script&gt;</code></pre>
<p>In our case, we&#8217;ll be using the <a href="http://plugins.jquery.com/project/backgroundPosition-Effect">background position plugin for jQuery</a> to accomplish part of the effect.</p>
<h3>6. Custom Script</h3>
<p>Now we are in a position just like we were with the CSS. Is there some script file that is already running on every page of the site? And is this menu going to be running on every page of the site? If yes, then you can drop the JavaScript into <em>that file</em>, to keep things clean and not load up another file. If there isn&#8217;t any JavaScript yet, you can link up your script just like we loaded the plugin:</p>
<pre><code>&lt;script type='text/javascript' src='&lt;?php bloginfo('stylesheet_directory'); ?&gt;/js/script.js'&gt;&lt;/script&gt;</code></pre>
<p>For our button, we are doing some pretty simple stuff. We are going to shift the background position of the gradient image a bit, to give it a subtle rollover effect. Then we&#8217;ll use the mousedown event to simulate the &#8220;active&#8221; state:</p>
<pre><code>$(function(){
	
	$("#nav li a")
		.hover(function(){
			$(this).animate({
				backgroundPosition: "0 -140px"
			}, 100)
		}, function() {
			$(this).animate({
				backgroundPosition: "0 -183px"
			}, 100)
		})
		.mousedown(function(){
			$(this).css({
				backgroundPosition: "0 -220px"
			})	
		});
	
});</code></pre>
<h3>We Made It!</h3>
<p>So that covers the theory of installing an already-existing demo into a WordPress site. In short, you need to break apart what is provided and figure out the best place to put or recreate all the parts in the smartest way. And again, check out Darren Hoyt&#8217;s blog for the origin of this <a href="http://www.darrenhoyt.com/2009/09/20/better-button-and-nav-interactions/">button technique</a>.</p>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/09/integrating-fading-button-navigation/">Permalink</a> | <a href="http://digwp.com/2009/09/integrating-fading-button-navigation/#comments">19 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/09/integrating-fading-button-navigation/&title=Integrating Fading Button Navigation">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/button/" rel="tag">button</a>, <a href="http://digwp.com/tag/pages/" rel="tag">pages</a>, <a href="http://digwp.com/tag/theme/" rel="tag">Theme</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/09/integrating-fading-button-navigation/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Display a Random Post (with AJAX Refresh)</title>
		<link>http://digwp.com/2009/07/display-a-random-post-with-ajax-refresh/</link>
		<comments>http://digwp.com/2009/07/display-a-random-post-with-ajax-refresh/#comments</comments>
		<pubDate>Mon, 20 Jul 2009 12:43:32 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://diggingintowordpress.com/?p=334</guid>
		<description><![CDATA[I think you&#8217;ll be surprised at how ridiculously easy this is. We are going to leverage some serious smartness from both WordPress and from the JavaScript library jQuery. 1. Set up area for Random Post (HTML) This could be anything really, just so long as it is a text page element with an ID you [...]]]></description>
			<content:encoded><![CDATA[<p>I think you&#8217;ll be surprised at how ridiculously easy this is. We are going to leverage some serious smartness from both WordPress and from the JavaScript library jQuery.</p>
<h3>1. Set up area for Random Post (HTML)</h3>
<p>This could be anything really, just so long as it is a text page element with an ID you can target. I put this in our <code>sidebar.php</code>.</p>
<pre><code>&lt;h4&gt;Random Post&lt;/h4&gt;
&lt;ul&gt;
	&lt;li id="randomPost"&gt;... loading ...&lt;/li&gt;
&lt;/ul&gt;
&lt;a href="#" id="another"&gt;Get another!&lt;/a&gt;</code></pre>
<p><span id="more-334"></span></p>
<h3>2. Create a new Page template</h3>
<p>The sole purpose for this page template is to query the posts and display one random post. Look how easy:</p>
<pre><code>&lt;?php
/*
Template Name: Random Post
*/
?&gt;

&lt;?php 
    query_posts('showposts=1&amp;orderby=rand'); 
    the_post();
?&gt;

&lt;a href='&lt;?php the_permalink(); ?&gt;'&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;</code></pre>
<h3>3. Publish a Page using this template</h3>
<p>Could be anywhere you want. On this blog it&#8217;s at <a href="http://digwp.com/random/">/random/</a>.</p>
<h3>4. The jQuery</h3>
<p>You&#8217;ll need jQuery loaded and a link to your own custom script going, then add this:</p>
<pre><code>$("#randomPost").load("/random/");
$("#another").click(function(){
   $("#randomPost")
            .text("... loading ...")
            .load("/random/");
   return false;
});</code></pre>
<h3>5. Rejoice</h3>
<p>I told you it would be easy! Check out our sidebar for a live example.</p>
<h3>UPDATE</h3>
<p>The above doesn&#8217;t work as written in Internet Explorer, which likes to cache AJAX requests. To fight this, just append a random URL parameter to the end of the load URL.  Like so:</p>
<pre><code>$("#another").click(function(){
   $("#randomPost")
            .text("... loading ...")
            .load("/random/?cachebuster=" + Math.floor(Math.random()*10001));
   return false;
});</code></pre>
<p>Thanks to Andy for this fix, who is using it on <a href="#" title="Edit: Page Not Found for http://sayitwrong.com/app/">this web app</a>. </p>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/07/display-a-random-post-with-ajax-refresh/">Permalink</a> | <a href="http://digwp.com/2009/07/display-a-random-post-with-ajax-refresh/#comments">18 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/07/display-a-random-post-with-ajax-refresh/&title=Display a Random Post (with AJAX Refresh)">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/php/" rel="tag">PHP</a>, <a href="http://digwp.com/tag/tricks/" rel="tag">tricks</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/07/display-a-random-post-with-ajax-refresh/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Making an Expanding Code Box</title>
		<link>http://digwp.com/2009/07/making-an-expanding-code-box/</link>
		<comments>http://digwp.com/2009/07/making-an-expanding-code-box/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 15:49:56 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://diggingintowordpress.com/?p=142</guid>
		<description><![CDATA[On blogs that like to share snippets of code like this one, it is common to use the &#60;pre&#62; tag to wrap the code so that the spacing/indenting is maintained and long lines do not wrap. While this is desirable behavior, it can be undesirable to have those un-wrapped lines break out of their containers [...]]]></description>
			<content:encoded><![CDATA[<p>On blogs that like to share snippets of code like this one, it is common to use the &lt;pre&gt; tag to wrap the code so that the spacing/indenting is maintained and long lines do not wrap. While this is desirable behavior, it can be undesirable to have those un-wrapped lines break out of their containers awkwardly and overlap other content.</p>
<p>On Digging Into WordPress, we use JavaScript (jQuery) to solve this problem. One solution could potentially be to use only CSS and expand the width with something like <tt>pre:hover</tt>, but JavaScript is more elegant:</p>
<ul>
<li>Expands only when needed</li>
<li>Expands only to as wide as needed</li>
<li>Expands with animation</li>
</ul>
<p><img src="http://digwp.com/wp-content/blog-images/boxgrow.png" width="590" height="200" alt="" title="" /></p>
<p><span id="more-142"></span></p>
<h3>The CSS</h3>
<p>The &lt;pre&gt; tag is naturally block-level, so this is what we&#8217;ll use to style our code blocks and hide the overflow.</p>
<pre><code>pre { 
  background: #eee; 
  padding: 10px; 
  border: 2px solid #c94a29; 
  overflow: hidden;
  margin: 0 0 15px 0; 
  width: 563px; 
  font-family: Courier, Monospace;
}</code></pre>
<h3>The jQuery</h3>
<p>The real trick here is that the code blocks are wrapped not only in &lt;pre&gt; tags but also in &lt;code&gt; tags. The code may ultimately get cut off by the pre block, but that inner code tag still has a natural width that can be measured by JavaScript. Here is the logic:</p>
<ol>
<li>When a pre block is hovered&#8230;</li>
<li>Measure the internal code blocks width</li>
<li>If that width is wider than the pre block&#8230;</li>
<li>Expand the pre block to be wide enough to accommodate</li>
<li>On mouseOut, return the pre block to its original size</li>
</ol>
<pre><code>$j("pre").hover(function() {
	var codeInnerWidth = $j("code", this).width() + 10;
    if (codeInnerWidth &gt; 563) {
		$j(this)
			.stop(true, false)
			.css({
				zIndex: "100",
				position: "relative"
			})
			.animate({
				width: codeInnerWidth + "px"
			});
		}
	}, function() {
			$j(this).stop(true, false).animate({
				width: 563
		});
	});</code></pre>
<p>Couple of things of note here. The &#8220;codeInnerWidth&#8221; is calculated on every hover, because different blocks will have different inner widths. The width of the pre blocks are hard-coded though. Calculating that on every hover leads to problems like fast mouse-in-mouse-outs expanding the box and re-calculating it&#8217;s size to be larger than it was originally. The <code>stop</code> function prevents queuing up of animations. Also note the $j being used is just because we are using jQuery in <code>noConflict</code> mode:</p>
<pre><code>var $j = jQuery.noConflict(); </code></pre>
<h3>Demo</h3>
<p>None of the code blocks so far have been long enough for you to see it in action, so here is a demo block (RSS readers, obviously you need to see this on our site to see it work).</p>
<pre><code>This is a really long line of code that is even longer than the world super-cala-frag-alistic-espee-ala-dosis</code></pre>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/07/making-an-expanding-code-box/">Permalink</a> | <a href="http://digwp.com/2009/07/making-an-expanding-code-box/#comments">25 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/07/making-an-expanding-code-box/&title=Making an Expanding Code Box">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/javascript/" rel="tag">JavaScript</a>, <a href="http://digwp.com/tag/jquery/" rel="tag">jquery</a>, <a href="http://digwp.com/tag/tricks/" rel="tag">tricks</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/07/making-an-expanding-code-box/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Use Google-Hosted JavaScript Libraries (&#8230;still the Right Way)</title>
		<link>http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/</link>
		<comments>http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 21:05:04 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[header]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://diggingintowordpress.com/?p=136</guid>
		<description><![CDATA[I previously posted on how to include jQuery in your WordPress theme the Right Way. That is, to use the wp_register_script function to register the script first. It&#8217;s literally a one-liner in your header.php or functions.php file, but by default, it loads the internal version of jQuery that ships with WordPress. It&#8217;s all the rage [...]]]></description>
			<content:encoded><![CDATA[<p>I <a href="http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/">previously posted</a> on how to include jQuery in your WordPress theme the Right Way. That is, to use the <code>wp_register_script</code> function to register the script first. It&#8217;s literally a one-liner in your header.php or functions.php file, but by default, it loads the internal version of jQuery that ships with WordPress. </p>
<p>It&#8217;s all the rage these days (for good reason), to use Google-hosted JavaScript libraries. They even encourage it. If you&#8217;d like to hop on the bandwagon, you can do so and still use the proper <code>wp_register_script</code> function. </p>
<p><span id="more-136"></span></p>
<h3>UPDATE (December 2011)</h3>
<p>As of WordPress 3.3, this is the best way to do it, using the proper hook (thanks David Hollander):</p>
<pre><code>//jQuery Insert From Google
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
}</code></pre>
<p><strike>Just add this code to your <code>functions.php</code> file:</p>
<pre><code>if( !is_admin()){
   wp_deregister_script('jquery'); 
   wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"), false, '1.3.2'); 
   wp_enqueue_script('jquery');
}</code></pre>
<p></strike></p>
<p>That last line there gets the script queued up for you so you don&#8217;t need to do it again in the header. Assuming you have the proper wp_head(); call in your header, you&#8217;ll be all set! Note that we have wrapped this in a <a href="http://codex.wordpress.org/Conditional_Tags">conditional tag</a> to prevent that action on Admin pages. Because this Google-hosted version of jQuery is not in <code>noConflict</code> mode, it interferes with the rich text editor in the admin. This prevents that.</p>
<p>Remember, the reason for all this is to ensure that other WordPress stuff (plugins&#8230;) are aware that the script is already loaded so don&#8217;t go around loading another copy. Loading two copies of a JS library is just bad news.</p>
<p>Also, I always use jQuery as an example but of course this would work with any popular JavaScript library. For example, the MooTools path at Google is:</p>
<pre><code>http://ajax.googleapis.com/ajax/libs/mootools/1.2.2/mootools-yui-compressed.js</code></pre>
<p>Google&#8217;s <a href="http://code.google.com/apis/ajaxlibs/documentation/index.html">AJAX Developer&#8217;s API Guide is here</a>.</p>
<p>ALSO&#8230; there are a crapload of scripts all ready to be queued up for your use in WordPress. See the <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script">full list here</a>. </p>
<p>David wrote in to tell us that he was working in an HTTPS environment, and he used this alteration to ensure the URL for the Google-hosted version of jQuery was properly served from HTTPS when needed:</p>
<pre><code>if (!is_admin()) {
   wp_deregister_script('jquery'); 
   wp_register_script('jquery', ("http".($_SERVER['SERVER_PORT'] == 443 ? "s" : "")."://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"), false, '1.4.2');
   wp_enqueue_script('jquery');
}</code></pre>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/">Permalink</a> | <a href="http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/#comments">22 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/&title=Use Google-Hosted JavaScript Libraries (&#8230;still the Right Way)">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/functions/" rel="tag">functions</a>, <a href="http://digwp.com/tag/header/" rel="tag">header</a>, <a href="http://digwp.com/tag/jquery/" rel="tag">jquery</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Including jQuery in WordPress (The Right Way)</title>
		<link>http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/</link>
		<comments>http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/#comments</comments>
		<pubDate>Wed, 03 Jun 2009 01:58:16 +0000</pubDate>
		<dc:creator>Chris Coyier</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[header]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://modernwordpress.com/?p=36</guid>
		<description><![CDATA[If you want, you can just download jQuery, put it on your server and link to it from your header.php file in the &#60;head&#62; section. But that can cause you grief. For one thing, some plugins use the jQuery library, and they are going to load it as well. This can cause problems. How was [...]]]></description>
			<content:encoded><![CDATA[<p>If you want, you can just download <a href="http://jquery.com">jQuery</a>, put it on your server and link to it from your <tt>header.php</tt> file in the <tt>&lt;head&gt;</tt> section. But that can cause you grief. For one thing, some plugins use the jQuery library, and they are going to load it as well. This can cause problems. How was your plugin to know you already had it loaded?</p>
<p>Another thing is that WordPress already includes a copy of jQuery. Here is how you can load up jQuery in your theme the smart (and intended) way. Put the following code in your <tt>header.php</tt> file in the <tt>&lt;head&gt;</tt> section:</p>
<pre><code>&lt;?php wp_enqueue_script("jquery"); ?&gt;

&lt;?php wp_head(); ?&gt;</code></pre>
<p><span id="more-36"></span></p>
<p>Your theme probably already has the <tt>wp_head</tt> function, so just make sure you call the <tt>wp_enqueue_script</tt> function BEFORE that. Now you are all set to call your own jQuery JavaScript file, AFTER the <tt>wp_head</tt> function.</p>
<pre><code>&lt;script type="text/javascript"
   src="&lt;?php bloginfo("template_url"); ?&gt;/js/yourScript.js"&gt;&lt;/script&gt;</code></pre>
<p>You are ready to rock, but there are still some considerations. For example, safeguarding yourself from the future possibility of conflict with other libraries. You really shouldn&#8217;t be using multiple JS libraries to begin with, but&#8230; better safe than sorry.</p>
<p>To be super-safe, you can put jQuery into &#8220;no conflict&#8221; mode and use a different shortcut for jQuery. In this case &#8220;$j&#8221; instead of the default &#8220;$&#8221;. The standard &#8220;$&#8221;, for example, can conflict with Prototype. Here is an example of a safe bit of jQuery JavaScript:</p>
<pre><code>var $j = jQuery.noConflict();

$j(function(){

    $j("#sidebar li a").hover(function(){
    	$j(this).stop().animate({
    		paddingLeft: "20px&amp;"
    	}, 400);
    }, function() {
    	$j(this).stop().animate({
    		paddingLeft: 0
    	}, 400);
    });

});</code></pre>
<p>Can you recognize this bit of code? We use it right here on Modern WordPress to do the cool &#8220;link nudging&#8221; in the sidebar!</p>
<h3>Translations</h3>
<ul>
<li><a href="http://webhostingrating.com/libs/including-jquery-in-wordpress-be">Belorussian translation</a></li>
</ul>
<hr />
<p><small>© 2009 <a href="http://digwp.com">Digging into WordPress</a> | <a href="http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/">Permalink</a> | <a href="http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/#comments">59 comments</a> | Add to <a href="http://del.icio.us/post?url=http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/&title=Including jQuery in WordPress (The Right Way)">del.icio.us</a> | Post tags: <a href="http://digwp.com/tag/header/" rel="tag">header</a>, <a href="http://digwp.com/tag/jquery/" rel="tag">jquery</a><br/></small></p>]]></content:encoded>
			<wfw:commentRss>http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/feed/</wfw:commentRss>
		<slash:comments>59</slash:comments>
		</item>
	</channel>
</rss>

