Tag Archives: javascript

Adding Scripts and Style only to a certain Page on WordPress

Sometimes we want to add a script or a css file only to a certain page. How can this be done?

Here’s what happened to me: I needed to insert a code snippet on a page. The snippet was generated by a third party. In fact – it was a form, and the form’s code, already ready, also contained the action for the form, on a galaxy far, far away. I.e. – remote server, not a part of the site.

That means – most of the work already done. All is needed is to paste the piece of code on a page, and let the 3rd party action page deal with the rest. Unfortunately, even when a remote server takes care of the form data, it is still our responsibility to validate it on the client side. So further to adding the html code for the form, we need some javascript to actually validate it. To do so, I wanted to call an external jquery plugin called validationengine. Question is: how do I call this script only on the form’s page?

So the first thing we do, is create a unique template for the form page. Having done that we go on to the next stage

What we need to do now, is creating 2 hooks that will be called and affect the content of the page’s head. The first hook, when called, will register the necessary js files, and the second hook will add a line to the head html: a call for the css file.

In this example I will demonstrate adding some script that take care of form validation, but you may use the same technique for anything you want.

So it is time to add some code to our functions.php file. You can find this file on your theme’s directory. If you don’t find it – don’t worry. Just go ahead and create one. Open the functions.php file with your favorite text editor and write down:
function print_form_scripts () {
wp_enqueue_script('validationEngine-en', get_bloginfo( 'template_url' ).'/jquery.validationEngine-en.js', array('jquery'));
wp_enqueue_script('validationEngine', get_bloginfo( 'template_url' ).'/jquery.validationEngine.js', array('jquery'));
function print_form_styles ($content) {
$content .= '<link rel="stylesheet" href="'.get_bloginfo( 'template_url' ).'/validationEngine.jquery.css" type="text/css"/>';
echo $content;

The first function (print_form_scripts) when called, will register a couple of scripts to the page,
The second function (print_form_styles) when called, will add an html line to the head content, a call for a css file, that is relevant for the form validation.

Now, all is left to do, is actual hooking of these functions to the wp_head action.

In order to do so, open your new page’s unique theme file (page-NNN.php) and add these lines, before the call for the get_header() function:
add_action('wp_print_scripts', 'print_form_scripts');
add_action('wp_head', 'print_form_styles');

Keep in mind, that these lines should be added to the file before the call for the theme’s header file (get_header()), as they are hooked to wp_head, which in its turn, is called from within the header file.

Having done that, you can refresh the page and check it’s html hitting “view source”, and see that indeed the calls to the requested js and css files are added to the head html, for this page only.

What’s $(this)??

I am far from being a javascript Ninja. But I do try to catch up.
The first JS library I used to work with was Prototype + Scriptaculous. Unfortunately These are not maintained anymore. So I moved on to the next Buzz – Mootools.

I really like Mootools. It’s a great powerful library. Unfortunately, Mootools’ golden days seem to be over. The new king is now Jquery. The fact that all the big players – Yahoo, Google, Microsoft implement this library for all their projects makes it a safe bet and the immediate choice for any developer. So although Mootools is great and my own choice, me too, I should move on.

At start I found Jquery rather annoying. On one hand it’s easy enough to point to a DOM element using the same notation as being used on your stylesheet. On the other hand I now need to learn new references to all its attributes and remember to pass them as arguments in a function, instead of the original and intuitive assignment. Html(‘bla’) instead of innerHTML = ‘bla’, css() instead of style, etc.. On top of everything – what’s with the $(this)? How does it relates to ‘this’? This is mind boggling.

So here’s the deal, in a nutshell:

Whenever we call the Jquery function, or its alias $, with a jquery DOM selector as a parameter, we get in return an array of elements.

For instance, if we point to ‘.my_class’, i.e. pass it as a parameter to Jquery (), we get back an array that contains all the elements in the page that have the ‘my_class’ class.

And here’s the big thing: we can refer to the first member of this array as ‘this’.
$(this)[0] == this
That means, that if we point only to a unique element:
$(‘#my_unique_element’)[0] == this;
$(‘#my_unique_element’).html(‘new content!’);
Is as good as
$(‘#my_unique_element’)[0].innerHTML = ‘new content!’;

As this is a reference to an element within its own context, $(this) means we pass it as a parameter to the Jquery function.

When we are within the context of $(‘.my_elements’), ‘this’ is any element that has a ‘my_elements’ class, and $(this), is that same element being passed to the $(Jquery) function. That way we can apply all the Jquery magic on it.

Keeping this in mind may also help us making our code more efficient: As Jquery almost never throws error at selecting a none-existance dom element, we now have a way to manually test that it indeed exists before we go on trying to manipulate it, simply by checking the returned array length:

if ($(‘div.my_elements’).length) { … }
When it equals 0 – i.e – jQuery returned an empty array – no such element on the DOM, let’s move on!

Code Dissection (or the Frog’s Revenge)

Here’s a piece of code that I have came across and pasting here in order to figure it out:

That’s right. This snippet is taken from the earlier discussed Lavalamp menu. But now we are going to dissect it.

So first step – the anonymous function that wraps the whole deal and gets an argument $. This is a general recommendation when designing a plugin – we pass the jQuery reference for $ as an argument of an anonymous function, to set up a closure and thus avoid collision with other scripts in the page, that may also use the $ sign.

Everything that we need for the plugin is inside this anonympus function.

Next, within this closure, we add a new function property to jquery’s fn object. This function’s name is the actual plugin’s name.

Most important to remember at this stage is that ‘this’ actually refer to the object we have just created – i/e/ the plugin itself, and not to the element it is applied on.

Next we deal with our constructor’s parameters: o. Basically o is an object that contains the properties speed, type of effect an a callback function. o is also extended by any argument passed through. If no argument is passed through – then o is extended by an empty object.

Next we iterate through all elements in the documents that are asigned by this onbjects – for example – all elements that has the class name ‘lavaLamp’, and for each we apply all the object’s properties and methods. We always define the properties first, separated by commas.

Html5 and the Modernizr

Modernizr is a little javascript api compatible with most modern libraries (jquery, mootools etc..), that allows you to already start using most of HTML5 tags and features, while taking care of all cross-browser compatibility issues for you! This is all over the internet, so there’s not much new I can add. However, here’s a speed guide to making a very basic cross-browser html5 page using Modernizr.

Continue reading

The Lava-Lamp Menu in WordPress

The other day one of my clients asked me to look at a very neat effect he saw somewhere. He insisting on having “the same” in his site. So I made a little research and came across this really neat gimic: the Lava Lamp Menu. The main idea is to have a neat transition that enhances the hover effect, making the active menu item transform to its new css with a very delicate and not-too-obtrusive sliding motion.

Continue reading