• Feed RSS
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

How to Include JavaScript and CSS in Your WordPress Themes and Plugins

"Knowing the proper way to include JavaScript and CSS files in your WordPress themes and plugins is very important for designers and developers. If you don’t adhere to best practices, you run the risk of conflicting with other themes and plugins, and potentially creating problems that could have been easily avoided. This article is intended as a reference for playing nicely with others.


Best Practices Make Everyone Happy

If you’ve ever developed a theme or plugin for WordPress, or worked with one that someone else has created, you’ve probably come across several different methods for including JavaScript and CSS. While there are several methods that may appear to work in a specific set of circumstances, there is one primary method recommended in the WordPress Codex. This preferred way will ensure your theme or plugin works in all cases, assuming others also code the correct way.
There’s also some misunderstanding about what exactly the Codex says about this, which I will help clarify.

What’s in the Box?

When you download WordPress, a selection of common JavaScript libraries are already included that you can use for your JavaScript development. A list of included libraries can be found in the WordPress Codex wp_enqueue_script article.
All those libraries are included, but by default WordPress only loads the ones it needs to, and only when it needs them in the admin. If you write JavaScript that utilises one of these libraries, you need to tell WordPress that your script needs the library loaded first.

Telling WordPress About Your Script and What It Needs

Some of the things to think about when you’re coding JavaScript for WordPress are:
  • Is there an included library I can use?
  • Can I use the version that’s included?
  • Do I need to load my script in the front-end and in the admin?
  • Which front-end and admin pages do I need to load my script on?
Answering these questions helps you know what you need to do to register and load your script. This is done using a WordPress function called wp_register_script, and here is its usage according to the WordPress Codex:
wp_register_script( $handle, $src, $deps, $ver, $in_footer );
So what are these variables and do we need them every time? (This is covered on the Codex page, so I’ll be brief and use plain English)
  • $handle – what you’ll use to refer to this particular script wherever you might need to enqueue it, and you have to include this variable at the very least
  • $src – the path to the source file within your plugin or theme
  • $deps – an array containing the $handle for any other scripts your script needs to run (i.e. a dependency)
  • $ver – the version number for your script, which can be used for cache-busting. By default, WordPress will use its own version number as the version number for your script
  • $in_footer – do you want your script to load in the footer? Set this to true or false. It is false by default, so it loads in the header where wp_head() is, and if you specify true it will load where wp_footer() appears in the theme

What Is “Cache-Busting”?

Browsers remember what scripts and stylesheets they’ve downloaded for a particular site based on the URL of the script and stylesheet. If you change the URL, even just by adding a querystring, the browser assumes it’s a new file and downloads it.

Ok, So Let’s Try Some Examples

Here is the most basic example for loading a custom script:
function wptuts_scripts_basic()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' );
First, we register the script, so WordPress knows what we’re talking about. The way to find the path for our JavaScript file is different whether we’re coding a plugin or a theme, so I’ve included examples of both above. Then we queue it up to be added into the HTML for the page when it’s generated, by default in the <head> where the wp_head() is in the theme.
The output we get from that basic example is:
<script type="text/javascript" src="http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1"></script>
Now if your script relies on one of the libraries included with WordPress, like jQuery, you can make a very simple change to the code:
function wptuts_scripts_with_jquery()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery' ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery' ) );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_jquery' );
Note: By default, jQuery is loaded with noConflict to prevent clashes with other libraries (such as Prototype). See the noConflict section of the Codex if you don’t know how to deal with that.
See what I did there? You just add an array with the ‘jquery’ handle as a dependency. It uses an array here, because your script could have multiple dependencies. If your script uses jQuery and jQuery UI, you’d add jQuery UI to your dependency array, like array( 'jquery', 'jquery-ui-core' )
So now the output has changed, and we can see that jQuery has also been added into the <head> of the page:
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1'></script>
Let’s try an example with all the bells and whistles:
function wptuts_scripts_with_the_lot()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), '20120208', true );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery', 'jquery-ui-core' ), '20120208', true );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_the_lot' );
Ok, so I’ve now added a version and specified that this script needs to be loaded in the footer. For the version number, I’ve chosen to use today’s date because it’s easy to keep track of, but you can use any version numbering you like. The output for this one is slightly different too, jQuery is output in the <head> and our script along with jQuery UI is output just before </body>, like this:
<head>
...
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
...
</head>
<body>
...
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/ui/jquery.ui.core.min.js?ver=1.8.16'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=20120208'></script>
</body>

Getting Your Priorities Straight

Some people may prefer not to use the proper enqueuing methods because they feel they have less control over the order in which scripts are loaded. For example, in a theme that uses modernizr, the theme author might want to make sure modernizr is loaded early on.
Something I haven’t mentioned earlier is more detail on how the add_action function works, as this is where we can exercise a little influence over the order of things. Here’s the usage of the function according to the WordPress Codex page:
add_action( $tag, $function_to_add, $priority, $accepted_args );
Note that often, and up until now in this article, only the $tag and $function_to_add parameters are used. The $priority parameter defaults to 10, and the $accepted_args parameter defaults to 1. If we want our scripts or styles to be enqueued earlier, we simply lower the value for $priority from the default. For example:
function wptuts_scripts_important()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_important', 5 );
The output will be the same as we’ve seen previously, but it will occur earlier in the HTML document.

Overriding Default Libraries and Using Content Delivery Networks

There may be times when you want to use a different version of a library that’s included with WordPress. Perhaps you want to use a cutting-edge version or you don’t want to wait for the next release of WordPress before using the latest stable version of jQuery. Another reason might be that you want to take advantage of Google’s CDN version of a library.
It’s important to note that this should only be done on plugins or themes used on sites that you will be personally maintaining. Any plugins or themes that you release for public use should use the libraries included with WordPress.
“Why?!”, I hear you ask. For the simple reason that you don’t control those sites. You don’t know what other plugins and themes might be used there, and you don’t know how often they will update your plugin or theme. Using the libraries packaged with WordPress is the safest option.
Having said that, if you are wanting to do this on a site you control, here’s how it’s done:
function wptuts_scripts_load_cdn()
{
 // Deregister the included library
 wp_deregister_script( 'jquery' );

 // Register the library again from Google's CDN
 wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), null, false );

 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery' ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery' ) );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_load_cdn' );
So first of all, I deregister the included version of the library, otherwise conflicts between different versions could be introduced. Then register the alternate version, using the same handle, and I’ve chosen to specify null as the version (it’s already in the URL!) and specified not in the footer. The rest of our code is the same, because we were depending on whatever script used the ‘jquery’ handle. The output we get now looks like:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1'></script>
Note: One of the reasons this is a bad idea to do in a plugin or theme for public release, is that all other plugins and themes used on this site will now have to use this version of jQuery. Also, the newly registered version of jQuery doesn’t have noConflict set, so if any other plugin or theme scripts use Prototype for example, this will break things.

Don’t Be Greedy

So far we haven’t mentioned anything about how to do all this in the admin, only on the front-end. The primary difference is what action to use. Instead of add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' ); which we use for the front-end, the action for the admin is add_action( 'admin_enqueue_scripts', 'wptuts_scripts_basic' );
Something that’s important to do for both the front-end and admin is be selective about which pages you load your scripts on. If your plugin or theme has a script that only does something on one front-end or admin page, such as the theme’s options page, or maybe a page with a specific widget, you only need to load your script on that page. No point clogging things up and loading scripts on pages where they’re not being used!
There’s a great example in the WordPress Codex on how to load scripts only on plugin pages. Because plugins and themes can vary a lot in how they’re written, I won’t go into specifics here on how to be choosy about which pages you load scripts on, but it was important to mention so you’re aware of it when you’re coding.

That’s Scripts, Now Styles

The process for styles is almost exactly the same as the process for scripts. It is done using a WordPress function called wp_register_style, and here is its usage according to the WordPress Codex:
wp_register_style( $handle, $src, $deps, $ver, $media );
Note that the only difference there between wp_register_script and wp_register_style is that instead of an $in_footer parameter, we have a $media parameter. This parameter can be set to any of the following: 'all', 'screen', 'handheld', and 'print', or any other W3C recognised media type.
So an example of how you might enqueue a style would be:
function wptuts_styles_with_the_lot()
{
 // Register the style like this for a plugin:
 wp_register_style( 'custom-style', plugins_url( '/css/custom-style.css', __FILE__ ), array(), '20120208', 'all' );
 // or
 // Register the style like this for a theme:
 wp_register_style( 'custom-style', get_template_directory_uri() . '/css/custom-style.css', array(), '20120208', 'all' );

 // For either a plugin or a theme, you can then enqueue the style:
 wp_enqueue_style( 'custom-style' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_styles_with_the_lot' );
This is a fairly comprehensive example, utilising most of the parameters, and the output it produces looks like:
<link rel='stylesheet' id='custom-style-css'  href='http://yourdomain.com/wp-content/plugins/yourplugin/css/custom-style.css?ver=20120208' type='text/css' media='all' />

So, Why Doesn’t Everyone Already Do Things This Way?

Good question, and the other question I guess you might ask is, “What makes you think this is the ‘right’ way and not just your preference?”. Essentially the answer is that this is the approach recommended by WordPress. It ensures that any combination of plugins and themes should be able to work together happily and without doubling up.
I’ve seen a few themes and frameworks around the place that use <script></script> and <link /> tags in their header.php, and even footer.php, files to load the scripts and styles for the theme itself. There’s really no reason to do things this way. As I’ve demonstrated above, it’s perfectly possible to prioritise scripts and styles and nominate whether they load in the header or footer from the comfort and safety of your functions.php. The benefit being that your theme / framework will work with a wider range of other plugins / child themes.
One example was loading jQuery using the <script></script> tags, which might appear to work nicely, but this can actually cause jQuery to be loaded twice! Loading jQuery in this way will not stop WordPress from loading its version of jQuery for other plugins, as WordPress’ version is in noConflict mode by default, and a plugin may specify it as a dependancy. So now you’ll have jQuery working for both noConflict mode and $, and also probably break any plugin that uses the Prototype library.

Conclusion

WordPress is a fantastic system, and it has been developed with a lot of thought. If there’s a mechanism made available to do something, it’s often a good idea to use it. When developing your plugins and themes, try to remember to code thoughtfully and for playing nicely with others.
What do you think about the use of wp_enqueue_script and its associated functions and actions? Do you know of any examples where it’s being done incorrectly? Do you know of any reason not to follow the advice above?"
read more

Uploading Files with AJAX

"
I can’t seem to reach the end of the fun stuff you can do with emerging web technologies. Today, I’m going to show you how to do something that—until the last while—has been almost unprecedented: uploading files via AJAX.
Oh, sure, there have been hacks; but if you’re like me, and feel dirty every time you type iframe, you’re going to like this a lot. Join me after the jump!


Why don’t we get the bad news over with?
This doesn’t work in every browser. However, with some progressive enhancement (or whatever the current buzzword is), we’ll have an upload page that will work right back to IE6 (albeit without the AJAXy bits).
Our AJAX upload will work as long as FormData is available; otherwise, the user will get a normal upload.
There are three main components to our project.
  • The multiple attribute on the file input element.
  • The FileReader object from the new File API.
  • The FormData object from XMLHttpRequest2.
We use the multiple attribute to allow the user to select multiple files for upload (multiple file upload will work normally even if FormData isn’t available). As you’ll see, FileReader allows us to show the user thumbnails of the files they’re uploading (we’ll be expecting images).
None of our three features work in IE9, so all IE users will get a normal upload experience (though I understand support for `FileReader` is available in IE10 Dev Preview 2). FileReader doesn’t work in the latest version of Safari (5.1), so they won’t get the thumbnails, but they’ll get the AJAX upload and the confirmation message. Finally, Opera 10.50 has FileReader support but not FormData support, so they’ll get thumbnails, but normal uploads.
With that out of the way, let’s get coding!

Step 1: The Markup and Styling

Let’s start with some basic markup and styling. Of course, this isn’t the main part of this tutorial, I won’t treat you like a newbie.

The HTML

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8" />
 <title>HTML5 File API</title>
 <link rel="stylesheet" href="style.css" />
</head>
<body>
 <div id="main">
  <h1>Upload Your Images</h1>
  <form method="post" enctype="multipart/form-data"  action="upload.php">
   <input type="file" name="images" id="images" multiple />
   <button type="submit" id="btn">Upload Files!</button>
  </form>

  <div id="response"></div>
  <ul id="image-list">

  </ul>
 </div>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
 <script src="upload.js"></script>
</body>
</html>
Pretty basic, eh? We’ve got a form that posts to upload.php, which we’ll look at in a second, and a single input element, of type file. Notice that it has the boolean multiple attribute, which allows the user to select multiple files at once.
That’s really all there is to see here. Let’s move on.

The CSS

body {
 font: 14px/1.5 helvetica-neue, helvetica, arial, san-serif;
 padding:10px;
}

h1 {
 margin-top:0;
}

#main {
 width: 300px;
 margin:auto;
 background: #ececec;
 padding: 20px;
 border: 1px solid #ccc;
}

#image-list {
 list-style:none;
 margin:0;
 padding:0;
}
#image-list li {
 background: #fff;
 border: 1px solid #ccc;
 text-align:center;
 padding:20px;
 margin-bottom:19px;
}
#image-list li img {
 width: 258px;
 vertical-align: middle;
 border:1px solid #474747;
}
Absolutely no shockers here.

Step 2: The PHP

We need to be able to handle the file uploads on the back end as well, so let’s cover that next.

upload.php

<?php

foreach ($_FILES["images"]["error"] as $key => $error) {
 if ($error == UPLOAD_ERR_OK) {
  $name = $_FILES["images"]["name"][$key];
  move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
 }
}

echo "<h2>Successfully Uploaded Images</h2>";
Bear in mind that these were the first lines of PHP I’d written in easily a year (I’m a Ruby guy). You should probably be doing a bit more for security; however, we’re simply making sure that there are no upload errors. If that’s the case, we use the built-in move_uploaded_file to move it to an uploads folder. Don’t forget to make sure that the folder is writable.
So, right now, we should have a working upload form. You choose an image (multiple, if you want to and your browser lets you), click the “Upload Files!” button, and you get the message “Successfully Uploaded Images.
Here’s what our mini-project looks like so far:
The styled form
But, come on, it’s 2011: we want more than that. You’ll notice that we’ve linked up jQuery and an upload.js file. Let’s crack that open now.

Step 3: The JavaScript

Let’s not waste time: here we go!
(function () {
 var input = document.getElementById("images"),
     formdata = false;

 if (window.FormData) {
  formdata = new FormData();
  document.getElementById("btn").style.display = "none";
 }

}();
Here’s what we start with. We create two variables: input is our file input element; formdata will be used to send the images to the server if the browser supports that. We initialize it to false and then check to see if the browser supports FormData; If it does, we create a new FormData object. Also, if we can submit the images with AJAX, we don’t need the “Upload Images!” button, so we can hide it. Why don’t we need it? Well, we’re going to auto-magically upload the images immediately after the user selects them.
The rest of the JavaScript will go inside your anonymous self-invoking function. We next create a little helper function that will show the images once the browser has them:
function showUploadedItem (source) {
 var list = document.getElementById("image-list"),
     li   = document.createElement("li"),
     img  = document.createElement("img");
  img.src = source;
  li.appendChild(img);
 list.appendChild(li);
}
The function takes one parameter: the image source (we’ll see how we get that soon). Then, we simply find the list in our markup and create a list item and image. We set the image source to the source we received, put the image in the list item, and put the list item in the list. Voila!
Next, we have to actually take the images, display them, and upload them. As we’ve said, we’ll do this when the onchange event is fired on the input element.
if (input.addEventListener) {
 input.addEventListener("change", function (evt) {
  var i = 0, len = this.files.length, img, reader, file;

  document.getElementById("response").innerHTML = "Uploading . . ."

  for ( ; i < len; i++ ) {
   file = this.files[i];

   if (!!file.type.match(/image.*/)) {

   }
  }

 }, false);
}
We don’t have to worry about IE’s proprietary event model, because IE9+ supports the standard addEventListener function.
There’s more, but let’s start with this. First off, we don’t have to worry about IE’s proprietary event model, because IE9+ supports the standard addEventListener function (and IE9 and down don’t support our new features).
So, what do we want to do when the user has selected files? First, we create a few variables. The only important one right now is len = this.files.length. The files that the user has selected will be accessible from the object this.files. Right now, we’re only concerned with the length property, so we can loop over the files …
… which is exactly what we’re doing next. Inside our loop, we set the current file to file for ease of access. Next thing we do is confirm that the file is an image. We can do this by comparing the type property with a regular expression. We’re looking for a type that starts with “image” and is followed by anything. (The double-bang in front just converts the result to a boolean.)
So, what do we do if we have an image on our hands?
if ( window.FileReader ) {
 reader = new FileReader();
 reader.onloadend = function (e) {
  showUploadedItem(e.target.result);
 };
 reader.readAsDataURL(file);
}
if (formdata) {
 formdata.append("images[]", file);
}
We check to see if the browser supports creating FileReader objects. If it does, we’ll create one.
Here’s how we use a FileReader object: We’re going to pass our file object to the reader.readAsDataURL method. This creates a data url for the uploaded image. It doesn’t work the way you might expect, though. The data url isn’t passed back from the function. Instead, the data url will be part of an event object.
With that in mind, we’ll need to register a function on the reader.onloadend event. This function takes an event object, by which we get the data url: it’s at e.target.result (yes, e.target is the reader object, but I had issues when using reader in place of e.target inside this function). We’re just going to pass this data url to our showUploadedItem function (which we wrote above).
Next, we check for the formdata object. Remember, if the browser supports FormData, formdata will be a FormData object; otherwise, it will be false. So, if we have a FormData object, we’re going to call the append method. The purpose of a FormData object is to hold values that you’re submitting via a form; so, the append method simply takes a key and a value. In our case, our key is images[]; by adding the square-brackets to the end, we make sure each time we append another value, we’re actually appending it to that array, instead of overwriting the image property.
We’re almost done. In our for loop, we’ve displayed each of the images for the user and added them to the formdata object. Now, we just need to upload the images. Outside the for loop, here’s the last piece of our puzzle:
if (formdata) {
 $.ajax({
  url: "upload.php",
  type: "POST",
  data: formdata,
  processData: false,
  contentType: false,
  success: function (res) {
   document.getElementById("response").innerHTML = res;
  }
 });
}
Again, we have to make sure we have FormData support; if we don’t, the “Upload Files!” button will be visible, and that’s how the user will upload the photos. However, if we have FormData support, we’ll take care of uploading via AJAX. We’re using jQuery to handle all the oddities of AJAX across browsers.
You’re probably familiar with jQuery’s $.ajax method: you pass it an options object. The url, type, and success properties should be obvious. The data property is our formdata object. Notice those processData and contentType properties. According to jQuery’s documentation, processData is true by default, and will process and transform the data into a query string. We don’t want to do that, so we set this to false. We’re also setting contentType to false to make sure that data gets to the server as we expect it to.
And that’s it. Now, when the user loads the page, they see this:
Tutorial Image
And after they select the images, they’ll see this:
Tutorial Image
And the images have been uploaded:
Tutorial Image

That’s a Wrap!

Uploading files via AJAX is pretty cool, and it’s great that these new technologies support that without the need for lengthy hacks. If you’ve got any questions about what we’ve done here, hit those comments! Thank you so much for reading!
"
read more

Quick Tip: How to Add Syntax Highlighting to Any Project

"
In this lesson, we’ll use a JavaScript based syntax highlighter to quickly add a syntax highlighting functionality to any web project — even on a simple HTML page!


Step 1 — Download the Source Code

You can download the syntax highlighter source files here.

Step 2 — Drag the src Directory into your Project

I generally rename this folder to highlighter. Don’t delete anything within here, unless you don’t anticipate using some of the language specific JavaScript files.

Step 3 — Import the Necessary Files

Within your HTML file (or whichever page is responsible for displaying your view), import both the prettify.css and prettify.js files.
<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf&mdash;8">
  <title>untitled</title>
  <link rel="stylesheet" href="highlighter/prettify.css" />
</head>
<body>

<script src="highlighter/prettify.js"></script>

</body>
</html>
Notice how we’ve placed our script at the bottom of the page, just before the closing body tag. This is always a smart move, as it improves performance.
Next, we need something to work with! The syntax highlighter will search for either a pre or code element that has a class of prettyprint. Let’s add that now.
<pre class="prettyprint">
(function() {
  var jsSyntaxHighlighting = 'rocks';
})();
</pre>

Step 4 — Calling the prettyPrint() Function

The last step is to execute the prettyPrint() function. We can place this bit of code at the bottom of the page as well.
<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>untitled</title>
  <link rel="stylesheet" href="highlighter/prettify.css" />
</head>
<body>

<pre class="prettyprint">
(function() {
  var jsSyntaxHighlighting = 'rocks';
})();
</pre>
<script src="highlighter/prettify.js"></script>
<script>prettyPrint();</script>
</body>
</html>
If we now view the page in the browser…
final product
Well that was easy! But, as a final bonus step, what if we want to change the highlighter theme? In that case, it all comes down to editing the stylesheet how you see fit. Even better, there are a handful of stylesheets in the theme gallery that you’re free to use. I personally like the Desert theme. To apply it, copy the CSS from the link above, create a new stylesheet in your project, and paste the CSS into it. Next, update the stylesheet include from within the head section of your document.
<head>
  <meta charset="utf&mdash;8">
  <title>untitled</title>
  <link rel="stylesheet" href="highlighter/dessert.css" />
</head>
Desert Theme Applied
Seriously — can it get any simpler than that?
"
read more

Professional Javascript Select Boxes for jQuery & Prototype

"
Chosen is a javascript plug-in makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors. Instead of forcing your users to scroll through a giant list of items, they can just start typing the name of the item they were looking for.
Add Chosen’s files to your app and then add the class chzn-select to your select box. Chosen automatically respects optgroups, selected state, the multiple attribute and browser tab order. You don’t need to do anything else except customize the style as you see fit.
chosen-select-javascript
Requirements: jQuery or Prototype Framework Demo: http://harvesthq.github.com/chosen/ License: MIT License
"
read more

50 jQuery and JavaScript Tutorials [Fresh]

"
jQuery has many Ajax and Javascript features that allow you to enhance user experience and semantic coding and it has captivated everyone’s attention by its fast and concise JavaScript Library that simplifies event handling, animating, HTML document traversing and Ajax interactions for speedy web development. In this post we present you 50 fresh JavaScript & jQuery tutorials that might be useful to you.

The 11 JavaScript Mistakes you’re Making

The 11 JavaScript Mistakes you're Making in JavaScript and jQuery: 50 New Tutorials

Image Control Manipulation in JavaScript

Image Control Manipulation in JavaScript in JavaScript and jQuery: 50 New TutorialsDownload

How to Speed Up Page Loading With Lazy Loading JQuery and JavaScript

How to Speed Up Page Loading With Lazy Loading JQuery and JavaScript in JavaScript and jQuery: 50 New TutorialsDownload

A Guide To Creating Forms In jQuery

A Guide To Creating Forms In jQuery in JavaScript and jQuery: 50 New Tutorials

Animated Scroll to Top

Animated Scroll to Top in JavaScript and jQuery: 50 New TutorialsDemo

Adding HTML Elements Dynamically via JavaScript

Adding HTML Elements Dynamically via JavaScript in JavaScript and jQuery: 50 New TutorialsDownload

Analog JQuery clock

Analog JQuery clock in JavaScript and jQuery: 50 New TutorialsDemoDownload

Learn how to detect browser in javascript

Learn how to detect browser in javascript in JavaScript and jQuery: 50 New Tutorials

How to get missing leading zero while conversion of number to string in javascript

How to get missing leading zero while conversion of number to string in javascript in JavaScript and jQuery: 50 New Tutorials

Learn how to create div element dynamically by using javascript

Learn how to create div element dynamically by using javascript in JavaScript and jQuery: 50 New Tutorials

Simple Images Slideshow With JQuery

Simple Images Slideshow With JQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Hover Image Zoom With JQuery

Hover Image Zoom With JQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Create Dynamic Tabs With JQuery

Create Dynamic Tabs With JQuery in JavaScript and jQuery: 50 New TutorialsDemo

Get page name from url in javascript

Get page name from url in javascript in JavaScript and jQuery: 50 New Tutorials

Create Simple One Page Profile With JQuery

Create Simple One Page Profile With JQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Limit the text length in textbox using javascript

Limit the text length in textbox using javascript in JavaScript and jQuery: 50 New Tutorials

Sliding Stacked Images With JQuery

Sliding Stacked Images With JQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Redirection in javascript after some time delay

Redirection in javascript after some time delay in JavaScript and jQuery: 50 New Tutorials

How to make sure your web pages are not included in other website frames

How to make sure your web pages are not included in other website frames in JavaScript and jQuery: 50 New Tutorials

Nested Arrays in JavaScript

Nested Arrays in JavaScript in JavaScript and jQuery: 50 New Tutorials

How to Make an Elegant Sliding Image Gallery with jQuery

How to Make an Elegant Sliding Image Gallery with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Drag-and-Drop with jQuery: Your Essential Guide

Drag-and-Drop with jQuery: Your Essential Guide in JavaScript and jQuery: 50 New TutorialsDemo

How to Make a Slick Ajax Contact Form with jQuery and PHP

How to Make a Slick Ajax Contact Form with jQuery and PHP in JavaScript and jQuery: 50 New TutorialsDemoDownload

Simple JQuery Slideshow

Simple JQuery Slideshow in JavaScript and jQuery: 50 New Tutorials

Simple jQuery Dropdown Menu

Simple jQuery Dropdown Menu in JavaScript and jQuery: 50 New TutorialsDemo

Words Validation with Javascript

Words Validation with Javascript in JavaScript and jQuery: 50 New Tutorials

Sliding Letters with jQuery

Sliding Letters with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Add a splash page on your website using javascript

Add a splash page on your website using javascript in JavaScript and jQuery: 50 New Tutorials

Grid Navigation Effects with jQuery

Grid Navigation Effects with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Dynamically Change hyperlink colors on a website using javascript

Dynamically Change hyperlink colors on a website using javascript in JavaScript and jQuery: 50 New Tutorials

Image Wall with jQuery

Image Wall with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Copy form field values using javascript

Copy form field values using javascript in JavaScript and jQuery: 50 New Tutorials

Rotating Image Slider with jQuery

Rotating Image Slider with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Moving Boxes Content with jQuery

Moving Boxes Content with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Create a grid Image Gallery that has intersecting highlights with jQuery and CSS

Create a grid Image Gallery that has intersecting highlights with jQuery and CSS in JavaScript and jQuery: 50 New TutorialsDemoDownload

Expanding Image Menu with jQuery

 in JavaScript and jQuery: 50 New TutorialsDemoDownload

Visitor counter using cookies and javascript

Visitor counter using cookies and javascript in JavaScript and jQuery: 50 New Tutorials

Detect browser close event and alert some messages using javascript

Detect browser close event and alert some messages using javascript in JavaScript and jQuery: 50 New Tutorials

Animated Content Menu with jQuery

Animated Content Menu with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Thumbnails Preview Slider with jQuery

Thumbnails Preview Slider with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Thumbnails Preview Slider with jQuery

Thumbnails Preview Slider with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

Parallax Slider with jQuery

Parallax Slider with jQuery in JavaScript and jQuery: 50 New TutorialsDemoDownload

How to use an External JavaScript Page

How to use an External JavaScript Page in JavaScript and jQuery: 50 New TutorialsDownload

Preloading images and executing code only after all images have loaded

Preloading images and executing code only after all images have loaded in JavaScript and jQuery: 50 New Tutorials

Setting CSS3 properties using JavaScript

Setting CSS3 properties using JavaScriptin JavaScript and jQuery: 50 New Tutorials

How To Build a Sliding Feature Slideshow with jQuery

How To Build a Sliding Feature Slideshow with jQuery in JavaScript and jQuery: 50 New TutorialsDemo

Making a Beautiful HTML5 Portfolio

Making a Beautiful HTML5 Portfolio in JavaScript and jQuery: 50 New TutorialsDemoDownload

Generating Files with JavaScript

Generating Files with JavaScript in JavaScript and jQuery: 50 New TutorialsDemoDownload

Shutter Effect Portfolio with jQuery and Canvas

Shutter Effect Portfolio with jQuery and Canvas in JavaScript and jQuery: 50 New TutorialsDemoDownload

Better Check Boxes with jQuery and CSS

Better Check Boxes with jQuery and CSS in JavaScript and jQuery: 50 New TutorialsDemoDownload

"

read more