Utilize jQuery to toggle and swap between multiple classes

I am looking to implement a feature where clicking on certain cells will add and switch classes, similar to a calendar schedule.

I attempted the code sample below, but it did not successfully toggle each class.

The desired outcome is to switch classes like this through clicks:

nullclassAclassBclassCnullclassA

Here is my current code snippet:

$("#our_calendar td")     
      .click(function() {  
       $(this).toggleClass('classA classB classC');
 });

I intend to change the color of the cells by creating corresponding CSS styles for them.

.classA {
    background-color: rgb(0,255,0);
}

.classB {
    background: linear-gradient(to bottom, yellow 49%,yellow 1%, rgb(0, 255, 0) 1%,rgb(0, 255, 0) 50%);
}

.classC {
    background: linear-gradient(to bottom, yellow 49%,yellow 1%, aqua 1%, aqua 50%);
}

If anyone knows how to achieve this functionality, please share your insight. Thank you!

Answer №1

If you're looking for a solution, consider implementing the following logic. Begin by creating a local variable that stores an array of classes. Utilize the data-class-index attribute within the td elements to determine which class to apply next.

Take a look at the code snippet below:

$(function(){
 var classArray = ['class1','class2','class3'];
 var arrLength = classArray.length;
 $("#calendar_table td").click(function() {  
       var currentIndex = $(this).data('class-index');
       $(this).removeClass(classArray[currentIndex]);
       if(currentIndex < (arrLength-1)) {
         currentIndex++;
       }  else {
         //reset index
         currentIndex = 0;
       }
       $(this).addClass(classArray[currentIndex]);
       $(this).data('class-index',currentIndex);
 });
});
.class1 {
    background-color: rgb(255,0,0);
}

.class2 {
    background: linear-gradient(to bottom, green 49%,green 1%, rgb(255, 0, 0) 1%,rgb(255, 0, 0) 50%);
}

.class3 {
    background: linear-gradient(to bottom, green 49%,green 1%, blue 1%, blue 50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="calendar_table">
 <tr><td class="class1" data-class-index="0">Date Value 1</td></tr>
 <tr><td class="class1" data-class-index="0">Date Value 2</td></tr>
 <tr><td class="class1" data-class-index="0">Date Value 3</td></tr>
</table>

Answer №2

To toggle multiple classes, you need to call the toggle function for each individual class. For more information, refer to this thread on Stack Overflow: ( Toggle multiple element classes with jQuery)

 $("#our_calendar td")    
    .click(function() {  
     $(this).toggleClass("classA").toggleClass("classB").toggleClass("classC");
 });

View the working example here:

https://jsfiddle.net/mohammadyaseer/qn2m01fu/4/

Answer №3

To customize your jQuery code, consider making the following adjustments:

$("#our_calendar td").click(function() {
   if ($(this).hasClass("classA")) {
    $(this).toggleClass("classA classB");
  } else if ($(this).hasClass("classB")) {
    $(this).toggleClass("classB classC");
  } else if ($(this).hasClass("classC")) {
    $(this).toggleClass("classC");
  }
});

If you want to cycle through the classes instead, you can try this method:

$("#our_calendar td").click(function() {
   if ($(this).hasClass("classA")) {
    $(this).toggleClass("classA classB");
  } else if ($(this).hasClass("classB")) {
    $(this).toggleClass("classB classC");
  } else if ($(this).hasClass("classC")) {
    $(this).toggleClass("classC classA");
  }
});

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

Using two different Readable streams to pipe to the same Writable stream multiple times

In my current project, I am facing the challenge of concatenating a string and a Readable stream. The Readable stream is linked to a file that may contain data in multiple chunks, making it quite large. My objective is to combine these two entities into on ...

Assigning a class to the following item in a list with a click event (However, this action will cease once the last item

I have implemented a feature where users can scroll through different dates in a list using the Next or Prev buttons. The functionality involves removing the class active from the current element and adding it to the next one upon button click. However, I ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

Enable swipe functionality for mobile users

Looking to make the code below swipable on mobile devices. Any suggestions or resources to achieve this would be greatly appreciated! <script> var links = document.querySelectorAll(".heart"); var wrapper = document.querySelector("# ...

Integrating data binding within a .append function using AngularJS

I followed this code example (http://jsfiddle.net/ftfish/KyEr3/) to develop a form. However, I encountered an issue with an input having ng-model set to "value" and needing to display that value within {{ }} in a TD: angular.element(document.getElementByI ...

Fill in a text box with a chosen value from a linked drop-down menu

My database contains two tables: 1 - tbl_category 2 - tbl_shelf_place I am working towards displaying the shelf_code in a textbox based on the selected category_name from a drop-down (book_category) with a value of category_id, instead of using another ...

Filtering a section of the HTML using Ajax and jQuery

Dealing with an Ajax call in jQuery that's delivering a lot of unexpected HTML content. I'm attempting to extract the specific part I need, but the console is showing an empty string. Can anyone provide guidance on resolving this issue? $.ajax({ ...

A guide to revealing the value of a button or anchor tag using AngularJS

I'm working on a way to show a button or anchor tag value depending on the true or false value returned by my angular variable. Here's a snippet of my code: <a href="#" id="verify">{{userInformation.value}}</a> The userInformation.v ...

Sending data from a dynamically created PHP table to a modal

In my PHP-generated table, I have: <tbody> <?php $results = DB::select()->from('users')->execute(); foreach ($results as $user) { echo "<tr id='".$user['id']."'> <input type=&bs ...

Having difficulty sending a jQuery ajax() request to a PHP file

I am facing an issue with using the ajax() function. I have an HTML file containing a form and some JavaScript code: <script> $(document).ready(function(){ $("form").submit(function(){ var url = "xxx.php/"; ...

Guide to dynamically inserting an audio file into a div with jQuery

I am looking to dynamically insert an audio file. Below are the declared tags: <div> <audio id="myaudio"> </audio> </div> Now, I am trying to add the source dynamically. Can anyone help me with how to add it to the div or audi ...

If the socket cannot be found, an error callback will be activated

Below is the method I am using to send a message to a targeted socket connection. socket.broadcast.to(socketid).emit('message', JSON.stringify(data)); If the specified "socketid" does not exist, is there a mechanism in place to capture the erro ...

Only the initial value is being processed in the for loop using Javascript

I am having issues trying to sum the values within a for loop sourced from my Django database using JavaScript. Currently, when I iterate through the loop, only the first value in the array is returned. I need assistance in finding a solution that allows ...

Working with CSS3 transitions in PHPStorm is a breeze

For some reason, my phpstorm does not provide code completion for CSS properties like -webkit-translate, translate, or animation. Has anyone encountered this issue before? Any suggestions on how to fix it? ...

The function of React's useState is not available

https://i.sstatic.net/ltglP.png This error is new to me and I'm unsure why my code isn't working correctly. I noticed a similar example on the React.js Org website. Can someone please explain what's happening in my code? Any help would be ...

Select the hidden HTML option value automatically according to the previous option selected

I am working on a form that includes 2 select tags with the options male and female. The first select, "gender", is visible to the user while the second select, "age", is hidden. <select name="gender"> <option value="1">Male</option> ...

The website's scrolling speed is painfully slow

Currently, I am working on enhancing the performance of this site at . If you scroll through the site or navigate using the Up and Down Arrow Keys, you may notice a sluggish and slow Scroll Behaviour. I am utilizing HTML5 and simple img tags with 85% wid ...

How can I solve the issue of connecting to a database with mysql_connect() in PHP?

While using PHP and AJAX to query a database, I encountered the following error messages: Warning: mysql_query() [function.mysql-query]: A link to the server could not be established... and Warning: mysql_query() [function.mysql-query]: Can't connect ...

determining the window width using javascript

Just diving into the world of JavaScript and attempting to implement some code that will only execute when the window is larger than 768 pixels. Here is what I've come up with: if ($(window).width() > 768) { const central = document.querySele ...

Retrieving the Input Value in Laravel Views

I'm currently working on a webpage that features two forms structured like this: index.blade.php: <form action="/" method="post"> <input type="text" list="cats" name="catipt" id="catip ...