I haven't posted in a bit since returning from Drupalcon Paris, and still have intentions to hash over some of the things I took away from the event, but for now, here's a quick group of jQuery code snippets I can't live without when developing Drupal sites.
Automatically opening external links in a new tab/window
(function($) {
$.fn.extend({
external_links: function () {
var site = String(document.location)
.replace(/^(https?:\/\/[^:\/]+).*$/, "$1")
.replace(/^((site)?(file:\/\/.+\/))[^\/]+$/, "$3")
.replace(/(\\.)/g, "\\$1");
$("a", this).filter(function (i) {
var href = $(this).attr("href");
if (href == null)
return false;
return (
href.match(RegExp("^("+site+"|(https?:)?/[^/])")) == null
&& href.match(RegExp("^(https?|ftp)://.+")) != null
);
}).each(function () {
$(this)
.addClass('external')
});
}
});
})(jQuery);
$(document).ready(function(){
/* Modify any links to external sites to open in a new window. */
$(document).external_links(); // adds the .external class to links
// this will activate on any link with the rel=external, or .external class
$('a.external, a[rel=external]').click(function(){
window.open($(this).attr('href'));
return false;
});
});
Auto populating a field, and removing text on focus
The following code will allow you to use any form field, and give it a default value that disappears when you enter into the form field, and if you exit the field, and it is empty, it will re-populate with the default value. I find this most useful in search boxes.
if($.trim($(selector).val()) == "") {
$(selector).val(defvalue);
}
$(selector).focus(function() {
if($(selector).val() == defvalue) {
$(selector).val("");
}
});
$(selector).blur(function() {
if($.trim($(selector).val()) == "") {
$(selector).val(defvalue);
}
});
}
$(document).ready(function(){
/* Give the search box some cool text & Functionality */
populateElement('#search-box input.form-text, #search-block-form input.form-text', 'type something here to search...');
/* Rock out with the login block to make it super sweet */
populateElement('#user-login-form #edit-name', 'Username');
populateElement('#user-login-form #edit-pass', 'Password');
});
The above sample applies this to the search box(es) on the site, and also the user login form. However, in this example, it shows me updating the password field, which will only by default show the ************** characters rather than the word "Password" as visible text. There is a way to accomplish this by switching form elements out for that when a user clicks in. It is NOT possible to change the type of a password field to text, and back again using javascript last I checked. There were many threads on the topic.
Making your primary menu respect paths, and show the appropriate active item based on path
This section of code may or may not work out of the box for everyone depending on theming variables and class names. The purpose of this is so that if I have a primary menu tab that is called "Portfolio", this will make sure that any page under the path portfolio/something/some-node will show that portfolio tab as active. This does not always work with CSS alone with the .active or .active-trail paths provided by Drupal. Sometimes this extra bit of massaging can make all the difference, and really helps a user always know where they are related to the primary nav. Also, this will determine if there are NO matches, and highlight a default menu item, in this case, the home link.
var currentURL = document.location.pathname;
var activeTopLevelPageArray = currentURL.split('/');
var activeTopLevelPage = activeTopLevelPageArray[1];
// applying the class to what we find
$('#header ul li a[href^=/'+activeTopLevelPage+']')
.addClass('active');
// now making the nav menu do what we want with styles for the active element
$('#header #primary-menu ul li a.active:first')
.addClass('current-main') // assign main active bg to active link
.parent('li') // select the parent list item
.addClass('active-trail'); // then assign a class to it for manipulation
/* If there is no match, just activate the "home" menu item/tab */
var isActive = $('#header #primary-menu li.active-trail').size();
if (isActive < 1) {
$('#header #primary-menu li:first').addClass('active-trail');
}
});
Wrapup
I hope this info helps someone else, I use these snippets on almost every personal project I work on, and they are simple, but can really help out the interface IMHO.
And on a side note, IE6 sucks ass, and should die a slow death. Just ask Morten.


Awesome snippets
Thanks, great stuff. #2 (Auto populating a field, and removing text on focus) is really handy for casual drupal users. Any issues/complications for using that snippet on node forms?
Populating fields on node forms.
I don't think there would be any issues with using the populate field on a node form, except if the form field being populated never was changed, it would submit the default text applied to it.
If using something like that on an advanced node form interface, it would proabably be good to check on the php side if those default values were what was submitted, and if so, just null out the field, and submit nothing for that field.
That's the only thing I can imagine running into with that one.
Jake Strawn
Drupal Rockstar
Newbie question: Where do you
Newbie question:
Where do you put code snipets? In a js file? How do you reference code to work on above items. Awesome to see you last night! Montreal or bust!
Usually in a js file included in the theme
Usually, I will include this code in a custom js file included via the .info file in the theme, or using drupal_add_js() in a module.
I have at times put this and other code that was more related to functionality than theming in a module so it could quickly be enabled or disabled.
As far as referencing the correct items, in the example related to the populating fields with default info,
The custom function populateElement() that is being called is passing standard jQuery selectors, in this case the #search-box input.form-text is selecting the default search form, and the #search-block-form ... is referencing the default search form that is presented in the block manager. It is easy to select any particular field based on a class or ID available for that item. If you had a search field that had a class of "my-search-field", the function would look like:
Jake Strawn
Drupal Rockstar
great! thank your for
great! thank your for populate js. very helpful!
Thanks for your query
Can i get this for primary menu also
Which part?
Not sure what you're asking for here. Can you elaborate a little what you are trying to accomplish?!
Jake Strawn
Drupal Rockstar
Post new comment