permalink

84

Catch404 – A jQuery And CSS3 Modal Plugin For Handling Broken Links Elegantly

 

Hey guys. I’ve got a brand new jQuery plugin for you today. Let’s talk about the problem we’re going to be solving with it first: Broken links and 404 Errors are a problem that have plagued almost all websites since the dawn of the internet – they’re just a really bad user experience and we’ve all encountered them.

There’s nothing attractive about clicking a link hoping that it’ll take you to your destination only to find out that the page doesn’t exist. In most cases you’re left having to figure out what to do next – do you hit the back button? do you go googling the file to see if you can find it?. In some cases they can be a total show-stopper, so what can we do to change that?.

Today I’d like to present a new jQuery Plugin I wrote called Catch404. Through the magic of jQuery we’re going to catch 404 errors without your users even having to leave the page and then suggest some other options they’ve got using an inline jQuery Modal window. So, why it this useful and how does it work?.

 

View Demo  Download Source

 

 

Why Is Catch404 Useful?

Let’s pretend that this is a broken link. Can you imagine that when your users click this link, instead of them being redirected to a 404 error on your site, a friendly modal message pops up on your current page saying that it’s not available?. In that same message box you can then give them a sense of direction so that they’re not lost – you could ask them to click on a contact link to report the link’s broken, offer an alternative mirror, recommend they do a site search for the file or just say that you’re experiencing hosting issues and the file will be back up soon. The choice is completely up to you. The benefit of Catch404 is that you can offer your users a better experience when errors are encountered on your site.

 

 

How Does Catch404 Work?

The basic idea behind Catch404 is that you perform an Ajax query for a URL and handle the response provided accordingly, so if its a 404 error, we handle this error specifically. Now because cross-domain 404 handling with jQuery is something that has often been problematic to correctly implement, achieving this isn’t as straight-forward as it should be. Instead, the plugin uses a neat trick using the Yahoo YQL Engine to access the URL for us which returns a HTML string (local URLs don’t require this hack) – thanks to James Padolsey and Christian Heillman for their work in this area. Depending on the contents of this string response, we’re then able to handle the error from the same page the user tried clicking out from. In my plugin, a modal window is used to render the error message and it’s here that you’re able to define whatever message, links or tips that you would like to offer your users regarding the 404. This offers a much better user experience than traditional 404 handling because rather than taking them somewhere with no content, you’ve now got the option to either present them with an alternative mirror or advice through the modal window.

 

Let’s take a look at the jQuery under the bonnet!

As you can see in the code snippet below, the most advanced piece of code in this plugin is the part that performs the above 404 handling. Because we’re connecting up to a third party site (Yahoo) in order to access this URL, there is going to be a wait of about a second or two during our query and this is the case for URLs that are valid as well as those that aren’t. To ensure your users are aware of whats going on it can be useful to display a progress overlay on your page with the label ‘Checking URL status..’ or something similar.

 
//Perform the Ajax JSON call to get the Yahoo YQL response for the URL
   function performAjaxCall(url,msg,container)
  {
    if(url.match('^http')){
      msg.html(' (checking...)');
      //connect to yahoo YQL to get a response for the URL
      $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent(url)+
                "%22&format=xml'&callback=?",
        function(data){
          if(data.results[0]){
            var data = filterData(data.results[0]);
             //if the url passes the test, navigate to it
			donav(url);
          } else {
            msg.html(' (404!)');
            //otherwise display the modal error window
	    fourPop();
          }
        }
      );
    }

   

and now we define our modal window function as follows:
function fourPop(){
		var popWidth = 500; //dim[0].split('=')[1];
		var popID = '404message';
		$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('Close');
		var popMargTop = ($('#' + popID).height() + 80) / 2;
		var popMargLeft = ($('#' + popID).width() + 80) / 2;
		//Apply Margin to Popup
		$('#' + popID).css({
			'margin-top' : -popMargTop,
			'margin-left' : -popMargLeft
		});
		//Fade in Background
		$('body').append('
 
'); . $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); return false; }; //Close Popups and Fade Layer $('a.close, #fade').live('click', function() { $('#fade , .popup_block').fadeOut(function() { $('#fade, a.close').remove(); }); return false; }); }); }
 

How Do I Use Catch404 On My Site Or Page?

Using Catch404 will help you keep those broken links and fail whales at bay, but the best news is it’s relatively easy to start using straight away. All you need to do is first include jQuery and catch404.js in your page and then call the catch404() function on a selector as follows – it should apply it to the links with that particular class or id and you’re all set. In the following case I’m using the class ‘ajaxcheck’ to indicate links on the page that I would like checked using Catch404.

HTML

This is a link to check


JavaScript

$(document).ready(function()
{
$(".ajaxcheck").catch404();
});

Demo and Download

To see a fully featured demo of Catch404 in action, just click the demo button below. You can also download the plugin and source files via the Download button if you’d like to start using it in your projects.

 

View Demo  Download Source

 

Thanks for reading and I hope Catch404 helps you to keep those broken links, 404′s and fail whales at bay. To share this article with your friends click Catch404 – A jQuery And CSS3 Modal Plugin For Handling Broken Links Elegantly now. Good luck with your projects!

- Addy.

84 Comments

    • Absolutely. This doesn't change the underlying links in your page in terms of what a bot sees. It's just pure HTML that has some jQuery applied on top of it to enable all of the Catch 404 features I've mentioned above.

    • I could always alter it to push the redirected URL into a new tab or window. That would allow you to still be able to get back to the previous page (in cases where it does in fact exist)

  1. When I click on the working link, my back button isn't working or hasn't registered that I was elsewhere before I got to Google

  2. I certainly don't think its a good idea to iterate over all your links and modify the dom to unlink anything that comes up as a 404. I can see using this occasionally if you find yourself linking to sources that don't seem entirely reliable but if that is the case I'm not sure I would link there in the first place.

    Either way, I'm sure there are good use cases for this. Thanks!

  3. I think if I were to use this I would periodically make the js iterate over the links on a page…maybe once per week, definitely not once per page view. Then if any links are 404s unlink them for that session and fire off an email to the maintenance person/team/AI robot notifying them that they need to update that link.

  4. As you're checking to see if the link's destination is available or not, you could also check the availability of the destination on Google Cache or the Wayback Machine, showing their links in the dialog.

  5. Pingback: Handle Broken Links Nicely with Catch404 jQuery Plugin | Webplus - web developer resource blog

  6. Seems like a good programming exercise for you to create this plugin, but it would be fairly irresponsible to put this on a live site. For every link the user clicks, it adds additional unnecessary overhead AND breaks the back button. You're requesting the URL twice (if it exists) to protect the user from seeing a 404 page. This only seems logical if you have more 404 links on your site than working links, which seems unlikely.

    I certainly don't want to discourage you from experimenting and releasing code, but I do feel that, as developers, we have a professional responsibility to review code (especially code packaged as a plugin).

    • Where I thought this would be useful in particular is blogs for example. On tech sites we have a tendency to reference each others work via links and on many occasions you can see links that just don't exist anymore. I would of course not recommend this be applied to every link on the page (catch404 supports just applying it to a particular selector) but if you applied it to just a portion, such as the blog content/blog html, it could offer a bit of use :)

    • to avoid breaking the back button you can wrap document.location.href = url within setTimeout. It will do the trick.

      setTimeout(function(){
      document.location.href = url;
      },0)

  7. I have to agree with Zach – this seems to be a bit of overkill.

    IMHO, the better approach would be to use a regular 404 page… but on that 404 page do the following:

    1.) Inform the user the page couldn't be found
    2.) Provide a few useful links: e.g. Home, Back, Search (for the search if you can pass in any relevant search terms from the failed request) e.g. if I went to "somedomain.com/products", passing "products" into the search would likely be helpful
    3.) automatically send an email/log the 404 so that the developer can automatically fix the issue (if there is one) – in my case, I send a special email (from a web app) that includes the logged in user, the referrer page, the 404 url, date/time, etc.

    I find the last item to be awesome. I've had a user or two find a genuine broken link in my app… they happily went either to the Home page, or did a search… I got the email alerts and (I should note its a fairly techy app) sent them a quick email reply indicating: "sorry about the broken page you found, but thanks for finding it!… I've already fixed it!"

    • All you need to do is include jQuery and the plugin in your page and you can then use the catch404() function to apply it to a particular class of links (or all the links) on your page.

  8. Pingback: 15 Freshes & Attractive jQuery Plugins « The Creative Project

  9. Pingback: Handle Broken Links Nicely with Catch404 jQuery Plugin « EFW Design

  10. Great thing about this script is that it do not force user to navigate to and error page(for broken) and user can remain on same page if link is broken but it is really slow for external links; working find for internal links.Need serious speed improvement.

  11. Pingback: リンク切れをその場でポップアップ通知するjQueryプラグイン「Catch404」 - WEBマーケティング ブログ

  12. Pingback: Beautify Broken Links With Catch404 | Tech Alps

  13. hi, very nive job!
    i have a question:
    why do you use getJSON() and in the url you use "&format=xml" and not "&format=json"

    But it works well and this is the goal :)

  14. Pingback: Smarter Links With jQuery: Catch404 | Free Web Resources

  15. Pingback: Smarter Links With jQuery: Catch404 | Site Design Tips

  16. Pingback: Catch404 – jQuery Plugin For Handling Broken Links Smartly | jQuery | Graphic Design Junction

  17. Pingback: Catch404 – A jQuery plugin | Webappsdepot - Web Resources, CSS, Ajax, Tutorials, JavaScript, Tools, etc

  18. Pingback: Handle Broken Links Nicely with Catch404 jQuery Plugin | CubIDWeb - Online file resources

  19. Pingback: Evita la redirección para enlaces inválidos con Catch404

  20. Pingback: Smarter Links With jQuery: Catch404 :: Graficznie

  21. Pingback: リンク切れのページをポップアップでお知らせするjQueryプラグイン「Catch404」 | Web活メモ帳

  22. is it possible to port this feature as a wordpress plugin? i mean, your blog is wordpress wouldn't it be easier to make it a plugin so everyone with wordpress can implement it easier?

    • Hey there!. I would have loved to port this over to a wordpress plugin but due to time-constraints (clients, the books and magazine articles I work on too) I usually don't have the time to do more than what I post up. If someone else wanted to take it through to a wordpress plugin project though, I'd be more than happy to lend them my support.

  23. I'm wondering how google, bing and yahoo's seach engine bots will view these redirects and 401 pages from an SEO perspective. For instance, will google recognize a 404 page from dead link or what will the search bot see?

    • Most bots don't take JavaScript into account so from an SEO perspective this approach should be fine. The JS features are only activated on page load and as I mentioned, I think most bots will just notice a genuine 404 as a genuine 404.

  24. Pingback: Handling 404′s with JavaScript | ChurchCode

    • Hey Devin,

      One could extend the plugin to work with hash tags to smooth the transition over to something like this if you wanted to maintain support for the back button.

      There are of course a number of other approaches which could be taken to solve this issue which may be better than the above.

      When creating this I really just wanted to display a POC, but it\’s really interesting to see the real world applications and how something like this may need to be modified to cope with them.

    • The only thing you may need to keep an eye on is the traffic from the Yahoo YQL look-up engine. If you notice a significant number of queries coming from there, it may be wise to filter that data out of your traffic stats, but other than that you should be fine.

  25. Hey Marcus,

    Thanks for your comments. A lot of the content you'll find on my site is very much proof-of-concept. I don't necessarily say that it should be used in a production environment, but at the same time, the code is there for the instances or projects where a developer may find it useful.

    Addressing your points:

    You mention that this might screw up site stats and affiliate stats – after I posted this I actually had a few companies contact me regarding this problem and I created them a custom solution using similar methodologies behind Catch404 which handled their stats without any errors or issues. That solution also only got applied on a particular type of link rather than every single link on a site and so it was perfect (for them) from that viewpoint. Obviously the idea of using it on ALL the links on your site is something no developer would advocate as a great idea.

    Catch404 is not production ready in it's current form – what I do recommend people do though is take what you can from the demo that I have provided and custom adjust it as per your own needs. You can avoid having to request every link twice (or limit it where necessary).

    Hopefully the solution can be found helpful in a few projects.

  26. Pingback: LiveWebResources » Elegant handling of broken links using Catch404

  27. Pingback: catch404 mit jQuery und CSS3 | carmadesign! Blog

  28. This is quite a plugin. Very nice and easy to implement.
    I would like though to be considered another situation: to have a timeout if no Internet connection is present at all.

  29. Pingback: Beautify Broken Links With Catch404 | msweb-solutions

  30. Pingback: Adding catch404 to any link within an WordPress article automatically | carmadesign! Blog

Leave a Reply

Required fields are marked *.

*