Archive for the ‘jQuery’ Category

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<br />');
    });
    $(window).blur(function(){
        document.write('blurred<br />');
    });
});

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 reselect a default option in a select box on the fly with jquery

How to reselect a option on the fly in a select element using jquery.

This always annoys me a little bit as I seem to have a tendancy to forget the solution, so I thought i’d just blog it this time round for future reference and hopefully it might also help someone else.

What I need it for quite often is setting a select box back to the default when using the select box to repopulate other elements on the page ie using the .change() function on the select box element.

Normally my solution for resetting it now is just this.

$("#elementID option[selected]").removeAttr("selected");

This will just set the focus back to the selected=”selected” element in the original html. Of course you could extend this somewhat further and perhaps actually set a new one if your list is not populated dynamically like so.

$("#elementID option[value='Today']").attr("selected","selected");

Hopefully this will be useful.

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.

Scroll To The Bottom Of A Page With jQuery

Today I was faced with the small problem of scrolling to the bottom of a page using jQuery. I noticed while trying to find a quick solution around the web that there was a distinct lack of examples, so I decided just to make my own code.

This will simply scroll the window focus to the very bottom of your page, which can be handy in some cases.



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.

Beginners Guide To jQuery

A while back I faced the daunting prospect of learning yet another language, jQuery. At the time I had a little to average knowledge of javascript, I would recommend you to stop reading if you do not have any prior knowledge of javascript or other similar programming languages.

As web sites march forward and us programmers look for ever more elaborate and space saving ways of delightfully cramming our pages with as much content as we can whilst also doing it within a respectable time frame, some life saving javascript libraries have emerged. Elaborate javascript effects have always been possible, but for clients not willing to pay that bit extra for the time it would normally take to build and utilise such features and for programmers not willing to spend the time on some projects, these features have sat very much in the dark corner of the room. Untill now! In relatively simple commands using jQuery you can achieve some actually very complex and cross browser compatible javascript functionality. Which not only looks really cool, but in use is very, very practical!

How to use jQuery

Using jQuery couldn’t be any simpler, head over to the jQuery website and simply download the library. This consists of only one file, which makes everything even more simple!

Upload this file to somewhere on your server and then include it to the head of the page you want to test something on, it should look something like this.







Im only going to touch on what you can do with jQuery in this topic as I want to focus on the main principles of switching from coding using your basic javascript mark up, to using jQuery. Alot of people refuse to make the move from javascript to jQuery or simply do not see the point. I think in alot of ways thats rather sad, especially when you consider the time it can save you and the simplicity in which otherwise complex javascript can be added to your pages. Yes like many other things it cannot do everything, but whats so great about it is that it can be mixed and matched with regular javascript.

The massive plus point for me using jQuery is its pretty much give or take cross browser compatible. At least the core of it is, this is a hugely important factor when choosing to use jQuery as we all know how javascript is rendered differently in every other browser. So leave the compatibility issues up to someone else and focus on your website, is what I say!

A Simple jQuery Example

Im simply going to show you the very core of any javascript or jQuery application. The selector! In regular javascript were all very used to using the following code to select an element from the dom (or page) by its id.

Add this div to the body of your test page:

Then add this code to the head of the page.



This is a extremely simple example, but I think it demonstrates nicely what jQuery stands for, “do more and write less!”
One of the most important functions available to you when using jQuery is the following:

$(document).ready(function(){ });
As the name suggests this calls and runs whatever is inside the function when the document is ready ie when the page finishes loading. Try inserting the code below into the head of your test page.



Another very important thing to learn about jQuery is how it works, differently to normal. For instance say we have a button that we wanted to fire a javascript when it was clicked, jQuery provides ways to bind events to elements. Ie if you click my button I can bind an event to that button on page load and when you click it fire a function of my choice. Where as conventionally before you would have attached the event as an attribute to the element. For example a onclick=”alert(‘clicked’)” on an element. Where as I could do the following with jQuery.

First add the button to your page


Then add the jQuery below to the head.


You will see an alert pop out with the text “You clicked my button”.

Selectors

Selectors are hugely important factor of selecting elements from the dom or the page to a non programmer. jQuery allows you to use numerous ways to select elements. Im only going to touch on a few of the most important ones, have a look at the following examples.


//# selects by the id of the element like so : $("#mybutton");
//. fullstop or a dot select by the class of the element like so : $(".mybutton");
//using a tree or selecting multiples elements by there element type
// selects all divs on the page $("div");
// selects all spans within a div on the page $("div span");

As you can see rather than using regular javascript to do the same its very very quick to code and works really well.

Im going to touch on one last subject in this small tutorial and thats binding of events to the same element. Earlier I showed you how to bind a click function to an element, but what jQuery rather uniquely does is enable you to continuously bind function after function to that element. So in the same function I could lets say add a click function and also a mouseover function with an action in it to change the color of the button. I’ll give a quick example below.

Using your button with the id of “mybutton” that you should have inserted into the body of your test page. Add the following code to the head of your page.

In this one line of code I can now tell whether you moused over the button and then perform an action if you do and whether you clicked the button or not. Hopefully your starting the see the scope and speed of this scripting language. Thats it for now, check my jQuery category for other posts about jquery.