How to detect blur of browser tab and re focus of browser tab with jquery

Its been a while since I last posted anything on my blog, and its mainly not through the want of trying, but more that I haven’t had the time to keep posting the things I find in my travels. However to try and keep up I have another interesting and potentially time saving / useful addition to make today.

How to detect when a user moves the focus of his/her browser to a different tab than yours. And also subsequently how to tell when your tab regains the focus of the user when they reselect it. This is useful why? Ever wondered how facebook and twitter update the title of the tab to inform you of how many messages or tweets you’ve missed out on while not focused on the tab. Then i’m just about to nail it.

It’s really quite simple, but the usage of it can become complex and very useful, particuarly to the efficiency of your app. For instance if a page requires being updated by an intervalled ajax call say every 5 seconds when a user is focused on the tab. Perhaps when it loses focus you could increase the interval time, to say 30 seconds. As while they are not looking at the tab, they probably don’t need to be updated so often. Then when they refocus you can just set it back to normal. This will improve the efficiency of your app.

Here’s how it can be done with a tiny little bit of jQuery magic.

$(document).ready(function(){
    $(window).focus(function(){
        document.write('focused
');
    });
    $(window).blur(function(){
        document.write('blurred
');
    });
});

Any questions i’ll be happy to answer them, perhaps i’ll even show you how you can turn this example into a more useful one later.

Programming large scripts in javascript using object orientated style coding

This week whilst coding a large javascript / jQuery script for one of our online games which started to grow to an unmanageable size and needed to be compartmentalized I decided to review my techniques.

Previously for scripts which were quite large I would create an object which contained lots of different methods like so. As you should already know in js its all about scope.

So here’s what I used to do:

function page(){
this.funcName = function(param){
alert("hey man this is a cool little function);
}
}

I’d then go and call this function into the page like so.


var mypage = null;
function init(){
mypage = new page();
}

$(document).ready(function(){
init();
});

Which then gives you full access to call objects of page via access of the mypage var.

This works fine, but meant that all of my code was inside one very big ass object. Not so great. 2000 lines later, even less great. 2000 lines later and finding out I need to use aspects of it for one page and not another, awful.

So I set out to find a change in practise and this is what I came up with. This is not a new technique, nor do I personally claim I came up with it. Just my take on things I read.

My new plan was to create a base script, which was then interfaced by several smaller scripts dependant on the view.


Post={
newmsg: function(){
alert("hey there man, how goes it?");
}
};
pgAjax={
request: function(options){
//could add some extension of the defaults for a jquery ajax call here
}
}

Hopefully from the above you can start to see its benefits. By compartmentalising it, I made it much easier for me to keep code housed in segments, the objects can also be called via inline commands like onclick=”Posts.newmsg();”

I interface the base with a series of smaller files based on the view, similar to this.

leadview.js
$(function(){
$("input[type='button']").click(function(){
Posts.newmsg();
});
});

Obviously this is massively simplified, hopefully this might help though. Feel free to leave a comment if you wish for me to expand on this.

How to enable some web developer tools for safari mac

If your like me and sometimes need to debug js in different browsers for web development. Sometimes its helpful to use debugging tools available with different browsers. Mozilla has the really useful firebug tool, which I use all the time and which is easily installed via mozillas browser plug in environment.

Safari on the other hand is a little trickier, I stumbled accross this today which certainly helped me.

Open up a terminal window on your mac and run this command

defaults write com.apple.Safari IncludeDebugMenu 1

Quit Safari and reopen, you should now see a ‘Develop’ tab along the top of your mac toolbar (where preferences is).

You can use this to do all sorts of useful profiling of your scripts on safari, which I have found most useful.
Enjoy.

Facebook Style Alternating Page Title – With jQuery / Javascript

This afternoon i’ve been trying to work out how facebook detects whether or not your focused on its interface or not. Ie focused on the browser tab.
Triggering a $(window).focus(function(){}); event in jquery will in most browsers solve coming back to the browser tab if your away from it, but in respect of how it detects on success of an ajax call whether or not to change the page title based upon if you are focused on the tab or not is still a mystery to me.

Can anyone shed any light on this?

I am now beginning to think, facebook uses a sly dog in the mix in which it detects if you have a mouse move over the body of the page, and when you do initiating all required requests.

jQuery Custom Ajax With Wrapper Layer

Whilst working on our online game Street Crime – Mmorpg Gangster Game I came accross the need to add a wrapper layer to all of our ajax calls thus to make sure players are always logged in before they make the call and if not then re-direct them too our login pages.

Most of you who are familiar with jQuery will also be familiar with the $.ajax() function that is commonly used for making ajax requests.

I decided to use jQuerys plugin functionality to create the wrapper layer.


jQuery.AJAXwrapper=function(options) {
var defaults = {
extensions: '',
theurl: '',
thetype: "POST",
defaultdataType: "xml",
payload: ''
};
var options = $.extend(defaults, options);
$.ajax({
url: options.theurl,
type: options.thetype,
data: options.extensions,
dataType: options.defaultdataType,
beforeSend: function(){
//in here insert your custom function
},
success: function(xml){
if(typeof options.payload==='function'){
options.payload(xml);
}
}
});
};

I call my function above by using a simple bit of code that you can added to any action/event you like.

$(document).ready(function(){
$("#myid").click(function(){
AJAXwrapper({
theurl: "somephp.php",
extensions: "action=refresh",
payload: yourcustomfunction;
});
});
});

And finally I stick an alert in the custom function I have selected to be my on success from the AJAXwrapper function.


function yourcustomfunction(){
alert("we made it to this bit");
}

There you have it now you could make all of your ajax calls using AJAXwrapper({}) and its possible values which I have listed below for clarity.

  • extensions – These are your normal ‘data’ fields in the normal $.ajax() function so something like ‘action=fred’
  • theurl – Quite simply the url you want AJAXwrapper to call
  • thetype – The type of request your making GET,POST default is set to POST
  • defaultdataType – The default data type of the call my function is defaulted to xml, but you could choose JSON,HTML etc
  • payload – Finally the payload, this is your defined function for AJAXwrapper to call when your request comes back successfully.

Form Input Validation With Javascript

Input validation with javascript is an essential part of any large day to day website. Its major advantage is that it can be processed client side thus avoiding avoidable load on the server.
If your running a PHP based website which is struggling to cope with load and your using basic php form validation. You could switch your form validation to Javascript.

You should treat your javascript validation as your first line of defence, as javascript source can be read by a user its easy enough to work around it if you know what your doing. So you will still need to keep your second line of defence ie your PHP code to do the second lot of checking.

However the javascript will help to limit load for people who genuinely make honest mistakes.

Heres a example of form validation.

Firstly lets make our Form

[sourcecode='html']

Whats your name:   

function checkform ( form ) { // ** START ** if (form.yourname.value == "") { alert( "Please enter your name." ); form.yourname.focus(); return false ; }

return true ; }

[/sourcecode]

This will simply check to make sure they have not tried to submit the form without entering anyting in the input box.

This is a very very simple version of a javascript validation.

[sourcecode='javascript']

[/sourcecode]

Here we have added another line of validation to check to see they at dont try and just put one character in the box using javascripts .length function.

I will add some more to this post later, including email validation and more.