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

Steps for implementing Onclick event within the <Script> tag to display a div:

I am currently working on a code that allows me to show and hide a <div> element after clicking on an advertisement from any website. This advertisement is generated by a script. How can I implement the onclick event within the <script> tag? T ...

access the database information within the fullcalendar plugin

I've been exploring the calendar code on arshaw/fullcalendar and made some modifications, but I'm still unsure how to link JavaScript with a database. Here is the original code: $(document).ready(function() { var date = new Date(); var d = dat ...

Implementing beans within an HTML form action allows for seamless communication between the form and

I am seeking assistance as I am unable to locate any tutorials online for the issue I am facing. How do you go about using a <bean:write....> within a <html:form....> The code I have written is: <html:form action="/restricted/client/so ...

What is the best method for choosing HTML "ids" that are generated automatically by DevExpress controls using JavaScript DOM manipulation?

How can I create a pop-up that displays unique information for each of the hundreds of html divs with a common class but individual ids generated by DevExpress Controls? I have a large number of automatically generated html div "ids" and I'm looking ...

Are there any options available for customizing the animation settings on the UI-bootstrap's carousel feature?

If you're interested in seeing an example of the standard configuration, check out this link. It's surprising how scarce the documentation is for many of the features that the UIB team has developed... I'm curious if anyone here has experie ...

Trouble with AJAX request on iPad, works perfectly on desktop

Here is some of my custom plugin code (function ($) { $.fn.createGallery = function(options) { var theObject = $(this); var settings = $.extend({ // Default settings. server: 'http://localhost/jQuery%20Gall ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Is the memory usage of node.js proportional to the number of concurrent requests, or is there a potential memory leak?

Running the following node.js code: var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/plain'}); res.write("Hello"); res.end(); }).listen(8888); Upon starting the server ...

Assign object properties to a constant variable while validating the values

When receiving the features object, I am assigning its values to constants based on their properties. const { featureCode, featureSubType, contentId, price, family: { relationCountsConfig: { motherCount, fatherCount, childrenCount }, max ...

Creating a new session in Node.js for every request

Our team is currently developing a nodejs application that requires the maintenance of sessions. We have implemented express to handle node variables, but we are facing an issue where a new session is created every time we hit a new service. The structure ...

Determine the length of the content within an HTML container that has

I am attempting to retrieve the length of the container's content in HTML dynamically. However, I am only receiving the object instead of the desired result. <script> $(document).ready(function (e) { var adsense_box_len = $(&apo ...

Is it possible to extract the CSS path of a web element using Selenium and Python?

I am working with a collection of elements using find_elements_by_css_selector, and my next task is to extract their css locators. I attempted the following approach: foo.get_property('css_selector') However, it seems to be returning None. ...

The functionality of aria-expanded is not functioning properly when set to false

Having trouble with the bootstrap accordion feature. When the page loads, the accordions are expanded by default instead of being collapsed. I want them to start collapsed and then expand when clicked. Here is the HTML code: <!DOCTYPE html> &l ...

Utilizing Filters to Dynamically Highlight and Unhighlight HTML in Angular

Currently, I am experimenting with creating a series of filters that can dynamically highlight and remove highlighting from generated HTML: Highlight filter: app.filter('highlight', function ($sce) { return function (str, termsToHighlight) ...

Tips for correctly deleting a duplicate ref Object ID following the removal of a Document

Coming from a background in relational databases, I'm encountering a challenge with a pattern in Mongoose. Let's say we have SchemaA and SchemaB (for example, pets and people): const Person = new Schema({ name: String, pets: [{ ref: ...

Remove an item from an array in JavaScript by specifying its value, with compatibility for IE8

Is there a way to remove an item from an array by its value rather than index, while ensuring compatibility with IE8? Any assistance would be greatly appreciated. Thank you. Below is the array in question: var myArray = ['one', 'two', ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...

The synchronization between Typescript and the HTML view breaks down

I am currently working on an application that retrieves user event posts from MongoDB and displays them in HTML. In the Event-post.ts file, inside the ngOnInit() function, I have written code to retrieve the posts using the postsService.getPosts() method. ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Exporting two functions in JavaScript

Currently utilizing React, Redux, and experimenting with Material-UI integration. The example codes provided by Redux and Material-UI libraries include an 'export' statement at the end. Redux: export default connect(mapStateToProps, actions)(my ...