MattBianco
MattBianco

Reputation: 1531

How do I create a jQuery Mobile button from javascript?

Is there a way to make jQuery Mobile render a javascript-generated link as a button widget, like it does automatically when loading the page?

I have javascript like this to create the link dynamically:

var ws=document.getElementById('workspace'); // empty <div id="workspace"></div>
ws.innerHTML='<a id="myb" href="foo.php" data-role="button">baz</a>';

And of course it only generates a normal link instead of a button, so my question is how do I make jQueryMobile create the button dynamically, as it would have done if the same <a id="myb" href="foo.php" data-role="button">baz</a> had appeared in the page from the beginning?

EDIT :

A script like this:

$('#tagspace').html('<a id="myb" data-inline="true" data-ajax="false"
                    href="boo.php" data-role="button">baz</a>')
              .button()
              .click(function() { window.location.href=this.href;});

Is an improvement. It does result in a button (full page width), and that is sensitive to clicks outside of the text of the label. However, this doesn't seem to be mapped to the element containing the intended link "destination".

The DOM results of this:

<div aria-disabled="false" class="ui-btn ui-shadow ui-btn-corner-all ui-fullsize
                                      ui-btn-block ui-btn-up-c" data-mini="false" data-inline="false" data-theme="c" data-iconpos="" data-icon="" data-wrapperels="span" data-iconshadow="true" data-shadow="true" data-corners="true"> <span class="ui-btn-inner ui-btn-corner-all">
        <span class="ui-btn-text">baz</span>
</span>
    <div aria-disabled="false" class="ui-btn-hidden" id="tagspace"> <a id="myb" data-inline="true" data-ajax="false" href="boo.php" data-role="button">baz</a>

    </div>
</div>

So, it is still not the same kind of button.

Upvotes: 1

Views: 239

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

You can create a button widget by wrapping your element in a jQuery object and calling the button() method.

$("#workspace").html("<a id='myb' href='foo.php' data-role='button'>baz</a>")
               .button();

Update: The button widget prevents the default behavior of the link, so you will have to add a click handler if you want that behavior back:

$("#workspace").html("<a id='myb' href='foo.php' data-role='button'>baz</a>")
               .button()
               .click(function() {
                   window.location.href = this.href;
               });

Upvotes: 1

Related Questions