Home > dev, Javascript, jQuery, jQuery Mobile, Mobile, open source > jQuery Mobile Slider Events

jQuery Mobile Slider Events

Out of the box there is no way to ask a jQuery slider to notify you when the value changes. This was problematic for me on a mobile app as I needed to know as soon as the user toggled the component. Some googling didn’t turn up anything helpful and I was hesitant to add a custom trigger. Now don’t get me wrong, there were lots of examples dealing with the programatic interaction with sliders, but none where you weren’t the creator of the slider (in this case jQuery Mobile automagically does it).

After a little head scratching I realized that I could monitor the change event on the underlying select element that the slider was bound to. The only catch was to filter out change events that weren’t really changing the value.. The reason for this was because if you held your finder on the slider and drug it around the on state (example: half drag through the off side) the change event on the select element is continuously fired. Simply storing the previous state of the button did the trick.

Sample button HTML:

<div data-role="page" id="sample">
    <div data-role="header">
        <h1>Sample Page</h1>
    </div>
    <div data-role="content">    
        <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
            <li>Toggle Me <select name="slider" id="toggle-me" data-role="slider">
                <option value="off">Off</option>
                <option value="on">On</option>
            </select> 
            </li>
        </ul>
    </div>
</div>

JavaScript

var oldVal = $("#toggle-me").bind("change", function(){ 
    if(oldVal != $(this).val()){
        oldVal = $(this).val();
        console.log("val change to " + oldVal);
    }
 }).val()

About these ads
  1. Xavier
    July 4, 2011 at 9:53 am

    Hello,
    Im a noob in JQuery and I was looking for a solution to a similar problem:
    each time I was using silders or range inputs in a page, the change event was triggerd when the page was loaded.
    With your solution, I could fix it!

    Thanks a lot, you don’t imagine how long I’ve been looking for the fix…

  2. Alan
    September 22, 2011 at 4:35 am

    Xavier, I have the same problem but somehow this did not worked for me.. Did you add up anything with this?

    Alan

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: