Tips on modifying classes within specific sections of HTML tables

I attempted to create calendar-like tables,

In my script, I am trying to handle events being registered.

My goal is to change the classes of cells from 2 to 5 when they are clicked on, and change the cell colors from first to hovered to aqua.

For this purpose, I have set a variable called first, but it seems like I need to define a second variable as well.

Do you know of any solutions for this issue?

Appreciate your help!

var first;

$("td").on('click', function(){
  first = this.id;
 });
 


$("td").hover(function() {
    const id = Number($(this).attr('id'));
      $("table td").removeClass("aqua");


    for(var j = first;j <= id; j++){
      $("#"+j).addClass("aqua");
    }
  });
  
    $("td").on('click', function(){
  second = this.id;
 });
.aqua{
  background-color: aqua;
}


td {
  padding: 10px;
  transition-duration: 0.4s;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
   </tr>
 <tr>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
    </tr>
  <tr>
  <td id="9">9</td>
  <td id="10">10</td>
  <td id="11">11</td>
  <td id="12">12</td>
  </tr>
</table>

Answer №1

  • Calendars are not closely related to tabular data, except for the day-of-week information. Using <div> elements instead of <table> is more convenient.
  • It's important to keep selection and hover states separate. They should not be grouped together.
  • To tackle your problem effectively, create a specialized Array that will store the sorted minimum and maximum values of a selection as a range.
  • For highlighting desired Elements, utilize .slice(start, end) function.
  • Class names should be neutral in terms of color. Opt for is-active and is-hover instead.

function CalendarSelection() {

  const $days = $(this).find('.d.m_this');
  const range = [-1, -1];

  const $daysRange = rng => {
    rng.sort((a, b) => a - b);
    return $days.slice(rng[0], rng[1] + 1);
  }

  function hoverRange(ev) {
    if (range[0] < 0 || (range[0] > -1 && range[1] > -1)) return; // Do nothing
    $days.removeClass('is-hover');
    if (ev.type === 'mouseleave') return; // Stop here, it's a mouseleave.
    $daysRange([range[0], $days.index(this)]).addClass('is-hover');
  }

  function activeRange() {
    $days.removeClass('is-active is-hover');

    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);
      $daysRange(range).addClass('is-active');
    }

    if (range[0] < 0 && range[1] < 0) { // SET START
      range[0] = $days.index(this);
      $daysRange([range[0], range[0]]).addClass('is-active');
    }
  }

  $days.on({
    click: activeRange,
    mouseenter: hoverRange,
    mouseleave: hoverRange,
  });
}

// Apply to all .calendar on page
$(".Calendar").each(CalendarSelection);
* {
  box-sizing: border-box;
  font: 14px/1.4 sans-serif;
}

.Calendar {
  display: flex;
  flex-flow: row wrap;
  max-width: 260px;
}

.Calendar>* {
  flex: 0 0 14.28%;
  text-align: center;
  padding: 0.5em;
}

.Calendar .wd {
  font-weight: bold;
}

.Calendar .d.m_this {
  transition: 0.2s;
  cursor: pointer;
}

.Calendar .d.m_this.is-hover {
  background: hsl(180, 70%, 90%);
}

.Calendar .d.m_this.is-active {
  background: hsl(200, 70%, 80%);
}

.Calendar .d.m_this:hover {
  background: hsl(180, 70%, 70%);
}
<div class="Calendar">
  <div class="wd">MO</div>
  <div class="wd">TU</div>
  <div class="wd">WE</div>
  <div class="wd">TH</div>
  <div class="wd">FR</div>
  <div class="wd">SA</div>
  <div class="wd">SU</div>

  <div class="d m_prev"></div>
  <div class="d m_prev"></div>
  <div class="d m_this">1</div>
  <div class="d m_this">2</div>
  <div class="d m_this">3</div>
  <div class="d m_this">4</div>
  <div class="d m_this">5</div>
  <div class="d m_this">6</div>
  <div class="d m_this">7</div>
  <div class="d m_this">8</div>
  <div class="d m_this">9</div>
  <div class="d m_this">10</div>
  <div class="d m_this">11</div>
  <div class="d m_this">12</div>
  <div class="d m_this">13</div>
  <div class="d m_this">14</div>
  <div class="d m_this">15</div>
  <div class="d m_this">16</div>
  <div class="d m_this">17</div>
  <div class="d m_this">18</div>
  <div class="d m_this">19</div>
  <div class="d m_this">20</div>
  <div class="d m_this">21</div>
  <div class="d m_this">22</div>
  <div class="d m_this">23</div>
  <div class="d m_this">24</div>
  <div class="d m_this">25</div>
  <div class="d m_this">26</div>
  <div class="d m_this">27</div>
  <div class="d m_this">28</div>
  <div class="d m_this">29</div>
  <div class="d m_this">30</div>
  <div class="d m_this">31</div>
  <div class="d m_next"></div>
  <div class="d m_next"></div>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

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

What is the best way to engage with a JavaScript/ClojureScript wrapper library for an API?

While I usually work with Python, I have recently been delving into learning Clojure/ClojureScript. To test my skills, I've set out to create a ClojureScript wrapper for Reddit's API. My main challenge lies in the asynchronous nature of Javascri ...

How can you utilize CSS grid to position an alternate symbol alongside ordinary text?

Does anyone have suggestions on how to align an "alt symbol" with "regular text"? I'm struggling to center both elements without resorting to hacky solutions. Currently, I am using CSS grid, but I am open to exploring other solutions that are easy an ...

Flask-WTForms QuerySelectField not displaying properly when rendered with Bootstrap causing <select> HTML tag issue

I am facing an issue while constructing a Flask form that includes a QuerySelectField. Despite having everything in place, Bootstrap is displaying the <select> as if it were a text input field. Upon inspecting the page source, I noticed that the fie ...

Guide on setting up a new NPM and JavaScript project within Visual Studio 2015

Whenever I watch tutorials, they always mention having a "special npm reference" that I seem to be missing. https://i.sstatic.net/I52dn.png All I can find are the "normal" references (.net assemblies). I also can't locate any project type labeled as ...

Understanding the distinction between deleting and nullifying in JavaScript

var obj = {type: "beetle", price : "xxx", popular: "yes" ,.... }; If I want to remove all the properties from obj, what is the correct way to do it? Should I use delete obj.type; delete obj.price; delete obj.popular ... and so on. Or should I set ob ...

Slow auto page refresh in local development for Angular2 on Windows can be quite frustrating

Recently diving into angular2 and following the heros tutorial from docs. Struggling with a sluggish development experience while working with angular2. It's taking approximately 5 seconds for angular2 to recognize changes in files, followed by anothe ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...

NuxtJS Static generated HTML page fails to load JavaScript while accessing /index.html

I'm currently working on a project using Nuxt.js to generate static content, which involves utilizing JavaScript for tasks such as navigation and form functionality. Everything works smoothly when running the page with npm run dev. However, after ex ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...

Sending a different name for the jQuery parameter

I'm looking to select CSS settings based on the presence of a data tag. What would be the correct approach for this? var datadirection = 'left'; //default direction if( $(this).attr('data-right') ){ datadirection = 'righ ...

Learn the step-by-step process of cropping and zooming an image using the react-image-crop

I am looking to implement zooming and cropping functionality for an image using react-image-crop instead of react-easy-crop. Currently, the cropping does not take into account the zoom level set by ReactCrop's scale property. I want to be able to zo ...

What could be causing my JavaScript pricing calculator to malfunction?

I've been struggling to make the script below work, but I can't seem to figure out why. It should be functioning properly. Even though all variables are in place, no price is appearing? You can view the HTML on this page: var cake_prices = n ...

Checking for jQuery's presence in Node.jsIn this guide, we will go over how

After using npm install jquery and adding the following code to my server.js file to check if jQuery is loaded: io.sockets.on('connection', function(socket) { console.log("Connection " + socket.id + " accepted."); // Check if jQuery is ...

Is the functionality of this.value compatible with Firefox but not with Internet Explorer?

I am facing an issue with the onChange event on a select element. When I use alert(this.value), it works fine on Firefox, but not on Internet Explorer. What could be causing this discrepancy? Below is the code snippet in question: <select onchange="n ...

Error Icon Displayed Incorrectly in Dynamically Generated List Items in Phonegap Android App

My attempt to dynamically create a list item with JSON response and set the data-icon to "check" is not working as expected. The result always shows "arrow-r" data-icon instead. This is how I generate the list item: function CallvarURL(url) { var res ...

Position the Bootstrap icon to float to the far right

My icon is always positioned to the right instead of beside the input field. Take a look at the image below: https://i.stack.imgur.com/Bb1eH.png The icon does not align next to the input field. This is my code snippet : <div class="form-horizontal"& ...

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

Arrange the JSON object according to the date value

I am working on a JavaScript project that involves objects. Object {HIDDEN ID: "06/03/2014", HIDDEN ID: "21/01/2014"} My goal is to create a new object where the dates are sorted in descending order. Here's an example of what I want: SortedObject ...

Error in React-Native: Unable to locate main project file during the build process

Just integrated cocoapods into a React Native project. After a successful build, RN is throwing this error... https://i.stack.imgur.com/czn2W.png No errors in Xcode during the build process, but Xcode is displaying these warnings https://i.stack.imgur.c ...

Ways to manipulate the content of a div

HTML <span class = "Box"> <div class = "active"> <a href ="#-night"> <span class ="list">4</span> <span class="locations"><?php echo $location; ?></span> <span ...