Using silent scrolling

You can use the $.mobile.silentScroll method to scroll to any vertical position on your page, without triggering the scroll event listeners. This recipe shows you how to use silent scrolling.

Getting ready

Copy the full code of this recipe from the code/09/silentscroll source folder. You can launch this code by using the URL: http://localhost:8080/09/silentscroll/main.html.

How to do it...

  1. Create main.html with an empty div tag and two buttons that will be used to scroll to the top and bottom of the page:
    <div data-role="content">
      <button id="bottombtn">Page Bottom</button>
      <div id="dispdiv"></div>
      <button id="topbtn">Page Top</button>
    </div>
  2. Add the following script to the <head> section to create a lengthy page:
    $("#main").live("pageinit", function(event) {
      var str="";
      for (var i=0; i<100; i++) {
        str += i + "<br/>";
      }
      $("#dispdiv").html(str);
  3. Now, based on the button clicked, scroll to the top or bottom of the page:
      $("#topbtn").bind("click", function(event, ui) {
        $.mobile.silentScroll($.mobile.defaultHomeScroll); 
      });
      $("#bottombtn").bind("click", function(event, ui) {
        $.mobile.silentScroll(2000);
      });
    });

How it works...

Add two buttons with IDs bottombtn and topbtn to main.html. Create an empty div tag with id="dispdiv", and populate it with some lengthy content. Here, a script is used on the pageinit event to add 100 lines of text in a loop to #dispdiv. The page is initially displayed as follows:

How it works...

Bind the click event of the #bottombtn button to call $.mobile.silentScroll with a large value (2000px here) as the Y parameter. Now, when you click on the Page Bottom button, the page scrolls to the Y position (2000px) which is at the bottom of the document, as shown in the following screenshot:

How it works...

Next, bind the click event of the #topbtn button, and pass the $.mobile.defaultHomeScroll property as a parameter to $.mobile.silentScroll. Now, click on the Page Top button, and the page scrolls back to the top.

There's more...

The silentScroll method does not invoke the scroll event listeners. Add the following code to verify that the alert is not shown when you click on any of the buttons. But the alert is shown when you use the scrollbar.

$(window).bind("scrollstop", function(event) {
  alert("Scroll event was fired");
});

The $.mobile.defaultHomeScroll Property

The $.mobile.defaultHomeScroll property used in this recipe is internally used by the jQuery Mobile framework to scroll to the top of the page. This value is obtained from the browser using the $.support.scrollTop property. If this value is not 0, the framework sets it to 0.

See also

  • The Using Scroll Events recipe in Chapter 8, Events
..................Content has been hidden....................

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