Tips for updating the background hue of a StackLayout box in a NativeScript app

Reviewing the following XML:

<ListView items="{{ lists }}" itemTap="itemTapped">
    <ListView.itemTemplate>
         <StackLayout class="list-group-item" orientation="horizontal">
            <Label text="{{ name }}" class="item-name" horizontalAlignment="center" />
         </StackLayout>
    </ListView.itemTemplate>
</ListView>

In the itemTapped function, the goal is to modify the StackLayout container's background color.

exports.itemTapped = function (args) {
    console.log(args.object.backgroundColor)
    args.object.backgroundColor = 'red'
    console.log(args.object.backgroundColor) 
}

Upon clicking a list item in the app, the console logs reveal:

CONSOLE LOG file:///app/pick/pick-page.js:111:14: undefined
CONSOLE LOG file:///app/pick/pick-page.js:113:14: #FF0000
CONSOLE LOG file:///app/pick/pick-page.js:111:14: undefined
CONSOLE LOG file:///app/pick/pick-page.js:113:14: #FF0000

An attempt was made using

args.object.className = 'selected-item'
to set the CSS property background-color: red;, but it did not yield the desired result.

What is the best approach for dynamically changing the color or providing visual feedback that a ListView item has been tapped?

Answer №1

It is not recommended to directly modify a ListItem within a ListView because the elements may be reused as you scroll up and down. Instead, you should have an attribute on your data item and toggle that attribute. Based on the attribute, you can bind the background color on the ListItem.

 <ListView items="{{ countries }}" itemTap="{{ onItemTap }}">
    <ListView.itemTemplate>
        <FlexboxLayout flexDirection="row"
            backgroundColor="{{ selected, selected ? 'red' : 'white' }}">
            <Image src="{{ imageSrc }}" class="thumb img-circle" />
            <Label text="{{ name }}" class="t-12"
                verticalAlignment="center" style="width: 60%" />
        </FlexboxLayout>
    </ListView.itemTemplate>
</ListView>

Playground Sample

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

Utilizing Knockout to Load JSON Data in DevExtreme

As a newcomer to both javascript and devextreme, I am currently navigating my way through. I successfully created a webpage that loads a json file, but I'm facing challenges implementing it using devextreme. I have a dxDataGrid where I intend to disp ...

What is the procedure for matching paths containing /lang using the express middleware?

I need to target paths that contain /lang? in the URL, but I am unsure how to specifically target paths that begin with /lang? I have two routes: app.get('/lang?..... app.get('/bottle/lang?....... I want to target these routes using app.use(&a ...

What sets apart the browser/tab close event from the refresh event?

Can you help me understand the difference between a browser/tab close event and a refresh event? I've been researching this on Stack Overflow, but I'm still having trouble with it. My goal is to be able to log out a user through a server call whe ...

Is there a way to verify the presence of an email, mobile number, and Aadhar number in my MongoDB database?

const express = require('express'); const router = express.Router(); require('../db/conn'); const User = require('../model/userSchema'); router.get('/', (req, res) => { res.send(`Greetings from the server vi ...

Multiple instances of Ajax drop-down effects are now available

On my website's staff page, I have implemented a dropdown menu using AJAX to display information about each member of the staff. The issue arises when attempting to open multiple dropdown menus on the same page - the second dropdown that is opened ten ...

AngularJS encountered an error following a successful GET request

I'm attempting to retrieve data from the server using this code snippet. $scope.get_file_list = function() { delete $http.defaults.headers.common['X-Requested-With']; //We don't want OPTIONS but GET request $htt ...

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

Converting axios response containing an array of arrays into a TypeScript interface

When working with an API, I encountered a response in the following format: [ [ 1636765200000, 254.46, 248.07, 254.78, 248.05, 2074.9316693 ], [ 1636761600000, 251.14, 254.29, 255.73, 251.14, 5965.53873045 ], [ 1636758000000, 251.25, 251.15, 252.97, ...

React Intersection Observer not functioning properly

Hey there! I'm trying to create an animation where the title slides down and the left element slides to the right when scrolling, using the intersection observer. Everything seems to be fine in my code, but for some reason it's not working. Any t ...

Efficiently loading an image in one go

Rendering approximately 3000 records, each row displays: Customer Profile Edit Customer Name, Action 1 John Edit image | Delete image 2 John Edit image | Delete image 3 John Edit image | Delete image 4 John ...

The animation feature on the slideshow is dysfunctional

For this Vue component, I attempted to create a slideshow. The process is as follows: 1) Creating an array of all image sources to be included (array: pictures) 2) Initializing a variable(Count) to 0, starting from the beginning. 3) Adding v-bind:src=" ...

Error message: "PHP encounters an issue with jQuery due to absence of 'Access-Control-Allow-Origin' header"

I am currently attempting to make an external API call in PHP using AJAX and jQuery, but I keep encountering the error message saying "No 'Access-Control-Allow-Origin' header is present". The API does not support JSONP. Is there any workaround t ...

How can one continue repeating a series in async.js until an unforeseen error arises?

Is it possible to continuously execute a series of tasks in async.js until an unexpected error occurs? For example: async.series([ function(callback) { // perform task }, function(callback) { // perform another task }, ...

Troubleshooting issues with transferring Coldfusion form data to Javascript and CFC, facing challenges with code execution

I am attempting to transfer my form data into a JavaScript function, which will then pass it into my CFC function for database insertion. Unfortunately, it is not functioning correctly. Below is the JS code: Updated: removed "." in front of alert() and ur ...

After successfully navigating past the login page on my website using JavaScript, my Selenium driver suddenly ceases to function

My current automation test involves logging into a hotel booking website using Selenium and Cucumber. After successfully logging in, I attempt to click on a checkbox labeled "wifi", but encounter issues with Selenium not functioning properly once logged in ...

Guide on how to import image data instead of an image using THREE.js in javascript

I wrote a JavaScript function that loads an image as a texture: var loader = new THREE.TextureLoader(); loader.load( 'textures/canvas1.png', function ( texture ) { var geometry = new THREE.SphereGeometry( 200, 20, 20 ); var material = n ...

Adjust the placement of the div dynamically in response to the positioning of another div tag

I have an icon that resembles a chat bubble. If the position of the icon is not fixed, how can I display the chat bubble relative to the icon and adjust its position dynamically based on the icon's location? See image here #logowrap{ padding: 8px ...

Real-Time Updating of Countdown Timer using JavaScript every passing second

I am currently working on a PHP script that displays the countdown until an event. The time remaining is shown in a format like this: 23h 15m 4s Below is the PHP code I am using: $now = new DateTime(); $future_date = new DateTime($res['post_ ...

"Ensuring Contact Information is Unique: A Guide to Checking for Existing Email or Phone Numbers in

I'm encountering an issue with validating email and phone numbers in my MongoDB database. Currently, my code only checks for the presence of the email but does not respond to the phone number. const express = require("express"); const router ...

What is the best way to retrieve a specific key from a JavaScript Map containing an array?

I am currently iterating through a two-dimensional array to populate a map. The map is using the [i,j] indices as keys and the corresponding arr[i][j] values as values: const arrMap = new Map() for(let i = 0; i < arr.length; i++){ for(let j = 0 ...