Javascript

Example scripts and howtos for Javascript

Javascript is a programming or scripting language primarily used for client-sided programming in web browsers. It can also be used as a server-side programming language but this is generally used less often. Javascript was originally created by Netscape for their browser Netscape Navigator, and is now an implementation of the ECMAScript standard. It is typically used in web browsers for form validation, floating navigation, AJAX and other nifty things to make web pages more interactive.

Post sort order: Post Date (Newest First) | Post Date (Oldest First) | Alphabetical | Date Updated

Implement placeholders in IE8 & 9 (and other older browsers) with jQuery

Posted in HTML and CSS and Javascript -

HTML5 saw the introduction of the very useful placeholder attribute for input elements, but it's not supported in Internet Explorer before version 10. There are still a number of people out there with version 8 & 9 but fortunately there are some ways to support placeholders in these older browsers with Javascript.

Master Mobile Web Apps with jQuery Mobile 3rd Edition

Posted in Javascript -

My friends over at elated.com have recently released the 3rd edition of their "Master Mobile Web Apps with jQuery Mobile" e-book. I had a brief read of one of the earlier editions and it's a great book and I'll be using it as a reference at some point in the future. In the meantime, here's some info about the book and where to buy it from.

Javascript UNIX timestamp converter

Posted in Javascript -

I often need to convert UNIX timestamps from log files into a human readable format and need a quick and easy to access tool for doing so, and have written up this post with the converter tool followed by an explanation of the Javascript code behind it.

Running Javascript functions after Disqus has loaded

Posted in Javascript -

Disqus is a 3rd party hosted Javascript comments system for websites which I use on several of my websites including this one. Disqus has an undocument set of callback functions which can be called after it has finished loading, when new comments are posted, etc.

Prevent an AJAX request firing twice with jQuery

Posted in Javascript -

I was asked on my post about showing a loading image when loading AJAX content with jQuery how to disable the button that loads the content while it's loading, and then re-enable it again once the content is fully loaded. This post shows how to do this, and it will work whether it's a link, button or some other action which calls the AJAX loading function.

Disable a link from going to the href URL with jQuery

Posted in Javascript -

When assigning a click handler to an anchor tag with jQuery you'll often want to then prevent the browser from clicking through to the actual link. There are two ways I know of to do this with jQuery and these are presented there.

Javascript frame buster

Posted in Javascript -

It's really annoying when instead of linking directly to your site in a full browser window another site links using an <iframe> or <frameset> <frame>. There's a really simple method to bust out of frames using Javascript but as I discovered yesterday if you also use iframes in your own site the commonly used frame buster needs some improvement.

Scroll to the bottom of a page with jQuery

Posted in Javascript -

Some time back I posted how to scroll to the top of a page with jQuery and was recently asked how to scroll to the bottom of a page with jQuery. I took a punt on the answer and posted it in the comments without testing it and the commenter said it didn't work, so I tested it out for myself and my solution did work. I present it here along with a link to a full working example which shows scrolling to the bottom and scrolling to the top.

Toggling a password field between plain text and password

Posted in Javascript -

Some time back I posted how to show plain text in a password field and make it a regular password field on focus using jQuery, so that it could show some default text (i.e. "password") before anything was entered and then work like a normal password field when the user started typing text into it.

As someone a couple of days ago pointed out in the comments on that page, while it's not possible to change the type of a password input with jQuery, it is with regular Javascript. So this post shows how to do just that and which browsers do and don't support it.

Use a CDN hosted version of jQuery and fallback to a local copy

Posted in Javascript -

I've always served jQuery off my own websites either as a separate file or included in a combined, minified file with all my other Javascript code. I've moved to using the Google CDN to deliver jQuery instead and include code to fallback to a local copy if the remote one could not be loaded.

Hide an element initially with CSS and show it later with jQuery

Posted in HTML and CSS and Javascript -

This post is to answer a question asked in the comments section of my "Show and hide an element with jQuery - Part 1 of 2" post from a couple of years ago. It's a pretty simple question, asking how to have an element hidden with CSS at first and then show it with jQuery later. It might be triggered automatically, or when a button is clicked or the mouse hovering over something.

Style HTML Anchor Titles with jQuery and CSS

Posted in HTML and CSS and Javascript -

The title property of anchor tags in HTML show the text in black on a yellow background by default in most browsers, after mousing over the anchor for a second or two. This tutorial will show you how to style the title with CSS using jQuery and a small amount of Javascript and it will appear as soon as the user mouses over the link.

Get the current page path and filename with Javascript

Posted in Javascript -

A couple of days ago, I needed to get the current page's path and script filename with Javascript, excluding the protocol prefix, domain name and any parameters or hashtags which might be present. So here's another page for future self reference and so I will remember it in the future.

Reset an HTML form with Javascript

Posted in Javascript -

After receiving a number of "creative" ways to reset forms with Javascript on my "clear a form with jQuery" post, I've decided to post the correct way to reset a form with Javascript.

Load Javascript files asynchronously

Posted in Javascript -

It's annoying when a web page is loading and gets stuck downloading a Javascript file from a remote domain. Until the file has downloaded, rendering on the page stalls which could potentially lose you traffic as people give up waiting. Instead it's a good idea to load the remote Javascript asynchronously so the page can continue to render and the code is downloaded in the background.

TinyMCE _mcePaste divs and Webkit browsers

Posted in Javascript -

There is a bug in older versions of TinyMCE when using Webkit based browsers (Google Chrome and Apple's Safari) which added and failed to remove hidden divs with the id _mcePaste. This post looks at the problem and offers two solutions: upgrade TinyMCE completely, or just upgrade the paste plugin.

Load JSON data with jQuery and PHP - Radio Buttons

Posted in Javascript -

A while back I wrote a series dealing with loading content and JSON data with jQuery and AJAX which culminated in the post "Load JSON data with jQuery, PHP and MySQL" which brought all the techniques together and loaded JSON data into select boxes when the first was changed. I was recently asked how to do this using radio buttons instead, which I show how to do in this post.

jQuery: Toggling select boxes when one changes

Posted in Javascript -

I was asked a couple of days ago on my get and set form values with jQuery post how to make a secondary select box appear with jQuery when the first one is changed. The first might contain a list of countries and the second one some cities which changes as the country changes, allowing the user to select both their country and city. This post shows how to do this with several hidden sub-selects, and an earlier post shows how to do it with JSON and AJAX.

Target links to _top with jQuery

Posted in Javascript -

Amazingly some people still use <frameset> and <frame> tags around the web, as I discovered the other day when someone linked my Running Calendar website into their frameset website. A common approach to this problem is to detect if the page is in a frameset and to bust out of it; in this post I offer an alternative which is to change the target for all links to _top where a target is not already set.

jQuery: set title of anchor tags to the href for offsite links

Posted in Javascript -

Over a year ago I posted how to use jQuery to make all offsite links open in a new window. I recently received a comment on that page asking how to make the title attribute of all anchor tags on a page for offsite links be the same as the href. This post shows how to do this with jQuery, but also leaves any <a> tags with a title as-is.

Write content into a dynamic Javascript popup from FCKEditor

Posted in FCKEditor and Javascript -

In response to a question asked on my "Count the words in an FCKeditor instance with Javascript" post about how to get the content from an FCKEditor instance and load it into a popup window, I posted "Write content into a dynamic Javascript popup" to show how to do this for any content. In this post I now show how to do this specifically for an FCKEditor instance.

Write content into a dynamic Javascript popup

Posted in Javascript -

I've posted a few articles about the Facebox lightbox dialog recently but sometimes a quick and dirty post of content into a regular window.open popup is all that is required. This post shows how to open a Javascript window and write content into it without having to load another page.

jQuery: hide text when the page is loaded and show it later

Posted in HTML and CSS and Javascript -

This post is a response to a question asked on my "Show and hide an element with jQuery - Part 1 of 2" article about how to hide text when the page loads and then show it with a button (or some other method to reveal the text at a later time).

Make jQuery Facebox dialog modal

Posted in Javascript -

The jQuery Facebox lightbox can be closed by clicking the close button, clicking anywhere outside the dialog or using the escape key. This post shows how to make the dialog modal so that the only way to close it is by clicking the close button. You could alternatively add a link etc into the content of the dialog which would close it, link to another page etc.

jQuery Facebox: setting the width

Posted in Javascript -

I've been looking at the jQuery Facebox plugin recently which is a Facebook style lightbox for loading remote content, images, local content etc. In this post I look at how to change the width of the Facebox dialog with CSS or programatically using Javascript.

jQuery Facebox window with full height with scrollbar

Posted in Javascript -

I've been using the jQuery Facebox plugin a fair bit on various websites to show stuff in "inline" windows. On my New Zealand Running Calendar website I make the dialog the full height of the window with a scroll bar if the content is longer than the height of the window. This post shows how to do this.

Cookies and domains

Posted in Javascript and PHP -

A little while back I posted how to set cookies with jQuery and was asked about the domain setting and how setting the domain affects sub domains. This post explains how cookies and domains work, and covers some tests I did to check my assumptions were correct.

Open a jQuery Facebox dialog programatically

Posted in Javascript -

A few days ago I showed a basic example using the jQuery Facebox plugin to open dialog windows where particular links are made to open in a Facebox dialog. I was then asked in a comment how to open a dialog without making it opened from a link; this is covered with a brief example on the Facebox page but I've covered this a little more comprehensively in this post.

jQuery: Get the vertical mid point of the browser's window

Posted in Javascript -

jQuery's $(window).height() and $(window).scrollTop() can be used to calculate the vertical mid point of a browser's window. This quick post shows how to do this and then tomorrow's post will look at vertically centering a Facebox dialog in the middle of the window using this method.

jQuery Facebox Basic Example

Posted in Javascript -

The jQuery Facebox plugin creates a Facebook like lightbox which can be used to load external pages, images or put in any content you want. It's not perfect but it works pretty well. This post shows a basic example and the html for a page skeleton which uses Facebox. I'm posting this now because I'll have some additional posts in the next few days using Facebox (and also some older ones here here and here).

Troubleshooting errors with Yahoo's YUI Compressor

Posted in Javascript -

I use Yahoo's YUI Compressor to minify Javascript and CSS files. Recently I got an error message when attempting to minify a Javascript file: this post looks at the error message and how to use it to work out where the error occurs.

Demos for getting and setting form values with jQuery

Posted in Javascript -

Some time back I posted how to get and set form element values with jQuery just showing the HTML and Javascript needed to do so but without an actual demo. Someone asked for some demos of these yesterday so I present these here.

jQuery: show plain text in a password field and then make it a regular password field on focus - Part 2

Posted in Javascript -

Almost a year ago I showed how to have a password field show plain text with a default plain-text value but then be an actual password field when the user clicks into it, implementing this with jQuery. Just recently someone asked in the comments on that page how to do the same thing if you cannot modify the HTML itself, so show how to do that in this post.

Find the index of an item in a Javascript array

Posted in Javascript -

Javascript 1.6 introduced the Array.indexOf() function. Javascript 1.6 is available in Firefox from version 1.5 and current versions of Chrome, Safari and Opera; importantly, it is not in any versions of Internet Explorer at all (as at the time of this post).

Get an element's position with Javascript

Posted in Javascript -

Last month I posted how to get an element's position relative to the document with jQuery and in this post show how to do the same thing but with native Javascript without the use of a 3rd party library.

jQuery JSON Ajax requests and caching

Posted in Javascript -

Last week I wrote how to load JSON data with jQuery, PHP and MySQL, noting at the end that there can be some caching issues which may or may not be a problem depending on your implementation. I look at this here and a possible solution.

Using Javascript's setTimeout() with variable parameters

Posted in Javascript -

Javascript's setTimeout function executes code after a specified amount of time but can only handle constant parameters. This post looks at how to pass variable parameters to setTimeout.

Load JSON data with jQuery, PHP and MySQL

Posted in Javascript, MySql and PHP -

This post shows how to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP script that gets the data from a MySQL database.

jQuery's Facebox and Google Maps

Posted in Javascript -

On my soon to be launched New Zealand Running Calendar, I have the location map of the running event on a Google Map. This map can be viewed either on a regular page or via an AJAX call in a jQuery Facebox popup window. However I had issues with the map displaying in the popup as shown in this post along with the solution.

Load JSON data with jQuery

Posted in Javascript -

JSON data can be retrieved using AJAX from a server either using jQuery's .ajax() function or the shorthand $.getJSON() function. If you have retrieved a JSON string without having jQuery decode it automatically using one of these functions, the string can also be parsed into a regular data array using the $.parseJSON() function.

Dynamically load a Javascript file with jQuery

Posted in Javascript -

jQuery's $.getScript() function is a shorthand wrapper to $.ajax() which easily allows remote Javascript to be loaded into the current page.

Get an element's position relative to the document with jQuery

Posted in Javascript -

jQuery's .offset() method returns an offset containing the top and left co-ordinates of the element top-left position relative to the document as a whole. There's is also a .position() method which is supposed to return the offset relative to the offset parent but for me it always returns the same co-ordinates as .offset(). Maybe I'm doing something wrong with .position()...

Browser feature detection with jQuery $.support

Posted in Javascript -

Rather than working out the engine and version with Javascript for doing stuff that may work differently in different browsers, it's better to use feature detection instead. jQuery has the $.support property which has a number of flags to indicate the presence of various features or bugs. I'll look at a couple of the more useful flags here, but be sure to read the documentation for full details about all the properties.

Detecting the browser engine and version with jQuery

Posted in Javascript -

While you ideally shouldn't use browser detection to choose whether or not to render something in a particular fashion, jQuery does provide the capability to work out which browser renderingengine and version is being used with $.browser. There is also $.support which provides information about what the rendering engine supports and I will look at that in a later post.

Iterate through an associative array the jQuery way

Posted in Javascript -

A few months ago I posted how to loop through key value pairs from an associative array with Javascript. I do a lot of work with jQuery these days so in this post look at how to do the same but using jQuery's each function.

Add a new option to a select with jQuery

Posted in Javascript -

My last jQuery post looked at how to count the number of options in a select and then clear all options from the select. This post looks at how to add a new option to a select with jQuery.

Content-type for Javascript with Apache

Posted in Apache and Javascript -

I was making some changes to an Apache configuration this morning to ensure mod_deflate was compressing CSS and Javascript files and discovered I'd either documented the content-type for Javascript incorrectly, or the Apache version and Linux distro I used at the time served Javascript differently.

Get the number of options in a select with jQuery

Posted in Javascript -

This post looks at how to get the number of options that are in a select drop down box with jQuery, and also how to remove all current options from the drop down box. My next jQuery post will look at how to add new options to the select.

Multiple variable assignment with Javascript

Posted in Javascript -

About a month ago I posted how it is possible to assign multiple variables with the same value in PHP and have since learned that this is also possible to do with Javascript. This can be useful if initializing multiple variables with the same initial value or if needing to make multiple copies of a value and then manipulate each separately.

jQuery's toggleClass function

Posted in Javascript -

While looking up something else in the jQuery documentation just now I discovered a useful function "toggleClass" to toggle a CSS class on and off.This post doesn't really offer anything more than what is in the jQuery documentation ( the toggleClass manual page is here) but simply serves to draw your attention to this very useful function.

jQuery: Changing the default text value on focus, and showing plain text in a password field Part 1

Posted in Javascript -

Last year I posted a couple of jQuery articles about how to change the default text value on focus and show plain text in a password field and then make it a regular password field on focus, with examples in the pages about how to do it. I did not post a full standalone working example which someone requested a couple of days ago, so follow those posts up here with a full standalone example.

jQuery Form Selectors

Posted in Javascript -

There are a number of different <input> types in HTML and jQuery makes it simple to select the different types of input elements, such as all the text fields, all the radio buttons, all the submit buttons and so on. Full information and examples can be found on the selectors page of the jQuery document; this post gives some examples and a summary of the possible selectors.

Specify multiple selectors with jQuery

Posted in Javascript -

Today's jQuery post is a quick tip for writing more concise code, which is to specify multiple selectors using commas if the same function should be applied to multiple elements.

Make an entire table row clickable with jQuery

Posted in HTML and CSS and Javascript -

If an HTML table row contains only one <a> link it can be useful to make the entire row clickable and make it activate that link. This post shows how to make the entire row clickable with jQuery so that clicking anywhere in the row is the same as clicking that link.

Get the number of days in a month with Javascript

Posted in Javascript -

This post shows how to get the number of days in a month using Javascript by passing the month and year to a function.

Set multiple attributes at once with jQuery

Posted in Javascript -

This post shows how to set multiple attributes of an element with jQuery with one call to the attr() function. The example used shows how to set the src, width and height of an image element.

Modify right-click menu behavior with jQuery

Posted in Javascript -

This post shows how to modify the right-click menu with jQuery - it's possible to either completely disable right-click context senstive menus or replace them with a custom dialog which is applicable to the application. This can be done to the page as a whole or just a specific element.

Using ellipsis with HTML and CSS

Posted in HTML and CSS and Javascript -

If the text is too wide to fit into a container, a nice solution can be to have ellipsis to show there's more information available. While not currently part of the official HTML specifications, it is possible to have ellipsis defined in CSS and it works for Internet Explorer, Safari, Chrome and Opera. It doesn't work for Firefox but there's a workaround that can be done with jQuery.

Assign and remove a click handler from an element with jQuery

Posted in Javascript -

Click handlers can be assigned to elements easily with jQuery so when the element is clicked some particular action is run. This post looks at how to add a click handler to an element, explains how adding multiple click handlers will fire all of them, and then how to remove the click events.

How to preserve comments with the YUI Compressor

Posted in HTML and CSS and Javascript -

I use the YUI Compressor to minify Javascript and CSS files. By default it will remove all comments from the files but there is a simple solution to retaining comments in files, which is often necessary for example when preserving copyright and license terms of use etc.

Loop through parameters passed to a Javascript function

Posted in Javascript -

I looked at how to set default values for parameters in a Javascript function the other day and in this post look at the arguments object which can be used to work out how many parameters were passed to a function and also to loop through each of them.

Setting default values for missing parameters in a Javascript function

Posted in Javascript -

Javascript functions can be passed as few or as many parameters as you like - the exact number of parameters specified in the function declaration is not exactly what must be passed in. This post shows how to set a default value for a parameter if it's not passed in.

Post a form to a popup window with Javascript and jQuery

Posted in Javascript -

I recently needed to post an HTML form into a popup window instead of targeted to the current document or an existing window. The Javascript for doing this is very simple and in this post I show how to post the form into a popup window with regular Javascript and then with jQuery.

Change the cursor with Javascript

Posted in Javascript -

This post shows how to change the cursor on a web page with Javascript by assigning a value to the document.body.style.cursor property.

Javascript: reference the parent window from a popup

Posted in Javascript -

If a window has been opened with the Javascript window.open function, that window can be referenced using window.opener. This post shows some examples about how to do this.

jQuery: Mouse co-ordinates within the element when mouseover or click an element

Posted in Javascript -

Following up a couple of earlier posts about get the mouse co-ordinates with jQuery and how to get the co-ordinates when an element is clicked, this post looks at how to do both of these but with co-ordinates relative to the element itself so i.e. the top left co-ordinate is 0, 0 instead of some other value relative to the page.

Get the mouse co-ordinates with jQuery when an element is clicked

Posted in Javascript -

My last jQuery post looked at how to get the mouse co-ordinates with jQuery as the mouse moves around the page or over a particular element. This post looks at how to get the mouse co-ordinates when an element is clicked.

Get the mouse co-ordinates with jQuery

Posted in Javascript -

jQuery's mousemove function can be used to track the mouse x and y co-ordinates either for an entire document or just when mousing over a particular element.

Use jQuery's select() function to automatically select text in an input field

Posted in Javascript -

By default, when a user clicks a text input field in an HTML form the cursor is positioned in the text input but the text is not selected. Using jQuery's select() function it's easy to make the text be selected when clicking into the field.

How to use static variables in a Javascript function

Posted in Javascript -

There may be times when a static variable is needed in a Javascript function; static variables maintain their value between function calls and are tidier than using a global variable because they cannot be modified outside of the function.

Minify Javascript and CSS with YUI Compressor

Posted in HTML and CSS and Javascript -

I've previously posted about minifying Javascript using a PHP port of Douglas Crockford's JSMin Javascript minifier but learned today of the YUI Compressor which does an even better job of minifying by replacing local symbols with 1 letter symbol names and other optimizations. It is also able to compress CSS files.

jQuery Facebox dialog with opaque background

Posted in Javascript -

A few months ago I posted how to make the web page behind a jQuery Facebox inline popup grey out using an opaque layer that would show and hide before and after the facebox dialog. A reader recently emailed me to let me know there's an easier way to do this using the undocumented opacity setting which I will show how to do in this post.

How to tell if an element is visible with jQuery

Posted in Javascript -

jQuery makes it easy to determine if an element is visible or hidden with the is() function. This post shows some examples of how to do this and also how to loop through each of the visible or hidden elements.

Upper and lower case strings with Javascript

Posted in Javascript -

I needed to convert a string to lower case the other day with Javascript and wasn't sure of the exact function name, so turned to my blog but was surprised I didn't have a post about how to do this... so here it is now.

Calling $(document).ready multiple times with jQuery

Posted in Javascript -

jQuery's $(document).ready() function runs the code within that function after the DOM is loaded (I've written about this previously here). Something I haven't needed to do before, but was wondering if it's possible, is to use $(document).ready() more than once.

jQuery Animated Information Box

Posted in Javascript -

This post shows how to have a animated information box with jQuery. There are a series of links and when the user either clicks the link or moves their mouse over it, the content in the box next to it changes. This can be useful when showing features of a software product, web hosting etc.

Scroll to the top of a webpage with jQuery

Posted in Javascript -

This post shows a simple way to make anchor tags with e.g. href="#top" scroll to the top of the webpage when clicked using jQuery.

Relatively moving a div left or right with jQuery

Posted in Javascript -

jQuery's animate() function can do a lot of useful animation effects (see here for some more examples and documentation on the jQuery website). Something I found useful the other day is that it's possible to move a div relatively left or right using the animate function, e.g. you can move it50px to the right from its current position, instead of to an absolute position.

Running a function with jQuery when the window is resized

Posted in Javascript -

Although it should be avoided where possible, there may be times when something on a web page needs to be adjusted if the window size is changed. This can be done quite easily with jQuery but it needs to be done with caution as I show in this post how different browsers react to $(window).resize()

jQuery Superfish Menus Plug-in and Caching the menu

Posted in Javascript -

My last jQuery post looked at the Superfish plug-in showing how easy it is to turn an HTML unordered list into a flyout menu. The only downside with it is if the menu structure is very big there's quite a large overhead in your HTML template with the menu. I present a simple solution in this post which involves caching the menu structure as a Javascript variable in a separate .js file.

jQuery Superfish Menus Plug-in

Posted in Javascript -

The Superfish jQuery plug-in creates Suckerfish style flyout menus from HTML unordered lists and is very easy to use. It can work entirely with CSS alone but the jQuery bits add some enhancements. This post demonstrates how simple it is to use and in the next jQuery post I show how I cache the parts of the menu that are initially hidden with Javascript so they don't need to be downloaded with every page load. This latter aspect is very useful if it's a large menu structure.

Substrings in Javascript with substring()

Posted in Javascript -

There are two ways to get substrings using Javascript using the string object's substr() and substring() functions. You could also extract a string using a regular expression but I'll cover that in another post.

Substrings in Javascript with substr()

Posted in Javascript -

There are two ways to get substrings using Javascript using the string object's substr() and substring() functions. You could also extract a string using a regular expression but I'll cover that in another post.

Combine and minify Javascript files with PHP

Posted in Javascript and PHP -

If you're using a Javascript library like jQuery it's likely you'll end up with many Javascript files that need to be included in each page request. Ideally these should be combined into a single file and minified to cut down on page load time. This post shows how to use jsmin-phpto combine multiple Javascript files into a single minified file.

Get a string's length with Javascript

Posted in Javascript -

This is one of those posts that looks at a really basic function: how to get the length of a string with Javascript. Yes this is a really basic function, but I found myself reaching for my O'Reilly Javascript book the other day because I couldn't remember if it really was as simple as String.length... In writing this post I know I will never forget it again!

Use jQuery's data() method to store data in the DOM

Posted in Javascript -

jQuery has a .data() method for storing data in the DOM should you need to for one reason or other. This is preferable to storing data in some other attribute such as "rel" or "alt" which is often seen in tutorials and examples on blogs.

Count the words in an FCKeditor instance with Javascript

Posted in FCKEditor and Javascript -

A couple of days ago I looked at how to count the words in a textarea or input with jQuery and in this post look at how to do the same but for an FCKeditor instance. FCKeditor is an in-browser HTML editor. The code for counting the words uses regular Javascript and does not require jQuery.

Count the words in a textarea or input with jQuery

Posted in Javascript -

This post shows how to get a word count from an HTML textarea or text input using jQuery and display it on the page. The word count is updated as the user types.

Make jQuery Facebox loading screen auto-center

Posted in Javascript -

I've been using the jQuery Facebox dialog plugin in a couple of my projects and one thing that annoys me by default is the loading screen appears at an arbitrary position on the page and then becomes centered after the content has loaded; it's the moving after load I find messy. This post has a simple change that needs to be made to the Facebox code so it auto-centers the loading dialog.

jQuery Facebox dialog with greyed out background

Posted in Javascript -

Yesterday I posted how to grey out a web page which is useful when showing a Javascript dialog box and in this post show how to do the same when using the jQuery Facebox plugin. The Facebox plugin makes dialog boxes that look like the ones in Facebook.

Grey out a webpage

Posted in HTML and CSS and Javascript -

When showing an inline popup in a webpage (as opposed to a popup window) it is nice to grey out the background a little to highlight that the user should now interact with the popup rather than the webpage. This post shows how to do the necessary HTML and CSS to achieve this and tomorrow's post will look at implementing the greyed out background with the jQuery Facebox plug-in.

Accessing form elements by name with jQuery

Posted in Javascript -

There are a variety of ways to access elements with jQuery including by the name property of form elements (the name="" part of <input name="foo">). This can be useful so you don't have to assign an id to each and every form element as well as a name which is needed to pass the form value to the next page.

Clear a form with jQuery

Posted in Javascript -

A few weeks ago I posted how to clear a form with Javascript and in this post look at how to do the same thing but using jQuery, which makes the code required to do it much more condensed.

Trimming strings with Javascript

Posted in Javascript -

Javascript does not have built-in functions to trim strings so they need to be defined either by using a Javascript framework/library such as jQuery which includes a trim function or to define trim functions yourself. This post shows how to create trim() ltrim() and rtrim() functions.

Get all cookies with Javascript

Posted in Javascript -

In my last jQuery post I looked at how to set, get and clear cookies with jQuery and now look at how to get a list of all the cookies that have been set. This is not jQuery specific and will work with just regular Javascript.

Setting cookies with jQuery

Posted in Javascript -

Setting and clearing cookies with jQuery is really easy (especially when compared with regular Javascript) but it's not includedin the jQuery core and requires a plug-in. This post shows how to set, get the value of and clear cookies with jQuery.

Use append() to add text/html to an element with jQuery

Posted in Javascript -

jQuery's function append() can be used to add text or html to an element. It's very easy to use and this post shows some example code and has a working example where you can type in some text that will be appended to a div.

jQuery: show plain text in a password field and then make it a regular password field on focus

Posted in Javascript -

My last Javascript post looked at how to change the default text value on focus with jQuery and this takes it a step further by showing how to have a password form field which shows "Password" and when the user clicks into it it then becomes a regular password field with obscured text.

Changing the default text value on focus with jQuery

Posted in Javascript -

You've seen those cool search boxes or login fields on websites which have some default value (like e.g. "Enter keywords here") and when you click into the field the default text disappears but is then restored if you click out of the box without typing anything. This post shows how to change the default value of an HTML text field on focus and blur with jQuery.

Clear a form with Javascript

Posted in Javascript -

An HTML form can be reset using a reset button but this resets the form back to its original state, whereas you may want to be able to clear all the fields in the form. This post shows how to do this with Javascript.

Find the index of the element that was clicked with jQuery

Posted in Javascript -

There may be times when you need to know the index of the element that is clicked from within a group of elements e.g. a group of divs inside another div. This can be done easily with jQuery using the index() function.

Get the milliseconds with Javascript and measure time

Posted in Javascript -

If you need to measure how long something takes with Javascript you can use the Date() object to get a start timestamp and then compare it later on using a second Date() object. Although I'm sure there are other benchmarking plugins etc available this can be a quick and easy way to benchmark something in Javascript.

Get a UNIX timestamp with Javascript

Posted in Javascript -

The Javascript Date object has a number of functions for working with dates and times. The getTime() method returns the millisecond representation of the Date object and this post shows how to convert this to a UNIX timestamp.

Clear upload file input field with jQuery

Posted in Javascript -

The value of an HTML file input field cannot be changed or reset (without doing a full form reset) for security reasons. The other day I read Bogdan Gusiev's post about how to clear an upload file input field by resetting the HTML of a containing div to its intial state using Javascript and thought I'd take it one step further by doing this in jQuery and adding a clear button next to any file input field on a web page.

Rounding numbers with Javascript

Posted in Javascript -

The Javascript Math object has various mathematical functions and constants including .round() for rounding, ceil() for rounding numbers up and floor() for rounding numbers down.

Pad a number with leading zeroes in Javascript - Improved

Posted in Javascript -

A couple of weeks back I posted how to pad a number with leading zeroes in Javascript as a lead-in to a post about how to format a date time in Javascript in database format. The original post used a while() loop to add zeroes on to the string but as pointed out to me by Greg Jorgensen it's not very efficient so I present his solution here.

Format a date time in Javascript in database format

Posted in Javascript -

In some admin forms for own purposes I needed to have a "now" function to put the current date and time into the text field using Javascript. For various reasons I preferred to do this on the client side with Javascript than on the server side with PHP. The date and time format needed to be in a database YYYY-MM-DD HH:MM:SS format so it could be directly inserted into the database.

Pad a number to two digits with Javascript

Posted in Javascript -

On Sunday I looked at how to pad a number with leading zeroes in Javascript and in this post look at a simpler function to pad a number to just two digits as if required for days and months, and hours, minutes and seconds.

Pad a number with leading zeroes in Javascript

Posted in Javascript -

As far as I have been able to tell there isn't a built-in way with Javascript to pad a number with leading zeroes to make it a fixed width like with e.g. sprintf in other programming langages. This post looks at a way to pad a number with zeroes with Javascript.

Loop through selected elements with jQuery (Revised)

Posted in Javascript -

Earlier today I posted how to loop through elements in jQuery but as pointed out by Bloid at DZone it wasn't a very good way of doing it. This post is a revision to that earlier post and thanks to Bloid for letting me know a much better (and more jQuery way) of doing this.

Loop through selected elements with jQuery

Posted in Javascript -

There may be times when you need to loop through elements in jQuery to collect information, change state or some other nifty trick that can't be done easily using jQuery's various selection etc functions. This post has an example of looping through elements with jQuery by getting all the href attributes from the <a> tags of a selected element.

How to tell if an element exists with jQuery

Posted in Javascript -

Last week I looked at how to get the total number of matched elements with jQuery which also showed how to tell if an element exists with jQuery. I've decided to create a second post just showing how to tell if an element exists to make it easier to find this functionality when searching this blog.

Loop through key value pairs from an associative array with Javascript

Posted in Javascript -

This post looks at how to loop through an associate array with Javascript and display the key value pairs from the array. An associative array can contain string based keys instead of zero or one-based numeric keys in a regular array.

Get the total number of matched elements with jQuery

Posted in Javascript -

There may be times when you need to work out how many times a particular element appears on a page or within a section with Javascript and this is easy to do with jQuery using the length property. Using the method in this post you can also work out if an element exists on the page with jQuery.

Add an offsite link icon after external links with jQuery

Posted in Javascript -

Yesterday I posted how to add an offsite link icon after external links with CSS and in this post look at how to do the same thing but with jQuery instead of CSS. This allows the offsite links to appear in Internet Explorer 6 because the a[href^="http://"] type selector is not supported in IE6.

Use jQuery to make all offsite links open in a new window

Posted in Javascript -

XHTML Strict does not allow opening links in a new window using target="_blank" so instead you can use jQuery to add the target attribute to all <a> tags after the page has loaded and still have the page validate as XHTML strict.

Force reload of updated CSS and Javascript files with unique filenames

Posted in Apache, HTML and CSS, Javascript and PHP -

When a CSS or Javascript file is changed the visitor's browser needs to get the latest copy of the file to reflect the changes, but it will have been cached and may cause rendering or functionality issues depending on the changes. To force reloading of the CSS and Javascript file the files should be renamed each time they are changed; this can be automated by using PHP to add the timestamp of the file into the filename.

Add options to an HTML select box with Javascript

Posted in Javascript -

This Javascript post was going to be about language selection in FCKEditor from a drop down box as a follow up to the previous FCKEditor post but I've decided to postphone that post until Friday and look at how to add options to an HTML <select> drop down box with Javascript, because the next FCKEditor post will be doing just that.

Show and hide an element with jQuery

Posted in Javascript -

jQuery is a powerful Javascript library which makes adding useful Javascript stuff to your website easy across browsers. This post looks at how to show and hide an element with jQuery using the show(), hide(), toggle(), fadeIn() and fadeOut() functions.

Attaching an event to an element with jQuery

Posted in Javascript -

My last jQuery post looked at jQuery's document ready initialization function which you can use to do stuff to prepare your web page, including things such as attaching an event to an element which I will look at how to do in this post.

jQuery's document ready initialization

Posted in Javascript -

jQuery has a $(document).ready() function which is invoked after the DOM is loaded and before the page contents are loaded. It means you don't have to have body onload events and can completely remove all Javascript from your HTML by attaching events to elements independent of the HTML after the DOM has loaded.

How to get the timezone offset with Javascript

Posted in Javascript -

There may be times when you want to work out what the difference in timezone is between the web browser client and the web server. This is possible using the Javascript Date object's getTimezoneOffset() function.

Replacing text with Javascript

Posted in Javascript -

Javascript has the .replace method for strings which allows for replacement of strings within strings using regular expressions. This post has some examples of replacing text with Javascript.

Loading content with jQuery AJAX and dealing with failures

Posted in Javascript -

Some of the last few jQuery posts on this blog have looked at loading content with jQuery AJAX, selecting the element to inject and using a loading image. In these posts I incorrectly noted that the .load() method does not allow for error reporting and therefore you cannot deal with failures so another method would be required. Having had a better read of the jQuery docmentation I now know youcan deal with failures when using .load() so this post looks at how to do this.

Loading content with jQuery AJAX - using a loading image

Posted in Javascript -

A couple of weeks back I looked at how to load remote content with jQuery and AJAX using the jQuery .load() function. This post expands the functionality by looking at how to put a loading image as a placeholder where the new content will go while it is still downloading.

Using setTimeout() with Javascript

Posted in Javascript -

The Javascript setTimeout() function allows code to be executed a set time after some trigger, such as when the page has loaded or a button is pressed. This post looks at how to trigger events after a set time with Javascript and alsp how to clear the timeout.

Loading content with jQuery AJAX - selecting the element to inject

Posted in Javascript -

On Wednesday I looked at how to load content with jQuery via AJAX using the .load() function. This is the second part of that post which looks at how to just select a portion of the content loaded and inject just that part into the current webpage.

Loading content with jQuery AJAX

Posted in Javascript -

With jQuery it is simple to load content with AJAX and inject it into the current web page using the .load() function. This post shows a basic example doing this. Future posts will look at some other ways of loading content and making AJAX requests with jQuery.

Dynamically get and set an elements content with jQuery

Posted in Javascript -

This is the first post in a long series of how to do stuff with jQuery. They will start with some basic stuff and get more complex as the year goes by. New jQuery and Javascript posts are made on this blog on Sundays and Wednesdays; subscribe to my blog at the end of this post so you don't miss out. This first post looks at how to get and set the HTML of an HTML element with jQuery.

Adding, removing and checking if an element has a CSS class with jQuery

Posted in Javascript -

jQuery is a useful Javascript framework which simplifies cross browser Javascript development. This post looks at how to check what CSS class an element has with jQuery, and how to add and remove CSS classes from elements.

Find the index of a string within a string with Javascript

Posted in Javascript -

This post looks at how to find the position of a character or a string within a string with Javascript using the indexOf function.

Opening a new window with Javascript

Posted in Javascript -

On the odd occasion when I need to open a popup window with Javascript I always have to reach for my O'Reilly Javascript book, look in the index and find the appropriate page because I never can remember what the parameters are. So this post gives me an easy reference place for how to open a window with Javascript.

How to check and uncheck a checkbox with jQuery

Posted in Javascript -

jQuery is a Javascript framework which can simplify coding Javascript for a website and removes a lot of cross browser compatibility issues. Yesterday I looked at how to get and set form element values with jQuery but didn't deal with checkboxes. Today's post looks at how to tell if an HTML form checkbox is checked or not checked with jQuery and then how to change it to be un/checked.

How to get and set form element values with jQuery

Posted in Javascript -

jQuery is a Javascript framework which can simplify coding Javascript for a website and removes a lot of cross browser compatibility issues. This post looks at how to get and set the values of HTML form elements with jQuery.

Style an HTML form input with CSS and jQuery

Posted in HTML and CSS and Javascript -

It's possible with CSS to style a particular form input type without having to assign a class to each one with the special style. For example you may want to add a margin before radio buttons in a form but not all the other input elements. Unfortunately this doesn't work in Internert Explorer 6 (which still has about 25% market share as at the writing of this post) but there is a way around this using Javascript. In this post I'll look at both the CSS way of doing this and then also using the jQuery Javascript library.

How to disable Javascript in Mozilla Firefox

Posted in Applications and Javascript -

Forms on websites are typically validated using Javascript on the client side to prevent additional round trips to the server if a form hasn't been completed correctly, and are then also validated on the server side. When testing a website you need to be able to test both so need to disable Javascript in your web browser to test the server side validation. This post looks at how to disable Javascript in the Mozilla Firefox web browser. The specific version the screenshots come from are Firefox 3 but it should be the same for earlier versions.

How to check if a Javascript function exists

Posted in Javascript -

Sometimes you might want to call a function in Javascript but check if the function exists before calling it. This is very simple and is covered in this post.

Clearing the default value of text input with Javascript

Posted in Javascript -

Often in a web form you will put a default value into a text box which explains what the box is for and when the user clicks into the box clear the value. An example of this is a sidewide search box where you might want to put the instructions (e.g. "enter your keywords here") in the box instead of as a title for the text input. This post looks at how to clear the value only if it is set to the default value with Javascript.

Using Javascript to focus a form element onload

Posted in Javascript -

The Personalised Plates website has a big input box on every page for searching for available personalised plates. The page template uses the Javascript form element focus() function to set the focus on this text box when the page loads so the user can start to type in a personalised plate idea without having to click the box with their mouse.

Assigning values to associative arrays in Javascript

Posted in Javascript -

Javascript has zero indexed integer arrays and also associative arrays. They work in a similar manner but there is a useful way to be able to initialise an associative array with both keys and values in one call. This post will look at the way a zero based integer based array can be initialised and then the ways it can be done with associative arrays in Javascript.

Javascript and CSS file timestamps with PHP

Posted in HTML and CSS, Javascript and PHP -

Many websites I have worked on have frequently modified CSS style sheets and Javascript library files. In order to prevent Javascript errors or layout and style issues caused by web browsers caching these files, I used to rename the file for each revision, and then modify the name of the CSS or JS file in my PHP header include files. This article looks out how I now do this using the modified timestamp of the file.