Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create a local variable to track the position of individual cells within the array?

Despite my efforts to create a local variable specific to each cell, it hasn't been effective.

Below is the relevant JavaScript function:

var i = 1;
var table = document.getElementsByTagName('table')[0];
var def = ["tex/white.png", "tex/grass.jpg", "tex/stone.jpg", "tex/water.jpg", "tex/wood.jpg", "tex/lava.jpg"];
table.onclick = function(e) {
    var target = (e || window.event).target;
    if (target.tagName in { TD: 1, TH: 1 }) {
        target.className = "img";
        console.log((e || window.event).target);
        target.setAttribute('style', 'background-image:' + "url(" + def[i] + ")");
        if (i < def.length) {
            i++
        }
        if (i == def.length) {
            i = 0;
        }
    }
};

Here's a functioning fiddle showcasing my progress so far:
https://jsfiddle.net/6L0armd4/

The desired outcome is that the array starts at individual cells and counts specifically for those cells. Currently, it always advances to the next texture even when selecting a different cell.

Answer №1

An effective solution would involve utilizing unique IDs to distinguish each cell and maintaining an object to monitor the current background being utilized for each cell, with their IDs serving as keys.

<html>
<head>

</head>
<body>
<table>
<tr>
  <td id='1'></td>
  <td id='2'></td>
  <td id='3'></td>
</tr>
<tr>
  <td id='4'></td>
  <td id='5'></td>
  <td id='6'></td>
</tr>
<tr>
  <td id='7'></td>
  <td id='8'></td>
  <td id='9'></td>
</tr>
</table>
</body>
</html>

<script>
var table = document.getElementsByTagName('table')[0];
var def = ["https://cdn1.imggmi.com/uploads/2019/6/19/5e4aedcf566fa5e4501ab584d357be01-full.jpg", "https://cdn1.imggmi.com/uploads/2019/6/19/3d39445ffda6687a6b0e80a69a35fdea-full.jpg"];
var currents = {}

getNextIndex = function(index) {
  return index === undefined || index >= def.length - 1 ? 0 : index + 1
}

table.onclick = function(e) {
  var target = (e || window.event).target;    

  if (target.tagName in { TD: 1, TH: 1 }) {
    var new_bg_index = getNextIndex(currents[target.id])
    currents[target.id] = new_bg_index
    target.setAttribute('style', 'background-image:' + "url(" + def[new_bg_index] + ")");
  }
};
</script>

Answer №2

Ensure you create a listener event in order to change the color codes to image paths below and avoid any local path issues by using direct online images.

var table = document.querySelector('#table')
var selectedCells = table.getElementsByClassName('selected')

table.addEventListener('click', function(e) {
var td = e.target

if (td.tagName !== 'TD') {
return
}

if (selectedCells.length) {
selectedCells[0].className = ''    
}

td.className = 'selected'
})
table {
 cursor: text;
}
tr {
background-color:white;
}
td {
font-size: 14;
cursor: default;
}

td.selected {
background-color: red;

 // replace this with background image tag like this  
 background-image: url("paper.gif


<table border="1" cellpadding="8" cellspacing="2" id="table">
<tr>
<td>Cell one</td>
<td>Cell Tw</td>
<td>Cell three</td>
<td>Cell Four</td>
<td>Cell five</td>
<td>Cell sex</td>
<td>Cell five</td>
<td>cell seven</td>
<td>cell eight</td>
<td>cell nine</td>
<td>cell tens</td>
<td>cell eleven</td>
<td>cell twelve</td>
</tr>
<tr>
<td>AKo</td>
<td>KK</td>
<td>KQs</td>
<td>KJs</td>
<td>KTs</td>
<td>K9s</td>
<td>K8S</td>
<td>K7s</td>
<td>K6s</td>
<td>K5s</td>
<td>K4s</td>
<td>K3s</td>
<td>K2s</td>

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

Issue with onDblClick event in Angular5 and PrimeNG's p-listbox

I encountered an issue while using p-listbox's onDblClick event as it does not return the selected list element. Instead, the event object only contains the value of 'this'. {"originalEvent":{"isTrusted":true}} HTML Blockquote <!-- S ...

Troubles arise when trying to encapsulate a ReactJS embedded application with Material ui, causing issues with the

Currently, I am integrating a ReactJS application using Material UI styled components within a Wordpress page. To achieve this, I am utilizing webpack for transpilation of the JavaScript. After generating the bundle for the embedded version of the applica ...

What is the best way to execute synchronous calls in React.js?

Currently, I am a novice in working with React JS and I have been tasked with implementing a feature to reset table data in one of our UI projects. Here is the current functionality: There is a save button that saves all overrides (changes made to the or ...

What is the best way to compress HTML code within a webpage's source?

I have noticed that my template is filled with empty spaces after previewing the page due to using many tags. Is there a way to make my code more compact, similar to the example below: https://i.sstatic.net/ZBlbg.jpg [...] startsWith",function(a){return ...

How can you add padding to an HTML page using CSS?

I've been attempting to use padding-bottom:90px; in order to shift Tweets by ‎@StackOverflow (the entire tweets section) downwards on the page. I want to move it further down using the above padding, but it doesn't seem to be working for me. H ...

Editing an XML file on the browser and saving it in its original location on the local file system

Seeking assistance with editing an XML file directly from the browser on a local file system and saving it back to its original location. I have conducted extensive research using Google, but have not been able to find a suitable solution. Any help or gu ...

Is there a Wordpress floating bar similar to the one seen on 9gag?

After browsing through some posts on stackoverflow, I noticed that my website is not responding as expected. You can check out my site here: To troubleshoot, you can examine the source code and utilize Firebug to inspect the css and javascript being used ...

Having trouble with uploading an image in Laravel using a modal?

For my laravel inventory system, I am facing an issue with uploading images for products. The old code I used for image upload is not working in my current project where I am utilizing a modal and ajax request to save inputs in the database. Can anyone pro ...

How to retrieve the input value in React Autosuggest

I recently began my journey into learning JavaScript and React. Currently, I am working on creating a simple table with material design. The goal is to be able to add rows to the table through a form popup and delete rows using an icon within each row. On ...

Tips on how to navigate to the end of a div that has been created through ng-repeat in Angular JS with the

Here is the template code I am working with: <div class="chatbox" id="mailBody" > <div class="panel-body" ng-repeat="mail in mails"> <div class="m-b-none" ng-if="mail.inboxMessageType == 1"> <a href class="pull-left ...

The duration spent on a website using AJAX technology

We conducted an online survey and need to accurately calculate the time spent by participants. After using JavaScript and PHP, we found that the calculated time is not completely accurate. The original script was sending server requests every 5 seconds to ...

Exploring ES6 classes in Java Script: accessing prototype properties

After searching extensively for an answer and coming up empty-handed, I decided to pose my question here. When creating an object constructor in JavaScript as shown below: function Car(speed){ this.speed = speed; this.position = 0; } Car.prototype.m ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

React.js: Why does the array index change after dropping an element?

When I create a table with items in a checkbox list, the issue arises; after selecting and submitting some items, the index of the remaining items changes. Consequently, re-submitting the remaining items becomes impossible. Below is my code snippet: expo ...

Automatically adjusting jQuery script now functions on all hyperlinks for seamless resizing

I am attempting to create a rollover script that will resize my social network links when hovered over. The desired effect is for the 32px square icon to expand and display the trailing address. For example, when hovering over the Facebook link, it should ...

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

Combining Bootstrap with Rails

As I delve into the official documentation on incorporating Twitter Bootstrap in Rails, I stumbled upon an interesting tidbit: It mentions to eliminate all the *= require_self and *= require_tree . statements from the Sass file and opt for @import to im ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...