As a developer I am finding myself browsing the web looking for examples of things I have done before but not made a note of. It seems that I regularly perform the same jQuery tasks; but not in a volume where it sinks in and I can just write without referring to other sites.
This article details the day-to-day jQuery we use in the studio so we don’t have to hunt around for it!
Here is a list of what’s covered in this post:
- How to get DOM html from a selector
- Short Hand ready() alternative
- Checking if an element exists on the DOM
- Accessible alternative for target=”_blank”
- JS image hovers
- Background position with IE
- Common attribute selectors
How to get DOM html from a selector
Often when working with jQuery you may be using another JS library or standard JavaScript code (such as Google Maps). There is quite often a need to select a DOM HTML node but its not clear how to do this in jQuery.
With standard JS you would use:
document.getElementById(“myDiv”);
In jQuery you can use the following:
$(‘#myDiv’)[0];
Simple Really, why is this stuff never easy to find?
Short Hand .ready() alternative
Trying to write clean jQuery can be a challenge when using standard jQuery as demonstrated on most tutorial sites. We try to reduce the amount of code where possible by writing with short hand jQuery. Although by default jQuery is very efficient and not OTT we are always striving for that little bit of perfection.
Below is the short hand jQuery we see as the most important to know:
Standard:
$(document).ready(function() {
// your code
});
Short Hand:
$(function() {
// your code
});
Checking if an element exists on the DOM
Sometimes when writing jQuery you will want to detect if an element exists in the DOM. This maybe because you are getting an “element not defined” error or you want to place in certain jQuery depending on a certain criteria.
An example of this is you have two pages on your site, both with similar element in the DOM tree but one page is to behave differently. In this case we would apply a class to the body and then run the following jQuery DOM check e.g.
if($(‘body.home’).length)
{
// do something only for page with body that has class of home
}
Accessible alternative to target=”_blank”
When developing with a XHTML Strict doctype the use of target=”_blank” is invalid, there is another way to ensure that external links from your site open in a new window and remain accessible.
As this only with with Javascript enabled, users with disabilities (therefore no JS support) get taken to the site in the same window and the user experience remains accessible.
We use the following code:
$(“a[href^='http:'], .newwin”).not(“[href*='YOURDOMAIN']“).attr(‘target’,'_blank’).attr(‘title’,'This link opens in a new window.’);
Lets break this down so it’s more understandable:
$(“a[href^='http:'], .newwin”)This will look for any link that starts with http: or links with a class of newwin. All internal links would be relative and start with /
.not(“[href*='YOURDOMAIN']“)Optional – This will ensure that if its an internal link it does nothing by searching the url for your domain (without the TLD and url prefix)
.attr(‘target’,'_blank’)This will dynamically assign the old school target=”_blank” attribute that fails against the doctype if in the source code
.attr(‘title’,'This link opens in a new window.’);A friendly tool-tip to the user to let them know that this link will open in a new window.
JS image hovers
Although it’s possible to sprite hover images with CSS, sometimes there is the need to use JS to handle image rollovers. An example of this scenario is when using images for form buttons where CSS can not reliably be implemented.
Here is an example of a our basic jQuery image rollover code:
$(function() {
$(‘form input[type="image"]‘).hover(
function(){
if($(this).attr(“src”).indexOf(“_active”) == -1) {
var newSrc = $(this).attr(”src”).replace(“.gif”,”_active.gif”);
$(this).attr(“src”,newSrc);
}
},
function(){
if($(this).attr(“src”).indexOf(“_active.jpg”) != -1) {
var oldSrc = $(this).attr(“src”).replace(“_active.gif”,”.gif”);
$(this).attr(“src”,oldSrc);
}
});
});
The code above assumes that images are named as follows:
imagename.gif = default image
imagename_active.gif = mouse over image
Background position with IE
When altering background positions with jQuery using the .css() method the parameters for altering the background position are different for IE compared to other browsers (no surprise there)
Typically you would expect the following to work:
$(‘#sample’).css({‘background-position’:’1px 30px’});
IE6 and 7 require the following:
$(‘#sample’).css({‘background-position-x’:’1px ‘,’background-position-y’:’30px ‘});
Common attribute selectors
The attribute selectors we use on a regular basis are as follows:
Find external links with jQuery
$(“a[href^='http:']“)
Find input images with jQuery
$(“input[type='image']“)
Find PDF document links with jQuery
$(“a[href$='pdf']“)
Find element without a class
In this example we get all DIV’s within #item that don’t have a class of selected.
$(“#item div:not(.selected)”)
Find external links
$(“a[href^='http:']“)
Find links and element attributes containing a certain string with jQuery
$(‘[href*="css"]‘)
Find nth number of XHTML node in jQuery
In this example we get the first LI element in DOM
$(‘li:eq(0)’)
Find even/odd XHTML nodes in jQuery
In this example we get all Even li elements in DOM
$(‘li:even’)
Find up to a number of XHTML nodes in DOM with jQuery
In this example we select the first three li element in DOM
$(‘li:lt(3)’)
Find child XHTML nodes with jQuery
In this example we select the em children directly within #sample
$(‘#sample > em’)
Select hidden XHTML nodes with jQuery
In this example we select the em that has a “display” of “none” applied through CSS
$(‘em:hidden’)
Home
