Question

I'm very new to Jquery & jquery mobile. I'm resizing a button so it's responsive to window size. To be more specific, i'm changing it from iconpos="left" to iconpos="notext" to remove the text on small windows. I found the following function, which works for me.

$(window).on("throttledresize", function() {
  var smallButtons = $(window).width() <= 480;
  $('#menu_toggle').toggleClass('ui-btn-icon-notext', smallButtons);
  $('#menu_toggle').toggleClass('ui-btn-icon-left', !smallButtons);
});

But it only works on the window resizing. Obviously, I'd also like it showing the correct size on pageload, not just resizing. I found the code below, but I don't know how put them both into 1, more succinct bit of code.

$("#page_id").on("pageshow" , function() {
 The Function
});
Was it helpful?

Solution

jQuery Mobile >= 1.4

.buttonMarkup() as well as data-role="button" are deprecated and will be removed in 1.5. Instead, classes should be added manually to Anchor tag.

  • Create a function to manipulate classes of Anchor. As of jQM page events are now replaced with pageContainer events. The new events can't be bound to a specific page, therefore, you need to look for the Anchor inside active page.

    Note that $.mobile.activePage is also deprecated and replaced with $.mobile.pageContainer.pagecontainer("getActivePage").

    function resizeBtn() {
        var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
        if ($(window).width() <= 480) {
            $("#notext.ui-btn-icon-left", activePage)
                .toggleClass("ui-btn-icon-notext ui-btn-icon-left");
        } else {
            $("#notext.ui-btn-icon-notext", activePage)
                .toggleClass("ui-btn-icon-left ui-btn-icon-notext");
        }
    }
    
  • Call function on pagecontainerbeforeshow event:

    $(document).on("pagecontainerbeforeshow", resizeBtn);
    
  • Call function on throttledresize event:

    $(window).on("throttledresize", resizeBtn);
    

Note: throttledresize is better than resize as it delays firing resize event coming from the browser.

Demo


jQuery Mobile <= 1.3

You need to use .buttonMarkup() if you're using jQuery Mobile 1.3 or lower.

$(".selector").buttonMarkup({
  iconpos: "notext"
});
  • Resize function:

    function resizeBtn() {
        if ($(window).width() <= 480) {
            $(".selector").buttonMarkup({
                iconpos: "notext"
            });
        } else {
            $(".selector").buttonMarkup({
                iconpos: "right"
            });
        }
    }
    
  • Call function on pagebeforeshow:

    $(document).on("pagebeforeshow", resizeBtn);
    
  • Call function on resize:

    $(window).on("resize", resizeBtn);
    

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top