Use your left/right keys to browse tutorials
jQuery Iphone Style Ajax Switch

jQuery Iphone Style Ajax Switch

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on July 3, 2009

I’ve been looking for a while at how to mimic the iPhone on / off switch with Jquery and stumbled across this post By Daniel LaBare over at elctech.com which is a great start to base an ajax tutorial on. In this tutorial I’ll purely be looking at making a simple ajax request using the functionality of the iPhone buttons to trigger a script to return a string based on whether the switch is on or off. You need to include the ‘jquery.iphone-switch.js’ file along with jquery which is in the download.

The Code:


<div id="ajax"></div>
<div id="1"></div>

<script type="text/javascript">

$('#1').iphoneSwitch("on",
function() {
$('#ajax').load('on.html');
},
function() {
$('#ajax').load('off.html');
},
{
switch_on_container_path: 'iphone_switch_container_off.png'
});
</script>

So to run through whats happening when the iphoneSwitch() function is called we run an ajax call to return the contents of the pages on.html and off.html. You could make this more dynamic by calling a php page which authenticates a user with a session id which would then update data in a database depending on the switches current status.

looking at jQuery .load:

Another way of using the .load function is to pass POST variables through to a script for example below we are passing the POST variable ‘limit’ with a value of ’10′ to the file rss.php and asking it to load the results into the div #rss, once the ajax request has completed it will alert ‘The last 10 entries in the rss feed have been loaded’:

$("#rss").load("rss.php", {limit: 10}, function(){
alert("The last 10 entries in the rss feed have been loaded");
});

demodownload



Recent shares

More tutorials from Papermashup
Comments
61 discussions around jQuery Iphone Style Ajax Switch
  1. Regis Grison says:

    Hi,

    I had to do 2 minor changes : I needed to override 2 settings (background-position & speed) so I haded this parameters.

    May I submit it to you?

    • Marcio says:

      Submit it to me at least, please. Or let it online for download. I updated the jquery and it’s not working any more. I’m trying to see what’s wrong. Regards.

  2. Pingback: 分享19个值得学习的jQuery和CSS按钮教程 | 站长站

  3. Robin says:

    You note:
    “You could make this more dynamic by calling a php page which authenticates a user with a session id which would then update data in a database depending on the switches current status.”

    OK, how might this Ajax switch be used as a ‘mechanical’ captcha? That is, to submit a form, switch presents as default OFF, and must be switched to ON.

    I figure you’d need to output some string for a hidden field that’s then validated (jQuery validation?) to allow form submission.

    Ideas welcome.

  4. Joe says:

    Wish there was an updated image for this tutorial :)

  5. Pingback: 無料Jqueryボタンデザイン - ismartop blog

  6. Matt says:

    This works great – lightweight and easy to implement! Thanks!

  7. pitchalite says:

    IE8 issue

    For all facing IE8 issue.. there is a bug in the source code at line no.37

    Instead of a closing tag tag is used.
    Fix this and it will work in IE8.

    Ofcourse it will still look stupid in the stupid browser IE..
    have fun

  8. Buy Things says:

    Useful info. Fortunate me I discovered your site unintentionally, and I am stunned why this twist of fate didn’t happened earlier! I bookmarked it.

  9. Meee says:

    thanks -> very nice -> but thats the iOS 4 GUI -> and not the new iOS 5 :)

  10. Thibaut says:

    Hi,

    How can I do that in javascript I can decide whether the switch is on or off? But not in .js

    Thanks

  11. I have been surfing online greater than 3 hours lately, but I by no means discovered any fascinating article like yours. It?s pretty value enough for me. In my opinion, if all website owners and bloggers made excellent content as you did, the web shall be much more useful than ever before.

  12. persa says:

    Hi, Nice Work, How to change background color ( black/white ) or any css with this ?

    Thanks
    Best Regards

  13. This works almost perfectly in IE if you just delete the unnecessary jQuery() following image = (line 37) and change jQuery(image) to just image (line 40). The changes Andy suggested above didn’t help in my case, and are not needed

    The animation moving to Off works great, and the only thing not perfect is that it instantly turns to On without an animation. I haven’t bothered tinkering to try and fix this, but I would think if the animation works in one directly, it should work in the other, but for now, I’m not worrying about it.

  14. Andy says:

    The problem seems to be in this line of code –

    image = jQuery(”);

    and

    jQuery(this).click(function() {
    if(state == ‘on’) {
    jQuery(this).find(‘.iphone_switch’).animate({backgroundPosition: -53}, “slow”, function() {
    jQuery(this).attr(‘src’, settings.switch_off_container_path);
    switched_off_callback();
    });
    state = ‘off’;
    }
    else {
    jQuery(this).find(‘.iphone_switch’).animate({backgroundPosition: 0}, “slow”, function() {
    switched_on_callback();
    });
    jQuery(this).find(‘.iphone_switch’).attr(‘src’, settings.switch_on_container_path);
    state = ‘on’;
    }
    });

    When i remove background-position:’+(state == ‘on’ ? 0 : -53)+’px” from first bit of code – then I can see the ON/OFF image on IE but once clicked, it’s again get disappeared. Looks like IE doesn’t like background-position property.

  15. Andy says:

    Hello, Did anyone found any fix for this IE6 ON/OFF text issue?

  16. Andy says:

    Also, if you try to view this example demo on IE6 -it will show you the blank image with no ON and OFF display.

    Any fix??

  17. Andy says:

    As Igor said – I have removed extra div in jquery.iphone-switch.js, now i can see the switch image on IE6 but it is just blank – it doesn’t display ON or OFF?

    Any ideas to get it working on IE6? Ashley, I guess you forgot to update the code as that extra div still exist in jquery.iphone-switch.js

    Thanks

  18. Reedyseth says:

    @raf Of course you can.

    $('#1').iphoneSwitch("on",
    function() {
    // do wherever you want when the switch is on
    $('#ajax').load('on.html');
    },
    function() {
    // do wherever you want when the switch is off
    $('#ajax').load('off.html');
    },
    {
    switch_on_container_path: 'iphone_switch_container_off.png'
    });

  19. Raf says:

    Hi,

    I would like to know if it’s possible to associate an action like a script or url with the switch on/off?
    Thanks

  20. jerry5 says:

    thx for your reply, i will try your suggestion later.
    working something correctly on IE is always a pain….

  21. jerry5 says:

    thx for your reply, i will try your suggestion later.
    working something correctly on IE is always a pain….

  22. Austin says:

    Anyway to possibly use the status of the switch in code?

  23. Reedyseth says:

    @jeery5 making work this on IE is a pain but the first thing you can try is to update the jQuery APi to the latest version(1.6.2). And you can check w hat I say to Varun DHawan.

    @Varun DHawan For some reason is not working on IE8 but you can debug the script and see where is the problem, for instances you may get undefined variables, verify where this is happening. I have something similar using the attr() method and used prop() instead. The same problem with find() and used children() instead.

    Hopes this may be helpful to both of you.

  24. Austin says:

    Do you by chance have the .psd for the switch? I’d love to make multiple skins for it

    Austin

  25. Andy says:

    Hi,

    How does the button load in this script? It works when i place the code in individual page and run it but when i try to place the script in one of the master template to run it when appropriate and place it on the left sidebar – the switch button doesn’t display. I think for some reason it’s not calling javascript/jquery? Any ideas what could go wrong??
    Thanks

  26. Varun DHawan says:

    Hi,

    I am using tthis with jquery 1.6 version. It doesn’t work for IE8.
    Can you suggest me something.

  27. jerry5 says:

    Does anybody know how to fix its compatibility issue on IE6?

  28. Andrew Solomon says:

    What would be the best way for the style switcher to be dynamic? Moreover, I would like the switch to stay OFF after a page refresh. Is there a way we can store the value of switch within the Dom or maybe a dynamic PHP variable?

  29. Reedyseth says:

    @todd I think that you just have to make same tags with different Id and the make reference to it on the Javascript, hope this may be helpful, regards.

  30. todd says:

    Does anyone know how you could use multiple instances of the slider on the same page? I have been tying to work on it with no success.

    Todd

  31. Igor G. says:

    Hey,
    thanks a lot. This is a very nice plugin!

    Igor

  32. Sam Woodard says:

    Have you considered putting the src on github?

  33. Maurizio says:

    for jquery 1.4:
    $(this).load(url…

    made the trick!

  34. dirkuijt says:

    got it working on chrome, but not on IE8…
    Any tips?

  35. BigDirty says:

    Not working with jquery 1.4.4 or 1.4.2 in IE8

  36. BigDirty says:

    Doesn’t work with jquery 1.4.4 or 1.4.2 in IE8

  37. lucky says:

    I have tried this plugin for my project development
    iphone app development

  38. Aman says:

    Hi

    I like this plugin.I have Also 10+ Jquery Style Switchers plugins please see:-

    http://jquery13.blogspot.com/2010/08/10-jquery-style-switchers.html

    Thanks
    Aman

  39. MariusV5 says:

    Excude me, I’ve a problem with Iphone Ajax Switch and Internet Explorer.

    When I go over the object, after the opening, launch the IE error:

    Messagge: Invalid argument
    Line: 23
    Character: 1286
    Code: 0
    URI: file:///C:/Users/xxx/Downloads/ajax-switch/ajax-switch/jquery.js

  40. doc says:

    Hi,

    great work.

    but could it be possible to change the switch state using code after having initialized it?

  41. Pingback: jQuery Enhanced CSS Button Techniques

  42. Pingback: 20 Awesome jQuery Enhanced CSS Button Techniques - Speckyboy Design Magazine

  43. Hunter says:

    Check this out! It is the same thing but you can drag it!

  44. Stephen says:

    Hi… nice little plugin here….

    I’d like to make one suggestion….

    change the “click handling” section to pass the through to the callback events, a la:


    jQuery(this).click(function() {
    ...
    switched_off_callback(this);
    ...
    switched_on_callback(this);
    ...
    });

    that way


    $(".Boolean").iphoneSwitch(
    "on",
    function(obj) {
    //do something on change to "on"
    },
    function(obj) {
    //do something on change to "off"
    }
    );

    that way if there are multiple objects wired to this plugin, there is some hook to be able to tell “where” we are inside those events…

    thanks for reading….

    - Stephen

  45. Leny says:

    Thank you Ashley for your post, cool demo :)
    Does anybody know why on IE6 it doesn’t work?

  46. Igor says:

    ERROR!
    text code inside file jquery.iphone-switch.js:

    image = jQuery(”);
    Pay attention to the end – there is an extra div-tag! It must be removed, otherwise, you will not see the switch in IE-browsers.
    Thanks.

  47. Jason says:

    I figured it out, I added the following code after the script tag:

    $(document).ready(function(){
    $(‘#ajax’).load(‘/alpha’);

    And you’ll also need to add the following at the end:

    });

  48. Jason says:

    So is there a way to have it load the on.html at page load?

  49. Hey why dont you make it so you can drag the button lest anf right that way it will be easer then just clicking it because im used to seeing it on my iphone to drag it but here i have to click it.

  50. Ben says:

    Cool, lots of people are copying the iPhone GUI these days.

    On a side note, could you make your RSS feed display full posts so I don’t have to come out of Google Reader. It kind if makes the point of an RSS feed useless.

    • Ashley says:

      @ben thanks for the feedback, I’ve been having major problems with my feed and have had to hackit a bit but i’ll take a look at doing that.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.