Creating multifunctional arrays in HTML tables

My goal is to create tables where each cell changes its class upon being clicked.

As I set up the table, I want to track the history of clicked cells in an array.

Currently, the history array is stored in the 'clicked' array:

array=[1,4,6,9]

However, my desired result would be:

array=[[1,2,3,4],[6,7,8,9]]

or

array=[[1,4],[6,9]]

Essentially, I wish to obtain parent keys for manipulation with each class change.

If you have any suggestions or recommendations, please feel free to share them.

Answer №1

Could this be of assistance?

let sets = []
  clicked.forEach((item,i) => { 
    if (i===0 || i%2===0) sets.push([])
    sets[sets.length-1].push(item)
  })  

let html = ''
html += '<table>';
let i = 0;
for (let w = 0; w < 10; w++) {
  html += '<tr>';
  for (let d = 0; d < 10; d++) {
    i = i + 1;
    html += '<td data-layer=0>' + '<div>' + i + '</div>' + '</td>'
  }
  html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;


const $days = $("td");
const range = [-1, -1];

let clicked = [];



$(function() {
  $("td").click(function() {

    if (range[0] > -1 && range[1] > -1) { // RESET
      range[0] = -1;
      range[1] = -1;
    }

    if (range[0] > -1 && range[1] < 0) { // SET END

      range[1] = $days.index(this);

      $days.slice(range[0], range[1] + 1).addClass('is-active');

    }

    if (range[0] < 0 && range[1] < 0) { // SET START
      range[0] = $days.index(this);
    }

    let clickedID = $days.index(this);
    clicked.push(clickedID)
    let sets = []
    clicked.forEach((item,i) => { 
      if (i===0 || i%2===0) sets.push([])
      sets[sets.length-1].push(item)
    })  
    console.log("Array of clicked cells", sets);
//    $(".is-active").each((i,td) => console.log(td.innerText))


  });
});
td {
  transition-duration: 0.5s;
  border: solid black 1px;
  cursor: pointer;
}

div {
  padding: 5px;
}

table {
  border-collapse: collapse;
}

.aqua {
  background-color: aqua;
}

td:hover {
  background-color: yellow;
}

.is-active {
  background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id=calendar></div>

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

Exploring the images in a continuous loop

Looking to create a unique image looping effect using HTML, CSS, and Jquery/Javascript. The concept is to display several images on one page that do not move, but loop through them one at a time while displaying text above the current image. For example, ...

What is the correct way to display or hide a button based on my specific situation?

Creating a 'show more' button for my app has presented me with a challenge. I am using a directive to handle actions when the user clicks on the read more button: (function(window, angular) { var app = angular.module('myApp'); ...

Various Ways to Add Hyperlinks in HTML Using CSS Styles

Does anyone know how I can link multiple HTML files to one hyperlink, where only one file opens randomly when clicked? I am currently using . Your assistance would be greatly appreciated! I've tried searching online for a solution, but haven't ...

Issue with Nextjs: getServerSideProps causing a blank page to display instead of redirecting to 404errorCode

I am facing an issue on my dynamic page where the external server returns a 404 error if the requested product is not found. However, when using getServerSideProps, instead of redirecting to a 404 page, it shows a blank page. Below is the code snippet: // ...

Successfully connected to the database, however the retrieved information is being returned as a

$db_connection = mysqli_connect('localhost', 'root', '', 'fireworks'); $query = "SELECT * FROM name"; $result = mysqli_query($db_connection, $query) or die(); while ($info = mysqli_fetch_assoc($result)); { var_d ...

What is the best approach to integrate a JQuery-powered widget into a Vue.js module for seamless use?

I have a group of colleagues who have started developing a complex web application using Vue.js. They are interested in incorporating some custom widgets I created with JQuery in the past, as re-creating them would be time-consuming and challenging. While ...

When adjusting to mobile dimensions, the responsive website design struggles to center the navbar properly

I am currently developing my senior year portfolio website and I am struggling to center the navbar (Work About Contact) when it is in mobile mode. My goal is for it to be positioned directly below the logo, perfectly centered, but so far nothing I have tr ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...

Website issues being displayed by Internet Explorer

Greetings! Let me begin by saying how wonderful this page is - I have already found many answers here before. Please forgive any errors in my English :) In my efforts to optimize my website for SEO and increase its speed, I made several changes. The site ...

Text within the footer section

When displaying the name of a subcategory, I want it in one line. However, if the subcategory name contains two words, it should be displayed in two lines. https://i.stack.imgur.com/CcDeL.png Code: .Footer { width: 100%; display ...

Ensure the presence of an HTML element in a directive when conducting unit tests

I have developed a custom directive called "generate-form-field-directive" that dynamically generates a form field based on the type received. Here is the code snippet for the directive - (function () { "use strict"; var app = angular.module("appModule" ...

What is the process for accessing someone's birthday information using the Facebook API?

Working on integrating Facebook login and successfully retrieving user details such as first_name, email, etc. However, encountering an issue with fetching the birthday information. When attempting to call for birthday using the code snippet below, no data ...

Breaking down a string using JavaScript

Is there a way to shorten the following code? It currently works for me, but it seems quite long-winded. var str = "some title of an event here, weekday 17:00&nbsp;&ndash;&nbsp;18:00 o’clock, with name of a person"; var date = str.split(&apo ...

Guide on transferring a WordPress website to a new domain

I manage a WordPress blog on my main domain, but I am looking to duplicate the entire blog onto a secondary "dummy" domain so I can experiment with significant changes without impacting my primary domain. My main domain is and my dummy domain is Althoug ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

Endless Loop: AngularJS app.run() Promise caught in infinite cycle

I have a situation in my AngularJS app where I am using app.run() to check if a user is logged in before displaying the site to restrict access to non-registered users. Initially, I faced issues with the isLoggedIn function returning false when reloading t ...

Steps to prevent cart resizing in desktop view:

For a front-end challenge, I need you to design a simple card that displays consistently in both mobile and desktop views. I took a mobile-first approach because I've encountered issues where the card layout changes when viewed on desktop. Check out ...

Strategies for managing rate-limited API services in React/Node.js: Handling ReferenceErrors

Hey there! I'm new to the world of React and NodeJS, and right now I'm navigating my way through dealing with a rate-limited API service. My plan is to have NodeJS fetch data from this API every half an hour, then send it to my "/youtube" endpoin ...

Having trouble grasping ES6 concepts with Reactjs?

I am completely new to reactjs and recently followed a tutorial (link: https://www.youtube.com/watch?v=Ke90Tje7VS0). Currently, I am using Windows and following the commands in cmd as instructed in the tutorial: npm i -g <a href="/cdn-cgi/l/email-prote ...

Encountering "net::ERR_EMPTY_RESPONSE" error when making a HTTP PUT request using the HUE API in JavaScript

GET requests are functioning properly. PUT requests made from the API Debug tool are also working correctly. However, both PUT and POST requests, regardless of the data or API URL used, are resulting in the following error: example: OPTIONS net::ERR_ ...