Over a million developers have joined DZone.

Dynamically Changing jQuery Mobile Buttons

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Filed in the "In case you need to know" department, jQuery Mobile provides a basic API that allows you to modify buttons. This is more useful for creating new buttons, but also has uses for existing buttons. Specifically, I was looking for a way to swap out the theme of a button in a form based on what had been entered. Here is a simple example of this API in action:

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Single page template</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>


<div data-role="page">

<div data-role="header">
<h1>Single page</h1>

<div data-role="content">
<a href="" data-role="button" id="testButton">Button Me</a>	
<button id="realButton">Real Button</button>	

<div data-role="footer">
<h4>Footer content</h4>


var themes = ["","a","b","c","d","e"];
var currTheme = 0;

$("#testButton,#realButton").on("click", function() {
var tb = $("#testButton");
var rb = $("#realButton");

if(currTheme == themes.length) currTheme=0;
newTheme = themes[currTheme];

console.log("Setting theme to "+newTheme);

//Do the test button

//Do the real button



Most of the template is boilerplate jQuery Mobile code. Note though the two buttons in the content section. Both are set to have no theme. Now - look at the JavaScript code at the bottom. I've got a basic click handler (should be touch I suppose) that will iterate over all possible theme values, including no theme specified. The API allows you to tweak pretty much everything, but I'm not sure what else you would change on the fly. Icon perhaps. Anyway, on the off chance someone needs this, here is a demo of the code above.


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}