Papermashup

Subscribe


Tweets


"RT @Eva_Shaughnessy: #finedining @romomobilecafes restaurant this evening with #NewHair #winning #SaturdayNight #GirlsNightOut http://t.co/…"

@ashleyford 3 weeks ago

"RT @kycutwilson: @ashleyford @burgerbeartom incredible. There's 5 more left! Shout about it!!"

@ashleyford 1 month ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

jQuery Iphone Style Ajax Switch

AshleyAshley

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

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 61
  • Regis Grison
    Posted on

    Regis Grison Regis Grison

    Reply Author

    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
      Posted on

      Marcio Marcio

      Reply Author

      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.


  • Robin
    Posted on

    Robin Robin

    Reply Author

    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.


  • Joe
    Posted on

    Joe Joe

    Reply Author

    Wish there was an updated image for this tutorial :)


  • Matt
    Posted on

    Matt Matt

    Reply Author

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


  • pitchalite
    Posted on

    pitchalite pitchalite

    Reply Author

    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


    • pitchalite
      Posted on

      pitchalite pitchalite

      Reply Author

      Instead of a closing tag tag is used.


    • pitchalite
      Posted on

      pitchalite pitchalite

      Reply Author

      correction
      “instead of a closing image tag div tag is used,”


    • Madhuri
      Posted on

      Madhuri Madhuri

      Reply Author

      Thanks, this helped..


  • Buy Things
    Posted on

    Buy Things Buy Things

    Reply Author

    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.


  • Meee
    Posted on

    Meee Meee

    Reply Author

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


  • Thibaut
    Posted on

    Thibaut Thibaut

    Reply Author

    Hi,

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

    Thanks


  • Shorten urls service make money
    Posted on

    Shorten urls service make money Shorten urls service make money

    Reply Author

    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.


  • persa
    Posted on

    persa persa

    Reply Author

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

    Thanks
    Best Regards


  • Andrew Swihart
    Posted on

    Andrew Swihart Andrew Swihart

    Reply Author

    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.


  • Andy
    Posted on

    Andy Andy

    Reply Author

    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.


  • Andy
    Posted on

    Andy Andy

    Reply Author

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


  • Andy
    Posted on

    Andy Andy

    Reply Author

    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??


  • Andy
    Posted on

    Andy Andy

    Reply Author

    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


  • Reedyseth
    Posted on

    Reedyseth Reedyseth

    Reply Author

    @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'
    });


  • Raf
    Posted on

    Raf Raf

    Reply Author

    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


  • jerry5
    Posted on

    jerry5 jerry5

    Reply Author

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


  • jerry5
    Posted on

    jerry5 jerry5

    Reply Author

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


  • Austin
    Posted on

    Austin Austin

    Reply Author

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


  • Reedyseth
    Posted on

    Reedyseth Reedyseth

    Reply Author

    @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.


  • Austin
    Posted on

    Austin Austin

    Reply Author

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

    Austin


  • Andy
    Posted on

    Andy Andy

    Reply Author

    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


  • Varun DHawan
    Posted on

    Varun DHawan Varun DHawan

    Reply Author

    Hi,

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


  • jerry5
    Posted on

    jerry5 jerry5

    Reply Author

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


  • Andrew Solomon
    Posted on

    Andrew Solomon Andrew Solomon

    Reply Author

    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?


  • Reedyseth
    Posted on

    Reedyseth Reedyseth

    Reply Author

    @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.


  • todd
    Posted on

    todd todd

    Reply Author

    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


  • Igor G.
    Posted on

    Igor G. Igor G.

    Reply Author

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

    Igor


  • Sam Woodard
    Posted on

    Sam Woodard Sam Woodard

    Reply Author

    Have you considered putting the src on github?


  • Maurizio
    Posted on

    Maurizio Maurizio

    Reply Author

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

    made the trick!


  • oraculum
    Posted on

    oraculum oraculum

    Reply Author

    nice man

    thanks


  • dirkuijt
    Posted on

    dirkuijt dirkuijt

    Reply Author

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


  • BigDirty
    Posted on

    BigDirty BigDirty

    Reply Author

    Not working with jquery 1.4.4 or 1.4.2 in IE8


  • BigDirty
    Posted on

    BigDirty BigDirty

    Reply Author

    Doesn’t work with jquery 1.4.4 or 1.4.2 in IE8


  • lucky
    Posted on

    lucky lucky

    Reply Author

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


  • Acher
    Posted on

    Acher Acher

    Reply Author

    Tnx 😉


  • Aman
    Posted on

    Aman Aman

    Reply Author

    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


  • MariusV5
    Posted on

    MariusV5 MariusV5

    Reply Author

    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


  • doc
    Posted on

    doc doc

    Reply Author

    Hi,

    great work.

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


  • Hunter
    Posted on

    Hunter Hunter

    Reply Author

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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Hunter looks great, thanks for the link!


  • Stephen
    Posted on

    Stephen Stephen

    Reply Author

    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


  • Leny
    Posted on

    Leny Leny

    Reply Author

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


  • Igor
    Posted on

    Igor Igor

    Reply Author

    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.


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @igor thanks for pointing that out, i’ve updated the code 😉


  • Jason
    Posted on

    Jason Jason

    Reply Author

    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:

    });


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Jason good to see you found a solution :)


  • Jason
    Posted on

    Jason Jason

    Reply Author

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


  • Sufian Hassan
    Posted on

    Sufian Hassan Sufian Hassan

    Reply Author

    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.


  • Ben
    Posted on

    Ben Ben

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      @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.