I have several views that are added to a ScrollView dynamically with a for, but when the user clicks on one of the views, I want to change the Background color of the view. I have the following code for the click event:
(function() {
var id = i;
viewQuantity.addEventListener('click', function(e) {
viewQuantity.backgroundColor = '#FFFFFF';
});
})();
but with this code the view that changes the color is always the last added view. How can I use the id to change the view that was clicked by the user?
Within a click event you get an event property in the function as first parameter. This has source
object which is the element the user has clicked.
var clickedView;
(function() {
var id = i;
viewQuantity.addEventListener('click', function(e) {
if (clickedView){
clickedView.backgroundColor= '#000000'; // put your own color here to restore original
}
e.source.backgroundColor = '#FFFFFF';
clickedView = e.source;
});
})();
To change the color later, you can store a reference to the object, and change the color later
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments