Dynamically change icon in jQuery Mobile listview
Asked Answered
T

2

5

When I dynamically change the icon, it does not reflect the change on the page, even though in the markup it was changed.

Example:

      <ul data-role="listview" data-autodividers="true" data-filter="true" data-inset="true">
        <li data-icon="check"><a href="#">Adam Kinkaid</a></li>
        <li data-icon="check"><a href="#">Alex Wickerham</a></li>
        <li data-icon="check"><a href="#">Avery Johnson</a></li>
        <li data-icon="check"><a href="#">Bob Cabot</a></li>
        <li data-icon="check"><a href="#">Caleb Booth</a></li>
        <li data-icon="check"><a href="#">Christopher Adams</a></li>
        <li data-icon="check"><a href="#">Culver James</a></li>
    </ul>

$("li").tap(function() {
    //Alert the old icon
    alert($(this).jqmData("icon"));

    //Toggle
    $(this).jqmData("icon") == "false" ? $(this).jqmData("icon", "check") :             $(this).jqmData("icon", "false");

    //Alert the new icon
    alert($(this).jqmData("icon"));
});

http://jsfiddle.net/Mc97V/

Tamworth answered 27/2, 2013 at 14:56 Comment(0)
S
10

I made you a working example: http://jsfiddle.net/Gajotres/qgE6L/

$('#index').live('pagebeforeshow',function(e,data){    
    $("li").tap(function() {
        $(this).buttonMarkup({ icon: "edit" });
    });  
});
Sacrarium answered 27/2, 2013 at 15:3 Comment(4)
Thanks, this mostly works. However, toggling between check/false, instead of false, it shows a blurry +. Toggling between any two others shows the icons correctlyTamworth
That's because icon "false" don't exist. Take a look at this icon list: jquerymobile.com/demos/1.2.0-alpha.1/docs/buttons/…. You can add your own custom icons, but that is another question. Or do you want to remove icon with false?Sacrarium
I want to remove the icon with false, yeahTamworth
NVM, got it. I used .buttonMarkup({ icon: "" }). Thanks for your helpTamworth
H
0

My solution is to first remove the ui-icon... class from the anchor child element and then set it to another one.

For example, for a list line with id "ElementId1" with an icon of type "check", to change the icon to "delete":

        $("#ElementId1").children('a').first().removeClass('ui-icon-check');
        $("#ElementId1" ).children('a').first().addClass('ui-icon-delete');
Hexagonal answered 4/11 at 20:1 Comment(3)
Dear lord why are you using jQuery Mobile in 2024Tamworth
Because the question is "Dynamically change icon in jQuery Mobile listview" AND it works very well and does not force my customers to update spasmodically their devices :)Hexagonal
Yes I am the author of the question and I feel sorry for you, but glad that it works for your business!Tamworth

© 2022 - 2024 — McMap. All rights reserved.