javascriptjquerylistviewjquery-mobile

jQuery Mobile Listview Swipe Menu


I have a standard JQM page with a ListView with auto generated dividers.

I'd like to be able to add some functionality that would allow the user to swipe left OR right on an item within the listview and it done either of the following;

  1. Reveal a star icon and create some info in localstorage. On swiping a second time change the icon to a 'hollow' star and remove the value in localstorage

  2. Reveal a 'hollow' star icon which when clicked on creates a value in locastorage and the icon is replaced with a 'filled' star. Likewise, if the star is pressed a second time, the localstorage value is removed and the icon reverts to a 'hollow' star

I'm sure I've seen info on a similar topic elsewhere but can't seem to find it today. Where can I start?


Solution

  • Create span element which will contain star. Add spans before each li element.

    <ul data-role="listview" id="list">
      <span class="yellowStar"></span>
      <li>Item 1</li>
      <span class="hollowStar"></span>
      <li>Item 2</li>
      <span class="hollowStar"></span>
      <li>Item 3</li>
      <span class="hollowStar"></span>
      <li>Item 4</li>
      <span class="hollowStar"></span>
      <li>Item 5</li>
    </ul>
    

    Apply the following CSS for both filled and hollow stars.

    .ui-listview>.ui-li-static {
      overflow: initial; /* to hide spans underneath */
      -webkit-transition: -webkit-transform 300ms ease; /* transition effect */
         -moz-transition: -moz-transform 300ms ease;
           -o-transition: -o-transform 300ms ease;
              transition: transform 300ms ease;
    }
    
    ul span {
      float: right;
      padding: 1.3em 20px;
      z-index: -1;
    }
    
    ul .yellowStar {
      background-image: url(filled.png);
      background-repeat: no-repeat;
      background-position: center;
    }
    
    ul .hollowStar {
      background-image: url(hollow.jpg);
      background-repeat: no-repeat;
      background-position: center;
    }
    

    And then attach swipeleft to reveal star.

    $(document).on("click", "ul span", function () {
        $(this).toggleClass("yellowStar hollowStar");
    }).on("swipeleft", "ul li", function (e) {
        $(this).off("click");
        $(this).css({
            transform: "translateX(-40px)"
        }).one("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", function () {
            $(this).one("click swiperight", function () {
                $(this).css({
                    transform: "translateX(0)"
                });
            });
        });
    });
    

    Whenever swipe is fired, it also fires click, hence, .off("click") is essential when swipe triggers. However, once the transition ends, click and swiperight listeners are attached to close/hide star.

    Demo