O'Reilly

dwClickable: Entire Block Clickable Using MooTools 1.2

By on  

I recently received an email from a reader who was really impressed with Block Clickable, a jQuery script that took the link within a list item and made the entire list item clickable. I thought it was a neat script so I took a few minutes and ported it to MooTools.

The XHTML

<ul class="block-list">
	<li>Clicking this block will take you to <a href="http://davidwalsh.name">DavidWalsh.name</a></li>
	<li>Clicking this block will take you to <a href="http://scriptandstyle.com">Script&Style.com</a>.</li>
	<li>Clicking this block will take you to <a href="http://bandwebsitetemplate.com">BandWebsiteTemplate.com</a></li>
	<li>Clicking this block will take you to <a href="http://mootools.net">MooTools.net</a></li>
</ul>

You see an unordered list with list items containing a link.

The CSS

.block-list	{ padding:0; margin:0; list-style-type:none; width:500px; }
.block-list li	{ padding:20px; background:#bfd0ed; border-top:3px solid #033289; }
.block-list li:hover	{ background:#e3ecfa; cursor:pointer; }

Here you can define styles for the list item. The :hover state is important -- you need to treat the list item as though it's a link when the mouse hovers over the link.

The MooTools 1.2 JavaScript Class


var dwClickables = new Class({
	
	//implements
	Implements: [Options],

	//options
	options: {
		elements: $$('li'),
		selectClass: '',
		anchorToSpan: false
	},
	
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		//set clickable
		this.doClickables();
	},
	
	//a method that does whatever you want
	doClickables: function() {
		
		//for all of the elements
		this.options.elements.each(function(el) {
			
			//get the href
			var anchor = el.getElements('a' + (this.options.selectClass ? '.' + this.options.selectClass : ''))[0];
			
			//if we found one
			if($defined(anchor)) {
				
				//add a click event to the item so it goes there when clicked. 
				this.setClick(el,anchor.get('href'));
				
				//modify anchor to span if necesssary
				if(this.options.anchorToSpan) {
					var span = new Element('span',{
						text: anchor.get('text')
					}).replaces(anchor);
				}
			}
			
		},this);
	},
	
	//ads the click event
	setClick: function(element,href) {
		
		element.addEvent('click', function() {
			window.location = href;
		});
	}
	
});

The class accepts three options:

  • elements: A list of elements to make clickable
  • selectClass: If you have more than one link in the item, you can designate which link to choose my the selectClass
  • anchorToSpan: Since the link borrows the anchor's href attribute, you don't necessarily need the link. This settings directs the class to change the anchor to a SPAN tag if anchorToSpan is set to true.

The MooTools 1.2 Usage

window.addEvent('domready', function() {
	
	var clix = new dwClickables({
		elements: $$('.block-list li'),
		anchorToSpan: true
	});
	
});

Just as you would with any other MooTools class, you instantiate the class and pass in the desired options.

I really enjoyed creating this class. It plays nice with search engines and implements the list item / click functionality flawlessly.

Any suggestions?

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • Fullscreen API

    As we move toward more true web applications, our JavaScript APIs are doing their best to keep up.  One very simple but useful new JavaScript API is the Fullscreen API.  The Fullscreen API provides a programmatic way to request fullscreen display from the user, and exit...

  • Full Width Textareas

    Working with textarea widths can be painful if you want the textarea to span 100% width.  Why painful?  Because if the textarea's containing element has padding, your "width:100%" textarea will likely stretch outside of the parent container -- a frustrating prospect to say the least.  Luckily...

Discussion

  1. I’m no CSS expert but I’ve always been able to accomplish things like this just by setting the width and height of the containing element and “display:block” as the anchors style.

  2. @Matt: I believe this would be considered the “semantic” approach. Your method works too.

  3. @David: Ok, I wanted to make sure I wasn’t missing something.

  4. Jeff Hartman

    Yes, I use this all the time with just CSS using display: block on the anchor. However, the CSS approach will not work if you have text within the list item that is outside of the anchor tag (like this example shows). If it is all within the anchor tag, go the CSS-only route.

    …and byt the way Matt, there is no need to set the width and height. :)

  5. @Jeff, you make a valid point about having text outside the anchor tag. My first thought was to just jam all the text into that anchor and be done with it. But that’s bad SEO practice. If I were to jam all the text into that anchor, Google would look at all that text instead of what’s most important.

    Thanks.

  6. Rich

    Hey David, any consideration on getting a JQuery version of this?

  7. @Rich: The link at the top of the page is a jQuery version made by someone else.

  8. Adam

    @David To this day I have still not been able to figure out which to invest my time on MooTools or jQuery. Which would you recommend? Why?

  9. @Adam: I’m a Moo guy. I love its syntax, plugins, documentation, and community.

    The only way to find out is to give them both a run.

  10. David,

    Thanks for all your hard work. My users were having a little trouble finding the actual spot to click in our list of apps. I implemented this in about 20 minutes. It’s working perfectly.

    You are the Main Moo.

    Justin

  11. Birke

    Is this working only with list elements or it is possible to make a div clickable if it contains different things like p, img, h1, etc.?

  12. @Birke: You can use my updated plugin here:

    http://davidwalsh.name/js/clickables

  13. Birke

    Hey thats nice! :)

    Thank you for the update of your plugin.

    Best wishes, Birke

  14. Birke

    May I ask you how your updated plugin works? I have a div which contains different elements like h1, img, p and my a for the link of the whole div. If I use the statement “elements: ‘.DIVNAME a ‘,” to adress the link in the div it is not working.

    I tried “elements: ‘.DIVNAME ‘,” too, but no success.

    Best wishes, Birke

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Access Mac Camera by Command Line

    With all of my recent command line tutorials, I've really gotten excited about the shell's simplicity and realized the true power of using the underlying technology of pretty UIs.  Since I work from home, I spend a lot of time on video calls, so when...

  • Open Files from Command Line on OS X

    I'm as much of a fan of application UIs as anyone else but I'm finding myself working more and more from the command line lately.  Much of that is becoming obsessed with media manipulation but I'm forcing myself to use less UIs so that I...

  • Get Stock Quotes From Command Line

    When I conned my way into my first professional programming gig, I didn't really think much about money -- just that I was getting my foot in the door.  But as my career has gone on, I've been more aware of money, investing, and retirement.  I've recently...

  • Geolocation API

    One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...

  • Create an Image Preview from a Video

    Visuals are everything when it comes to media.  When I'm trying to decide whether to watch a video on Netflix, it would be awesome to see a trailer of some kind, but alas that isn't available.  When I'm looking to download a video on my computer,...