Reputation: 579
I am trying to create a button in jquery mobile which toggles between a list and grid view. However I am stuck getting the button icon to change when I press/click it. This is my code:
HTML
<a href="javascript:changeLayout()" class="ui-btn-right" data-role="button" data-icon="bars" data-iconpos="notext" data-theme="b" data-inline="true"></a>
Javascript
function changeLayout() {
if ($('#changeLayout').data('icon') == 'grid'){
$('#changeLayout').data('icon', 'bars');
$('#changeLayout .ui-icon').addClass('ui-icon-bars').removeClass('ui-icon-grid');
}
else {
$('#changeLayout').data('icon', 'grid');
$('#changeLayout .ui-icon').addClass('ui-icon-grid').removeClass('ui-icon-bars');
}
However the button icon doesn't change. What am I doing wrong?
Thanks
Upvotes: 0
Views: 437
Reputation: 579
I'm really stupid. I forgot to assign the id of changelayout to my button in the HTML. My bad, thanks though!
Upvotes: 0
Reputation: 5236
In jQuery .data('x')
does not read/write to an element's data-x
attribute - it reads/writes to a background set of data handled solely by jQuery. You instead need to use the .attr()
method.
Try the following instead:
function changeLayout() {
if ($('#changeLayout').attr('data-icon') == 'grid'){
$('#changeLayout').attr('data-icon', 'bars');
$('#changeLayout .ui-icon').addClass('ui-icon-bars').removeClass('ui-icon-grid');
}
else {
$('#changeLayout').attr('data-icon', 'grid');
$('#changeLayout .ui-icon').addClass('ui-icon-grid').removeClass('ui-icon-bars');
}
Note that while the jQuery docs say you can use .data('x')
to access data-x
, I've never seen it actually work. Changing to .attr('x')
always fixes the issue as long as there are no other problems in the code.
Upvotes: 1