JavaScript onClick event not functioning properly on iOS devices

I have created a code that can detect when a user clicks on a cell in a table and retrieves the background color set for that cell.

Everything works perfectly on my desktop computer, but when I attempt to use my iPad, it does not respond. I attempted to use touchstart instead, but it did not solve the issue.

I made a change from:

 t[i].onclick = getVal;  

to:

t[i].addEventListener('touchstart', function(){getVal});

However, this alteration did not resolve the problem. I also need to ensure that my code is compatible with both desktop and touch devices. I am unsure how to achieve this in this situation.

Below is my current code:

<script type="text/javascript">

function getVal(e) {
    var target;
    if (!e) var e = window.event;
    if (e.target) target = e.target;
    else if (e.srcElement) target = e.srcElement;
    if (target.nodeType == 3) // workaround for Safari bug
        target = target.parentNode;

    var colorSelected = target.attributes.bgcolor.value;
    alert(colorSelected);
}
onload = function() 
{
    var ids = ['colorchart1', 'colorchart2', 'colorchart3', 'colorchart4', 'colorchart5'];
    for(var j = 0; j < ids.length; j++) 
    {
        var t = document.getElementById(ids[j]).getElementsByTagName("td");
        for ( var i = 0; i < t.length; i++ )
            t[i].onclick = getVal; 
    }
}

</script>



<table id="colorchart1">
<tr>
<td bgColor="#F8E0E0"></td><td bgColor="#F8ECE0"></td><td bgColor="#F7F8E0"></td><td   bgColor="#ECF8E0"></td>
<td bgColor="#E0F8E0"></td><td bgColor="#E0F8EC"></td><td bgColor="#E0F8F7"></td><td bgColor="#E0ECF8"></td><td bgColor="#E0E0F8"></td>
</tr><tr>
<td bgColor="#F5A9A9"></td><td bgColor="#F5D0A9"></td><td bgColor="#F2F5A9"></td><td bgColor="#D0F5A9"></td>
<td bgColor="#A9F5A9"></td><td bgColor="#A9F5D0"></td><td bgColor="#A9F5F2"></td><td bgColor="#A9D0F5"></td><td bgColor="#A9A9F5"></td>
</tr>
<table>

Answer №1

What do you think of this handle function?

function handleEvent(evt){
 evt.target.nodeName!='TD'||alert(evt.target.bgColor+' on '+
 evt.target.parentNode.parentNode.parentNode.id);
}
window.addEventListener('click',handleEvent,false);

or 

window.addEventListener('touchstart',handleEvent,false);

Check out the demo

http://jsfiddle.net/gfmbkmmn/

View multiple tables

http://jsfiddle.net/gfmbkmmn/1/

The above function provides an alternative solution for handling multiple tables with one event handler. If you need more information to debug your code:

Note: In iOS, it's recommended to use window.onload. Also, what does the script tag in your "current code" do?

If you have any questions about the code, feel free to ask.

EDIT

function getValue(event){
 event=event||window.event;//not necessary
 event.target=event.target||event.srcElement;//not necessary
 if(event.target.nodeName=='TD'){// check if it's a td
  alert(event.target.bgColor);// why use 'targ.attributes.bgcolor.value'?
 }
}

The node bug dates back 7 years ago "Changed 7 years ago by ..."

JavaScript is case sensitive: bgcolor != bgColor

http://jsfiddle.net/gfmbkmmn/2/ This simple example allows you to create a quick color palette.

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

Creating a multi-dimensional array in JavaScript with two different sizes

I'm struggling to find the best way to create a multi-dimensional array with varying sizes dynamically. Our user interface requires a pattern where there are rows of 4 items followed by rows of 3 items. This pattern should continue until all contents ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

AJAX jQuery requests can flatten arrays when they are sent

The below code shows an endpoint written in Express, using the body-parser middleware. app.post("/api/poll/new",api.NewPoll); api.NewPoll = function(req,res){ if(!req.body) return res.status(400).send("MISSING BODY"); console.log(req.body,typeof(r ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

Transmitting FormData from Angular to a .NET MVC Controller

Here's my perspective: <form ng-submit="onFormSubmit()"> <div class="form-group"> <label for="Movie_Genre">Genre</label> @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Na ...

What are the reasons behind the pagination with numbers not functioning properly in Vue?

I've encountered an issue with my Vue application using Vuex while implementing pagination. The problem lies in the fact that the events stored are not being displayed, and neither are the page numbers for pagination. Another issue is that the paginat ...

Vue Router consistently triggers browser reloads, causing the loss of Vuex state

I encountered an issue that initially appeared simple, but has turned out to be more complex for me: After setting up a Vue project using vue-cli with Router, VueX, and PWA functionalities, I defined some routes following the documentation recommendations ...

Prevent the event from bubbling up on active elements

Having trouble with stopping event propagation? Picture this situation: <table id="test"> <tbody> <tr> <td class="row"> </td> <td class="row"> </td> <td class="ro ...

Enhance your spreadsheet by incorporating dynamic columns utilizing xlsx and sheetjs libraries

I have an array consisting of multiple tags with unique ids and corresponding data: [ { "id": "tagID1", "error": { "code": 0, "success": true }, "data": [ [1604395417575, 108 ...

How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts). My goal is to transfer the option val ...

Using AngularJS to hide elements within a nested dictionary structure

My dictionary structure is as follows: var data = { a: [1, 2, 3, 4, 5], b: [ [1, 2], [3, 4], [5, 6] ] }; Currently, I am using ng-hide to hide an element if the value 2 exists in data->a. Here's how it's implemented: <i ...

Testing HTTP requests on a form click in Vue.js 2 - Let's see how

Within my component, I have the following method: methods:{ ContactUs(){ this.$http.post("/api/contact-us").then((res)=>{ ///do new stuff },(err)=>{ //do new stuff }) ...

Having trouble seeing the output on the webpage after entering the information

I can't seem to figure out why the result is not displaying on the HTML page, so for now I have it set up as an alert. <h1>Factorial Problem</h1> <form name="frm1"> Enter any number :<input type="text" name="fact1"& ...

determining the file size of images being loaded remotely by retrieving their image URLs

There is a straightforward regex function in jQuery that I'm using to automatically add an image tag to image URLs shared by users. This means that when a user posts something like www.example.com/image.jpg, the image tag will be included so that user ...

Can someone provide a description for a field within typedoc documentation?

Here is the code snippet: /** * Description of the class */ export class SomeClass { /** * Description of the field */ message: string; } I have tested it on the TSDoc playground and noticed that there is a summary for the class, but not for it ...

Advanced automatic type inference for object literals in TypeScript

When working with TypeScript, I often declare generic functions using the syntax: const fn: <T>(arg: T)=>Partial<T> While TypeScript can sometimes infer the type parameter of a function based on its parameters, I find myself wondering if t ...

When a model.find is passed as an argument to be invoked, it results in an error

After working with ExpressJS for a while, I decided to explore using Mongoose alongside it. In the callback of my queries where I handle errors like this: function( error, data ) {...} , I found myself repeating code. To streamline this process, I created ...

Vuejs is throwing an error claiming that a property is undefined, even though the

I have created a Vue component that displays server connection data in a simple format: <template> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="page-header"> < ...

Utilizing Html.BeginCollectionItem helper to pass a collection with only a glimpse of the whole picture

After seeking guidance from Stephen Muecke on a small project, I have encountered an issue. The javascript successfully adds new fields from the Partial View and connects them to the model through "temp" values set by the controller method for the partial ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...