Using scroll events

When you scroll, the jQuery Mobile framework fires the scrollstart event. When you stop scrolling the scrollstop event is triggered. This recipe shows you how to use these two events.

Getting ready

Copy the full code of this recipe from the code/08/scroll sources folder. You can launch this code by using the URL http://localhost:8080/08/scroll/main.html

How to do it...

Carry out the following steps:

  1. Create main.html with the page content div styled with a large value for its height, so that the scroll bars appear:
    <div id="main" data-role="page" data-theme="e">
      <div data-role="header" data-theme="a" data-
      position="fixed">
        <h1>Scroll Events</h1>
      </div>    
      <div data-role="content">
        <div style="height: 1000px">Scroll now</div>
      </div>
    </div>
  2. Add the following script to the <head> section to handle the scroll events:
    $(window).bind("scrollstart", function(event) {
      $("h1").html("Scrolling now...");
    });
    $(window).bind("scrollstop", function(event) {
      $("h1").html("Scrolling done!");
    });

How it works...

Create main.html as shown in the preceding code. Add a div container with a height of 1000px to the page content. This will make the vertical scroll bars appear. Now, add the given script to the <head> section of the page. Bind the scrollstart event to a callback function that updates the page header text. Similarly bind the scrollstop event to a callback function that updates the header text. Now, scroll the page holding the vertical scroll bar handle. You can see the page header text showing "Scrolling now...", and when you stop or pause scrolling, the text is updated to "Scrolling done!".

There's more...

There is an issue as to how the scrollstart event works on iOS devices. DOM manipulation is not allowed during scroll, and the event gets queued and triggered as soon as the scrolling stops. So keep this in mind when you work with scroll events on iOS devices. You will have to have to make your changes before scrolling starts and not as soon as it starts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.17.40