DotNetCurry Logo

Extending jQuery and Writing Custom Logging for Your Application in JavaScript

Posted by: Malcolm Sheridan , on 12/2/2009, in Category jQuery and ASP.NET
Views: 34631
Abstract: The following article demonstrates how to extend jQuery by creating your own method to log data to the console object.
Extending jQuery and Writing Custom Logging for Your Application in JavaScript
 
When you work with jQuery allot, you realise how easy it is to get carried away with coding, and by the time you look up from your keyboard, you’ve created tonnes of code! A nice way to log data when you’re working with JavaScript is to log data to the console object in Firefox if you have Firebug installed. Hopefully you’re using Firebug! It’s a valuable development tool. Firebug adds a global variable named "console" to all web pages loaded in Firefox. The console window is also available in Google Chrome. The console object contains methods that allow you to write to the console to expose information that is flowing through your scripts. The end result is you’ll be able to log data by using the following statement:
jQuery.log([your message]);
For this example you don’t to create a Visual Studio project. A simple HTML file will do.
The console object is available in Firefox and Google Chrome, so for this to be compatible with other browsers such as Internet Explorer, I’ll write the debug information straight to the window. Okay let’s get started! Writing to the console object is simple. You write the following line of code to log data:
console.log(“Hello world!”)
The code above is nice and simple! Next I’m going to extend jQuery and create a custom function that I can call from anywhere in my code. To extend jQuery you use the jQuery.extend function. Here’s the complete code below:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>jQuery</title>
    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script language="javascript" type="text/javascript">
        var debug = true;
        jQuery.extend({
            log: function(msg) {
                if (debug) {
                    if (window.console) {
                        // Firefox & Google Chrome
                        console.log(msg);
                    }
                    else {
                        // Other browsers
                        $("body").append("<div style=\"width:600px;color:#FFFFFF;background-color:#000000;\">" + msg + "</div>");
                    }
                    return true;
                }
            }
        });
 
        $(function() {
            $("#Button1").bind("click", function(e) {
                jQuery.log("Hello");
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <input id="Button1" type="button" value="button" />   
</body>
</html>
In the code above I have first created a variable that will enable/disable logging data:
var debug = true;
To extend jQuery, I am using jQuery’s extend function. I check if the console object is available. If it is, I call console.log to log the data. If it’s not, then I simply append a new <div> tag at the end of the <body> tag to print the data.
jQuery.extend({
log: function(msg) {
                if (debug) {
                    if (window.console) {
                        // Firefox only
                        console.log(msg);
                    }
                    else {
                        // Other browsers
                        $("body").append("<div style=\"width:600px;color:#FFFFFF;background-color:#000000;\">" + msg + "</div>");
                    }
                    return true;
                }
            }
});
If you run the example and click the button in Firefox, you can open Firebug and see the data being logged to the console window:
FireFox
If you run the page using Internet Explorer, the console object is not available, so the data will be printed in the window:
InternetExplorer

Hopefully you find this small piece of code useful. It certainly has helped me out recently whilst trying to debug hard to find issues in JavaScript. See a Live Demo here.

If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

Malcolm Sheridan is an independent contractor who has been working with Microsoft technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly enjoys ASP.NET.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by philbo on Thursday, December 3, 2009 1:14 AM
I so so so much love your jqeury article. please show more to use mvc and jquery along
Comment posted by ReTox on Thursday, December 10, 2009 8:11 PM
suggestion: log all parameters sent to log function

        for(var i=0; i < arguments.length; i++) {
            if (window.console)
                console.log(arguments[i]);
            else
                $("body").append("<div style=\"width:600px;color:#FFFFFF;background-color:#000000;\">" + arguments[i] + "</div>");
        }
Comment posted by Malcolm Sheridan on Friday, December 11, 2009 8:56 PM
@philbo
Thanks.  I'll have more articles on mvc and jQuery in the future.

@ReTox
Nice suggestion!
Comment posted by custom writing on Tuesday, June 15, 2010 4:01 AM
I like your tips!
Comment posted by jim on Thursday, November 11, 2010 6:11 PM
sorry about previous error http://www.becomeadrivinginstructor.org.uk/
Comment posted by Recepti on Monday, November 15, 2010 11:50 PM
I want to thank you for this great read! I really enjoyed reading.
<a href="http://www.recepti.hr/">Recepti</a>
Comment posted by marius on Monday, January 24, 2011 2:36 PM
good article thans