jquery
Sep
MooTools Plugin: Event.Mock
Those of you who visit this blog often know that I have a certain love for the simple things: simple CSS enhancements, simple PHP scripts, and most importantly, simple JavaScript plugins. One plugin that recently caught my attention was Arieh Glazer Event.Mock plugin. Event.Mock is a tiny MooTools plugin (essentially just a small function; not a MooTools class) that does exactly what it says: provides a Mock event for easy use with Element.fireEvent.
Why Event.Mock?
One frequent MooTools occurrence is assigning an event to a given element, then firing an event on the given element. The problem that occurs is that fireEvent doesn’t provide an Event object to the event listener’s function because a real event didn’t occur. Thus, if you reference the event within the listener function, you’ll get an error:
/* assign an event to myElement */
$('myElement').addEvent('click',function(e) {
var target = e.target; /* ERROR! -- e is null */
})
/* fire an event */
$('myElement').fireEvent('click');
Event.Mock serves as a fake event to provide to the listener function.
The Event.Mock MooTools JavaScript
/**
* creates a Mock event to be used with fire event
* @param Element target an element to set as the target of the event - not required
* @param string type the type of the event to be fired. Will not be used by IE - not required.
*
*/
Event.Mock = function(target,type){
var e = window.event;
type = type || 'click';
if (document.createEvent){
e = document.createEvent('HTMLEvents');
e.initEvent(
type, //event type
false, //bubbles - set to false because the event should like normal fireEvent
true //cancelable
);
}
e = new Event(e);
e.target = target;
return e;
}
Event.Mock accepts two arguments: the first being the fake event’s target element, the second being the type of event (i.e. “click”, “mouseenter”, etc.) That means I can use Event.Mock as such:
/* listen! */
$('myElement').addEvent('click',function(e){
/* log the event to the console */
console.log(e);
});
/* fire! */
$('myElement').fireEvent('click',new Event.Mock($('myElement'),'mousedown'));
Boom. No worries about event errors AND useful information, in the form of a fake event target and type, is event listener function.
Big ups to Arieh for his simple but useful MooTools plugin!
Follow Me! Twitter | Facebook | LinkedIn | MooTools Forge.
Full David Walsh Blog Post: MooTools Plugin: Event.Mock
Related posts:
- dojo.connect: A Powerful Object and Event Listener
- MooTools Tip: Event.stop
- Count MooTools Events Per Element in MooTools 1.2
- Implement MooTools’ Elements.addEvent in jQuery
- New MooTools Plugin: ElementFilter
Sep
Duplicate the jQuery Homepage Tooltips
The jQuery homepage has a pretty suave tooltip-like effect as seen below:
The amount of jQuery required to duplicate this effect is next to nothing; in fact, there’s more CSS than there is jQuery code! Let’s explore how we can duplicate jQuery’s tooltip effect.
The HTML
The overall structure includes a wrapping DIV element with each tooltip link featured in a list:
<div id="jq-intro" class="jq-clearfix"> <h2>jQuery is a new kind of JavaScript Library.</h2> <p>jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and AJAX interactions for rapid web development. <strong>jQuery is designed to change the way that you write JavaScript.</strong></p> <ul class="jq-checkpoints jq-clearfix"> <li><a href="http://docs.jquery.com/Tutorials" title="Lightweight Footprint" class="jq-thickbox">Lightweight Footprint</a> <div class="jq-checkpointSubhead"> <p>About 18KB in size <em>(Minified and Gzipped)</em></p> </div> </li> <li><a href="http://docs.jquery.com/Tutorials" title="CSS3 Compliant" class="jq-thickbox">CSS3 Compliant</a> <div class="jq-checkpointSubhead"> <p>Supports CSS 1-3 selectors and more!</p> </div> </li> <li><a href="http://docs.jquery.com/Tutorials" title="Cross-browser" class="jq-thickbox">Cross-browser</a> <div class="jq-checkpointSubhead"> <p>IE 6.0+, FF 2+, Safari 3.0+, Opera 9.0+, Chrome</p> </div> </li> </ul> </div>
Note that the UL element has been given a jq-checkpoints CSS class — we’ll use that in a selector for both CSS styling and element collection using jQuery.
The CSS
Like I said…there’s more CSS than there will be jQuery code:
#jq-intro { padding-top:1em; width:605px; margin:0 auto; }
#jq-intro h2 { font-size:1.9em; font-weight:bold; color:#5DB0E6; line-height:1em; }
#jq-intro h2 span.jq-jquery { float:left; width:81px; height:23px; margin-right:.3em; position:relative; }
#jq-intro h2 span.jq-jquery span { position:absolute; left:-999999px; }
#jq-intro p { clear:both; font-size:1.5em; margin:5px 0; font-weight:normal; line-height:1.6; }
#jq-intro ul { padding:1.5em 0; list-style-type:none; }
#jq-intro li { float:left; font-size:1.4em; }
#jq-intro li a { color:#5DB0E6; font-weight:bold; text-decoration:underline; float:left; padding:0 30px 0 23px; }
#jq-intro li p { font-size:12px; }
#jq-intro li { position:relative; }
div.jq-checkpointSubhead { display:none; position:absolute; width:253px; height:54px; background:url(jquery-tooltip.png) 0 0 no-repeat; top:-1.5em; left:-35%; z-index:100; }
div.jq-checkpointSubhead p { font-size:1em; padding:10px 5px 0 50px; color:#AE0001; font-weight:bold; line-height:1.3em; margin:0; cursor:pointer; }
Most of the CSS is gloss for the overall look. The important piece is the jq-checkpointSubhead CSS class being positioned absolutely and with an initial display value of none. That will allow us to use the :hidden selector within jQuery.
The jQuery JavaScript
And now for the jQuery JavaScript:
jQuery(document).ready(function() {
var duration = 500;
jQuery('.jq-checkpoints li').hover(
function(){ jQuery(this).find('div.jq-checkpointSubhead:hidden').fadeIn(duration); },
function(){ jQuery(this).find('div.jq-checkpointSubhead:visible').fadeOut(duration); }
);
});
When the use hovers over the list items, the tooltip for the given list item fades in. When the user leaves the list item, the tooltip fades out.
There you have it. If you’re interested in how to do this with out JavaScript frameworks, read my MooTools and Dojo tutorials!
Follow Me! Twitter | Facebook | LinkedIn | MooTools Forge.
Full David Walsh Blog Post: Duplicate the jQuery Homepage Tooltips
Related posts:
- Duplicate the jQuery Homepage Tooltips Using MooTools
- Duplicate the jQuery Homepage Tooltips Using Dojo
- MooTools 1.2 Tooltips: Customize Your Tips
- jQuery Comment Preview
- Sexy Album Art with MooTools or jQuery
Aug
Working With WordPress Shortcodes

WordPress shortcodes are used frequently in plugins and themes as a way to achieve extra functionality, without the need to modify template files. You just type the shortcode word right into your post. Some plugins and themes use them to add event calendars, some for making announcements, while others use them for inserting contact forms.
Simply, WP shortcodes are awesome.
However, what if you’re a theme / plugin developer wishing to use them for your next great product, but you have no idea where to start? We’re going to fix that in this tutorial.
1 – Overview – Exactly Where We are Going
We will start out by looking at the basic ways that we can use WP shortcodes, then we will move onto some more advanced tricks. After the usage sections, I’m going to show you some examples of real-world shortcodes, followed by even more ideas / references of what you could do with them.
2 – Getting Into the Basics
The first you thing you should always do when working with something WordPress, is check the WordPress Codex. It’s a great reference and starting point.
Shortcodes, like just about everything else in WordPress, can be created in the functions.php file, or from within your plugin file if you’re developing a plugin.
Let’s start simple by making a shortcode that we can use to add additional styles to some text.
1 2 3 4 |
function extra_style_shortcode( $atts, $content = null ) { return '<span style="color: blue; text-decoration: underline;">' . $content . '</span>'; } add_shortcode('extra-style', 'extra_style_shortcode'); |
This is a very simple example that serves almost no purpose, but easily illustrates the basics of shortcode creation. It allows us to do something like this in our WP posts/pages:
[extra-style]Hello World![/extra-style]
and have it outputted like this:
Hello World!
So what’s happening? It’s simple, we’re simply telling WordPress to put all of the text inside of the [ ] . . . [/ ] into a variable called $content, then outputting $content inside of a span tag that has some simple inline styling applied to it.
Okay, that was easy, now let’s get into something a little more complex. This time we’ll give the ability to define the color of the text using attributes.
1 2 3 4 5 6 7 |
function extra_style_shortcode( $atts, $content = null ) { extract(shortcode_atts(array( "color" => 'blue', ), $atts)); return '<span style="color: ' . $color . '; text-decoration: underline;">' . $content . '</span>'; } add_shortcode('extra-style', 'extra_style_shortcode'); |
Now we can do this:
[extra-style color=red]Hello World![/extra-style]
and we’ll see: Hello World!
or:
[extra-style color=orange]Hello World![/extra-style]
and we’ll see: Hello World!.
This example uses this bit of code
extract(shortcode_atts(array( "color" => 'blue', ), $atts));
to extract the information inputted by the user for the variable color. We have also defined a default color of blue in case no color is defined.
Again, this example is pretty much useless, but its simplicity makes it very easy to understand.
Let’s get just a little bit more complex before moving on.
1 2 3 4 5 6 7 8 9 |
function extra_style_shortcode( $atts, $content = null ) { extract(shortcode_atts(array( "color" => 'blue', "size" => '14px', "padding" => '0px', ), $atts)); return '<span style="color: ' . $color . '; padding: ' . $padding . '; font-size: ' . $size . '; text-decoration: underline;">' . $content . '</span>'; } add_shortcode('extra-style', 'extra_style_shortcode'); |
By using a shortcode like this within a block of text:
[extra-style color=purple size=18px padding=5px]Hello World![/extra-style]
we could see something like this:
Elementum odio? Sed, Hello World! proin pulvinar eros nascetur, massa urna aliquam turpis elit, adipiscing mauris montes ac, vel lacus placerat in adipiscing ridiculus rhoncus.
Well that’s enough of the pointless examples; let’s look at some real shortcode examples.
3 – Making an Information Box
This shortcode example will let you include a nice little message box at the top of your post to help catch readers’ eyes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function box_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'color' => 'yellow', 'size' => 'medium', ), $atts ) ); return ' <style type="text/css"> .shortcode_box { padding: 2px 4px; border: 1px solid #ccc; } .yellow { background: #ffd149; color: #666; } .blue { background: #a0c5ef; color: #333; } .gray { background: #f0f0f0; color: #333; } </style> <div class="shortcode_box ' . $size . ' ' . $color . '">' . $content . '</div>'; } add_shortcode('box', 'box_shortcode'); |
Now we can use our “box” shortcode to produce something like this
by using this shortcode:
[box color=yellow]This is a message box with important information you should read.[/box]
By changing the color variable, we can have different colors of boxes:
With a little more CSS, we could also control the size of the box, but I’ll leave that to you.
4 – Create a Download Button
The process for creating a download button is very similar to creating a message box: we simplu wrap the content of the button inside of a div with some special CSS3 styles applied to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
function button_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'color' => 'blue', 'size' => 'medium', ), $atts ) ); return ' <style type="text/css"> .shortcode_button { padding: 2px 8px; border: 1px solid #ccc; border-radius: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; } .black { background: #ffd149; background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#636363), to(#332F2F)); background: -moz-linear-gradient(19% 75% 90deg,#332F2F, #636363); color: #f0f0f0; border-top-color: #1c1c1c; border-left-color: #1c1c1c; border-right-color: #525252; border-bottom-color: #525252; } .blue { background: #a0c5ef; background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#508BC7), to(#203F75)); background: -moz-linear-gradient(19% 75% 90deg,#203F75, #508BC7); color: #f0f0f0; border-top-color: #023778; border-left-color: #023778; border-right-color: #26609e; border-bottom-color: #26609e; } .large { width: 200px; } .medium { width: 120px; } .small { width: 80px; } </style> <div class="shortcode_button ' . $size . ' ' . $color . '">' . $content . '</div>'; } add_shortcode('button', 'button_shortcode'); |
We can display our button by using:
[button color=black size=medium]<a href="#">Download</a>[/button]
In order to control the size or color of the button, all we have to do is create a CSS class with the same name as the value we input for our size / color variables. For example, if we do size=large in our shortcode, we need a CSS class called large in our stylesheet. You can see I have included extra styles in my above example to illustrate some possible options.
5 – Buttons and Boxes Together
Shortcodes are great because they also let us combine them to a result like:
Integer in, odio mattis ac! Nascetur augue odio in risus, arcu nunc, phasellus ultrices lectus velit, et tincidunt tristique. Integer vel pulvinar purus magnis.
by using a shortcode like:
[box color=blue]Porta ultricies. Amet odio amet, pellentesque elementum adipiscing sagittis enim, eu, proin placerat sed pid cum? Dictumst turpis integer. Adipiscing, porttitor scelerisque! Lorem turpis porttitor.
Integer in, odio mattis ac! Nascetur augue odio in risus, arcu nunc, phasellus ultrices lectus velit, et tincidunt tristique. Integer vel pulvinar purus magnis.
[button color=black size=small]<a href="#">Download[/button][/box]
There is one small hitch, though. By default, WordPress does not allow you to embed shortcodes within other shortcodes. In order to get around that, we have to add a line to our functions.php or main plugin file:
add_filter('the_content', 'do_shortcode');
This will make WordPress process both sets of shortcodes.
6 – Show Related Posts
This is a really handy shortcode we can use to display a list of posts related to the current post by comparing tags.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
function related_posts_shortcode( $atts ) { extract(shortcode_atts(array( 'limit' => '5', ), $atts)); global $wpdb, $post, $table_prefix; if ($post->ID) { $retval = '<ul>'; // Get tags $tags = wp_get_post_tags($post->ID); $tagsarray = array(); foreach ($tags as $tag) { $tagsarray[] = $tag->term_id; } $tagslist = implode(',', $tagsarray); // Do the query $q = "SELECT p.*, count(tr.object_id) as count FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID AND p.post_status = 'publish' AND p.post_date_gmt < NOW() GROUP BY tr.object_id ORDER BY count DESC, p.post_date_gmt DESC LIMIT $limit;"; $related = $wpdb->get_results($q); if ( $related ) { foreach($related as $r) { $retval .= ' <li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li> '; } } else { $retval .= ' <li>No related posts found</li> '; } $retval .= '</ul> '; return $retval; } return; } add_shortcode('related_posts', 'related_posts_shortcode'); |
We can show the related posts by using:
[related_posts]
Credit goes to Blue Anvil for this shortcode.
7 – Drop Caps With a Shortcode
Drop caps are pretty and make your articles look really nice. They can really add some nice detail to post and make your site stand out above the rest.
1 2 3 4 5 6 |
function dropcap($atts, $content = null) { return ' <div class="dropcap">'.$content.'</div> ;'; } add_shortcode('dropcap', 'dropcap'); |
The CSS:
1 2 3 4 5 6 7 |
.dropcap { display:block; float:left; font-size:50px; line-height:40px; margin:0 5px 0 0; } |
Use it with:
[dropcap]M[/dropcap]auris ut lectus erat. In ...
Credit for this shortcode goes to TutToaster.
8 – Custom Post Type Query
Let’s say that you have set up a custom post type called News and you wish to display all posts inside that custom post type on a page called Articles. You could do it with the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function news_shortcode() { //The Query query_posts('post_type=news'); //The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); echo '<h3><a href="'; echo the_permalink(); echo '">'; echo the_title(); echo '</a></h3>'; echo the_excerpt(); endwhile; else: endif; //Reset Query wp_reset_query(); } add_shortcode('news', 'news_shortcode'); |
Then display the news posts on your Articles page by using this shortcode:
[news]
9 – Display Posts from Category on Page
Very similar to the shortcode example above, we can also display limited number of posts from within a particular category using a shortcode like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function category_shortcode( $atts ) { extract(shortcode_atts(array( 'limit' => '5', 'category' => '', ), $atts)); //The Query query_posts('category=' . $id . 'posts_per_page=' . $limit); //The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); echo '<h3><a href="'; echo the_permalink(); echo '">'; echo the_title(); echo '</a></h3>'; echo the_excerpt(); endwhile; else: endif; //Reset Query wp_reset_query(); } add_shortcode('category', 'category_shortcode'); |
You can list the posts using:
[category id=# limit=5]
Just replace # with the ID of the category you wish to display.
10 – Great Examples of Other Possible Shortcodes
I’ve shown you a few examples, both of my own and other’s creation, now let me give you even more examples of awesome things you could do.
Joen Asmussen of NoScope.com created a really nifty little shortcode to make a Google PDF Viewer.
Jean Baptiste, of WP-Recipes created a shortcode to display a “ReTweet” or “TweetMeme” buttons in your posts. Find it here.
Justin Tadlock made a great plugin that turns all (or most) WordPress template tags into shortcodes so that they can be used within the post editor. Download the Plugin.
A few weeks ago I wrote a shortcode plugin of my own (sorry, couldn’t leave myself out!). It’s a shortcode utility plugin that allows you to insert a variety of message boxes and web buttons via shortcodes (similar to some of the examples I’ve used above). Check out WP Utility Shortcodes.
11 – Some More Ideas
- Use shortcodes for displaying contact forms
- use shortcodes for displaying a Google map
- Shortcodes to display author bios
- A shortcode that outputs all of your social network info
- Shortcodes for image galleries
- Shortcodes for jQuery image sliders
Have you seen any other interesting uses of shortcodes? Do you make use of them in your site already?
Aug
Create a Twitter AJAX Button with MooTools, jQuery, or Dojo
There’s nothing like a subtle, slick website widget that effectively uses CSS and JavaScript to enhance the user experience. Of course widgets like that take many hours to perfect, but it doesn’t take long for that effort to be rewarded with above-average user retention and buzz. One of the widgets I love is Twitter’s “Follow” button. Let me show you how you can implement this functionality with three popular JavaScript toolkits: MooTools, jQuery, and Dojo.
Note: This tutorial will only display the client side handling of the form submission — NOT any PHP/MySQL/server-side handling of the request.
The HTML Structure
The HTML for the button is very simple. The structure revolves around a BUTTON element which contains an I element and SPAN element. You’re probably thinking “An I element? WTF.” I know I did. The truth of the matter is that the I element is deprecated and, as far as I’m concerned, and be used for any purpose the developer would like. I’m also sure that Twitter doesn’t mind saving bytes here or there.
The CSS Styles
/* twitter button and its children */
button.btn {
-moz-border-radius:4px;
-webkit-border-radius:4px;
background-attachment:scroll;
background-color:#ddd;
background-image:url(http://s.twimg.com/a/1282150308/images/buttons/bg-btn.gif);
background-position:0 0;
background-repeat:repeat-x;
border:1px solid #ddd;
border-bottom:1px solid #ccc;
color:#333;
cursor:pointer;
font-family:"Lucida Grande",sans-serif;
font-size:11px;
line-height:14px;
padding:4px 8px 5px 8px;
text-shadow:1px 1px 0 #fff;
vertical-align:top;
}
button.btn:hover {
border:1px solid #999;
border-bottom-color:#888;
color:#000;
background-color:#d5d5d5;
background-position:0 -6px;
}
button.btn:active {
background-image:none !important;
text-shadow:none !important;
}
button.btn i {
background-image:url(http://s.twimg.com/a/1282150308/images/sprite-icons.png);
background-position:-176px -32px;
background-repeat:no-repeat;
display:inline-block;
height:13px;
margin-right:5px;
width:15px;
}
button.btn i.active { background:url(http://s.twimg.com/a/1282150308/images/spinner.gif); }
/* properties for the element that is generated *after* following */
span.following { background:#ffd; padding:5px 10px; }
span.following span { width:10px; height:9px; margin-right:5px; display:inline-block; background:url("http://s.twimg.com/a/1282150308/images/sprite-icons.png") -160px -16px no-repeat; }
Most of the styling for this button goes onto the BUTTON element itself. You’ll notice directives to round the button; leaving the button sharp also please the eye. Through the regular, hover, and active button states, check out how Twitter users the background position and colors to nicely modify the button without the need for additional images. You’ll also notice Twitter uses sprites…as should you.
The MooTools JavaScript
/* with mootools */
window.addEvent('domready',function() {
/* fetch elements */
$$('form.follow-form').each(function(form) {
/* stop form event */
form.addEvent('submit',function(e) {
/* stop event */
if(e) e.stop();
/* send ajax request */
var i = form.getElement('i');
new Request({
url: 'twitter-follow.php',
method: 'post',
data: {
followID: form.getElement('input').value
},
onRequest: function() {
i.addClass('active');
},
onSuccess: function() {
var button = form.getElement('button');
button.setStyle('display','none');
new Element('span',{
html: 'Following!',
'class': 'following'
}).inject(button,'after');
},
onComplete: function() {
i.removeClass('active');
}
}).send();
});
});
});
The first step is grabbing all of the FORM elements with the follow-form CSS class. Upon form submission, the default submission action is stopped. An AJAX request is fired, using the INPUT element’s ID as the user to follow. When the request is fired, the I element’s background image is set to the spinner. When the request is complete, the button is hidden and a new SPAN element is displayed informing the user that they are now following the given user!
The jQuery JavaScript
// Idiomatic jQuery by Doug Neiner
jQuery(function ($) {
/* fetch elements and stop form event */
$("form.follow-form").submit(function (e) {
/* stop event */
e.preventDefault();
/* "on request" */
$(this).find('i').addClass('active');
/* send ajax request */
$.post('twitter-follow.php', {
followID: $(this).find('input').val()
}, function () {
/* find and hide button, create element */
$(e.currentTarget)
.find('button').hide()
.after('<span class="following"><span></span>Following!</span>');
});
});
});
The code above is based off of the MooTools code. The workflow is exactly the same.
The Dojo JavaScript
/* when the DOM is ready */
dojo.ready(function() {
/* fetch elements */
dojo.query('form.follow-form').forEach(function(form) {
/* stop form event */
dojo.connect(form,'onsubmit',function(e) {
/* stop event */
dojo.stopEvent(e);
/* active class */
dojo.query('i',form).addClass('active');
/* get button */
var button = dojo.query('button',form)[0];
/* ajax request */
dojo.xhrPost({
form: form,
load: function() {
dojo.style(button,'display','none');
dojo.create('span',{
innerHTML: 'Following',
className: 'following'
},button,'after');
}
});
});
});
});
The code above is based off of the MooTools code. The workflow is exactly the same.
This “Follow” button is only one of many details that Twitter has paid attention to, just to make the user experience on the site better. Take note from the effort put forth by large websites — adding these types of details to your smaller websites can make the user experience much better for YOUR users!
Follow Me! Twitter | Facebook | LinkedIn | MooTools Forge.
Full David Walsh Blog Post: Create a Twitter AJAX Button with MooTools, jQuery, or Dojo
No related posts.
Aug
Quick Tip: Object Indexing vs. Array Collection
The Setup & Goal
Let’s say that we have one large text document and we have a a bunch of keywords that we want to parse the document for. We don’t care how many times times the keyword appears — we just care that it’s been used. When we find a keyword, we need to record that keyword been found so that we may check at a later time.
Inefficient Method: Array Collection and Search
The first method to record that a keyword has been found is by pushing the keyword into one array:
//Assume an array called "foundKeywords" was defined above
if(shouldSave(keyword)) {
foundKeywords.push(keyword);
}
At the end of the document search, we’d end up with an array like:
//the foundKeywords array looks like: //['keyword1','keyword2','keyword2',...]
When it comes to checking this array for the existence of a given keyword, this method will prove inefficient. Why? Because we’d need to loop through the array and search until we found the given keyword (if ever). Those are a lot of “wasted” or fruitless cycles, even if we break the loop when the keyword was found. Inefficient is the only word to describe this process.
The Efficient Method: Object with Index
The fastest method of checking a storing keywords for later reference is by object (in JavaScript) or associative array (in PHP). Instead of adding the keyword to an array, we add the keyword as an index to a master object, giving the value as 1:
//Assume an object {} called "foundKeywords" was defined above
if(shouldSave(keyword)) {
foundKeywords[keyword] = 1;
}
Why is this faster? No wasted cycles looking blindly through an array. The check is quick and simple:
if(foundKeywords[keyword]) { //FOUND!
//do something
}
It’s either an index or it’s not! In PHP, we’d save the keyword to an associative array:
//Assume an array called "$found_keywords" was defined above
if(shouldSave($keyword)) {
$found_keywords[$keyword] = 1;
}
//Later: checking if the keyword was there...
if($found_keywords[$keyword]) {
//FOUND!
}
In a word…awesome. Not only fast but simple!
I cannot provide a benchmark because the speed of execution depends on how large the keyword array is. Suffice to say, for the sake of simplicity and speed, using an object with keyword index is definitely the way to go!
Follow Me! Twitter | Facebook | LinkedIn | MooTools Forge.
Full David Walsh Blog Post: Quick Tip: Object Indexing vs. Array Collection
Related posts:
- dojo.connect: A Powerful Object and Event Listener
- Implementing an Array.count() Method in JavaScript
- Element Collection Manipulation Shortcut Using MooTools 1.2
- Implement Array Shuffling in MooTools
- Access JavaScript Object Variable Properties


