JavaScript Redirects and window.open

By  on  

One of the sweet parts in the simplified HTML5 spec was allowing A elements to wrap DIVs and other block level elements.  For too long we added JavaScript listeners and window.location redirects when a wrapping A would have probably sufficed.  But there are also times when the wrapping A wouldn't work -- for example, a block with A elements already within it -- you just want clicks on anything else within the parent to land at a given location.

Of course a basic listener like this would work:

someElement.addEventListener('click', function(e) {
	// not important what the URL is but assume it's available on
	// the element in a `data-src` attribute
	window.location = someElement.get('data-url');
});

...but it would succumb to one of my biggest pet peeves:  COMMAND+CLICK'ing a block and the link opening in the same window.  The closer we can get custom-coded blocks to native browser functionality the better.  So take a moment and fix your event listener callbacks:

someElement.addEventListener('click', function(e) {
	var url = someElement.get('data-url');

	if(e.metaKey || e.ctrlKey || e.button === 1) {
		window.open(url);
	}
	else {
		window.location = url;
	}
});

I've implemented this on my blog and it's something I keep in mind whenever I use a window.location redirect.  It's a minimal code addition but a major usability boost!

Recent Features

Incredible Demos

  • By
    Animated AJAX Record Deletion Using jQuery

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with jQuery JavaScript. The PHP - Content & Header The following snippet goes at the...

  • By
    Scrolling “Go To Top” Link Using Dojo

    One of the most popular code snippets of posted on my blog has been the scrolling "Go To Top" link snippet. The premise of the snippet is simple: once the user scrolls an element (usually the BODY element) past a given threshold, a "Go...

Discussion

  1. Peter Galiba

    Or maybe just put a link there. You can put block elements inside links, and you can make links block elements.

  2. This is an excellent step in the right direction (I hate that too), but is there an equivalent for long-pressing on mobile?

  3. I think so: window.location redirect will give us usability boost. Thanks…

  4. Przyb

    But it will still suck on mobile. Would be nice if we could fix this with html5 context menu, shame for no support in WebKit http://davidwalsh.name/html5-context-menu

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