Changing the color of the selected item in a Jquery Mobile ListView

I have a dynamic list that triggers a JavaScript function using the onclick event. However, I am struggling to change the color of the selected item in the list.

Here is an example of the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>`enter code here`
    <script src="scripts/jquery.js" type="text/javascript"></script>
    <link href="stylesheets/jquery.mobile.css" rel="stylesheet" type="text/css" />
    <script src="scripts/jquery.mobile.js" type="text/javascript"></script>
    <script>

        $(document).ready(function () {
            var $al = $("#mylist");
            $al.append("<li ><a id='a1' href=\"#\" rel=\"external\" onclick=\"test('selected test 1'); return false\">TEST 1</a></li>");
            $al.append("<li ><a id='a2' href=\"#\" rel=\"external\" onclick=\"test('seleced test 2'); return false\">TEST 2</a></li>");
        });

        function test(text) {
            $("#divtest").html(text);
        } 

        $("#myList li a").click(function () {
                $('#myList li > div').each(function (index) {
                    $(this).removeClass("ui-btn-active");
                });
                var p = $(this).parent();
                $(p).addClass('ui-btn-active');
            });

    </script>
</he`ad>
<body>
    <div data-role="page" id="profile">
        <div data-role="header" data-position="fixed">
        </div>
        <!-- /header -->
        <div data-role="content">
            <ul id="mylist" data-role="listview" data-inset="true">
            </ul>
        </div>
        <div id='divtest'>

        </div>
        <!--/content-->
        <div data-role="footer" data-position="fixed">
        </div>
        <!--/footer-->
    </div>
</body>
</html>

Answer №1

In order to achieve this, you must utilize the .addClass and .removeClass functions within your list item. The specific classes that need to be added or removed will depend on the desired color scheme. To begin, consider adding the ui-btn-active class to the items.

Answer №2

To customize the appearance of your list, simply add the data-theme='a' attribute to the li element and select the desired template.

For more information on this attribute, visit: http://jquerymobile.com/demos/1.2.0/docs/content/content-themes.html

Don't forget to run .listview('refresh'); to update the style of the listview.

Here's a functional example using your code: http://jsfiddle.net/Gajotres/z5Vhm/

Below is the code snippet:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>`enter code here`
    <link href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
    <script>

        $(document).ready(function () {
            var $al = $("#mylist");
            $al.append("<li data-theme='a'><a id='a1' href=\"#\" rel=\"external\" onclick=\"test('selected test 1'); return false\">TEST 1</a></li>");
            $al.append("<li data-theme='b'><a id='a2' href=\"#\" rel=\"external\" onclick=\"test('seleced test 2'); return false\" >TEST 2</a></li>");
            $al.listview('refresh');
        });

        function test(text) {
            $("#divtest").html(text);
        } 

    </script>
</head>
<body>
    <div data-role="page" id="profile">
        <div data-role="header" data-position="fixed">
        </div>
        <!-- /header -->
        <div data-role="content">
            <ul id="mylist" data-role="listview" data-inset="true">
            </ul>
        </div>
        <div id='divtest'>

        </div>
        <!--/content-->
        <div data-role="footer" data-position="fixed">
        </div>
        <!--/footer-->
    </div>
</body>
</html>

Answer №3

To change the background color of the parent Li element when clicking on a hyperlink, use the following jQuery code:

$('a').click( function() {
  $(this).parent().css({'background-color' : 'blue' });
});

For a demo, you can visit this CodePen link: http://codepen.io/example/123/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The width of the Div is set to 100%, yet there is still some empty space visible on

I am having trouble setting the background of my code to display a picture that is 300px in height and 100% in width. However, when I set the width to 100%, there are about 15px gaps on each side. I could adjust the width to 1000px, but that presents issue ...

What is the most efficient way to calculate the total sum of all product amounts without using Jquery?

I am working with a dynamic table where data is inserted and the total of each product is calculated by multiplying the price by the quantity. What I need now is to get the sum of all the totals for each product. You can see how the table looks here: htt ...

Is there a way to horizontally center a content container in Flutter similar to a "max-width" container in CSS?

How can I create a centered content box like this in Flutter?: .content-box { margin-left: auto; margin-right: auto; width: 100%; max-width: 600px; background-color: blue; height: 100vh; } <div class="content-box"> Cont ...

Prevent the float:left property from causing my div to overlap with another div

Is there a way to style "a" so that it can take up space and float to the left simultaneously? <div style="background:#111"> <div id="a" style="float:left; height:30px"></div> </div> ...

What steps should I take to get my fixed position to function properly in Internet Explorer 6?

I've attempted the following to solve my issue: body {height: 100%;overflow: auto; body #cornerImage {position: absolute;bottom: 0;} I also tried this solution: { margin:0; padding:0; } html, body { height: 100%; overflow:auto; } body #fixe ...

Switch classes while navigating within a div

My website has a sticky sidebar with a list of cars and their corresponding categories in a table: <ul class = "cars"> <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li> ...... ...

The complete height of the website is concealed by the mobile toolbar/menu

I encountered a perplexing issue regarding the responsive resizing of a website on mobile devices. The problem arises when the full height extends over the toolbar/menu, unless the user manually hides the toolbar. Is there a way to dynamically resize the ...

The Bootstrap navbar stubbornly refuses to hide after being clicked on

Is there a way to adjust the data-offset-top for mobile view? Additionally, I am having trouble hiding the menu when clicking on a link. I have tried some code from stackoverflow without success. Can someone please assist with this issue: <nav class= ...

javascript - Retrieving a JSON string

I am currently working on a stock website where I need to retrieve JSON information from either Google's API or Yahoo's API. To test this functionality, I have used a replacement function to log the data onto a text box for testing purposes. Howe ...

Obtaining the innerHTML value using JavaScript in an Asp.net Core 5 View

Apologies for any inaccuracies in my English writing. In the Asp.Net Core project view, I am trying to use JavaScript to capture multiple Span tags within innerHTML represented by a loop and display their sum in another tag. However, I am only able to ret ...

Calculating the computed width based on flex-basis at 0% and the flex-grow factor: what's the deal

Below is an example of HTML with default flex properties being used: <div class="container"> <div class="box"> BOX 1</div> <div class="box"> BOX 2</div> <div class="box box2"> BOX 3 .</div> </div> The ...

Guide to implementing a universal animated background with Angular components

I'm having trouble figuring out why, but every time I attempt to use a specific code (for example: https://codepen.io/plavookac/pen/QMwObb), when applying it to my index.html file (the main one), it ends up displaying on top of my content and makes ev ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

Prevent jQuery from overriding CSS styling

Having an issue with adding a <p> tag before each jQuery accordion on my MVC page. No matter what I try, the jQuery styling keeps interfering with the classes and styles of my <p> tag. Is there a way to make it look like the other non-jQuery & ...

My goal is to extract the usernames of all sellers from the Poshmark webpage using a combination of JavaScript, Cheerio, and Axios

After experimenting with various methods, I've come close to the solution, but it only retrieves one of the div elements I'm looking for... Although I managed to retrieve multiple divs at one point, when I attempted to extract text using the .te ...

Animation of underline on hover for NavLink

As a newcomer to React, I am currently exploring how to create an animated underline effect when hovering over a NavLink from reactstrap. I have managed to get the underline working on hover thanks to the solution provided at , but I am struggling with imp ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Is SimpleHTTPServer included in the package?

Lately, I've been experimenting with the Python SimpleHTTPServer in Mac OS X Bash instead of MAMP to assist with front-end templating. I appreciate its user-friendly nature, but I'm curious if there is a method to incorporate includes for repeate ...

Success/Fail Page for Form Redirect

I've been struggling to figure out how to redirect my form to a success or fail page. I've scoured the internet for solutions, looking into traditional form redirects and even JavaScript onClick redirects. Can someone guide me on adding a redirec ...

When adjusting the top margin of the main content in CSS, the fixed top navigation section's margin also decreases simultaneously with the main content

I am in the process of creating a basic static blog page using HTML5, SASS, and CSS. While working on the design, I utilized the 'nav' semantic element for a fixed top bar on the page that remains visible even when scrolling down. Additionally, ...