Tips for implementing an active class for td within jQuery tabs?

I'm currently using Jquery tabs within a table, and it's working fine. However, I need to activate the td when its link is clicked.

Here's my code:

$(document).ready(function() {
    $(".vertical_tabs_menu a").click(function(event) {
        event.preventDefault();
        var tab = $(this).attr("href");
        $(".vertical_tabs").not(tab).css("display", "none");
        $(tab).fadeIn();
    });
})
.vertical_tabs {
  display:none;
}

#tab-1 {
 display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vertical_tabs_menu">
        
        
        <table width="500" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td height="40"> <a href="#tab-1">Tab 1</a></td>
  </tr>
  <tr>
    <td height="40"><a href="#tab-2">Tab 2</a></td>
  </tr>
  <tr>
    <td height="40"> <a href="#tab-3">Tab 3</a></td>
  </tr>
  <tr>
    <td height="40"> <a href="#tab-4">Tab 4</a></td>
  </tr>
</table>
        
    </div>
    
    
    <div class="tab">
        <div id="tab-1" class="vertical_tabs" style="display:block;">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet purus urna. Proin dictum fringilla enim, sit amet suscipit dolor dictum in. Maecenas porttitor, est et malesuada congue, ligula elit fermentum massa, sit amet porta odio est at velit. Sed nec turpis neque. Fusce at mi felis, sed interdum tortor. Nullam pretium, est at congue mattis, nibh eros pharetra lectus, nec posuere libero dui consectetur arcu. Quisque convallis facilisis fermentum. Nam tincidunt, diam nec dictum mattis, nunc dolor ultrices ipsum, in mattis justo turpis nec ligula. Curabitur a ante mauri...
        </div>
        <div id="tab-2" class="vertical_tabs">
            <p>Donec semper dictum sem, quis pretium sem malesuada non. Proin venenatis orci vel nisl porta sollicitudin. Pellentesque sit amet massa et orci malesuada facilisis vel vel lectus. Etiam tristique volutpat auctor. Morbi nec massa eget sem ultricies fermentum id ut ligula. Praesent aliquet adipiscing dictum. Suspendisse dignissim dui tortor. Integer faucibus interdum justo, mattis commodo elit tempor id. Quisque ut orci orci, sit amet mattis nulla. Suspendisse quam diam, feugiat at ullamcorper eget, sagittis sed eros. Proin tor...
        
        </div>
        <div id="tab-3" class="vertical_tabs">
            <p>Duis egestas fermentum ipsum et commodo. Proin bibendum consectetur elit, hendrerit porta mi dictum eu. Vestibulum adipiscing euismod laoreet. Vivamus lobortis tortor a odio consectetur pulvinar. Proin blandit ornare eros dictum fermentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur laoreet, ante aliquet molestie laoreet, lectus odio fringilla purus, id porttitor erat velit vitae mi. Nullam posuere nunc ut justo sollicitudin interdum. Donec suscipit eros nec leo condiment...
        </div>
        <div id="tab-4" class="vertical_tabs">
            <p>Proin sollicitudin tincidunt quam, in egestas dui tincidunt non. Maecenas tempus condimentum mi, sed convallis tortor iaculis eu. Cras dui dui, tempor quis tempor vitae, ullamcorper in justo. Integer et lorem diam. Quisque consequat lectus eget urna molestie pharetra. Cras risus lectus, lobortis sit amet imperdiet sit amet, eleifend a erat. Suspendisse vel luctus lectus. Sed ac arcu nisi, sit amet ornare tellus. Pellentesque nec augue a nibh pharetra scelerisque quis sit amet felis. Nullam at enim at lacus pretium iaculis sit ame...
        </div>
    </div>

Can you please help me add a background color class for the entire td without affecting the anchor tags?

Answer №1

To apply the .active class, just utilize these 2 lines of code as shown in the example below.

$("td").removeClass("active");
$(this).closest("td").addClass("active");

Example

$(document).ready(function() {
  $(".vertical_tabs_menu a").click(function(event) {
    event.preventDefault();
    var tab = $(this).attr("href");
    $("td").removeClass("active");
    $(this).closest("td").addClass("active");
    $(".vertical_tabs").not(tab).css("display", "none");
    $(tab).fadeIn();
  });
})
.vertical_tabs {
  display: none;
}

#tab-1 {
  display: block;
}

.active{
  background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vertical_tabs_menu">


  <table width="500" border="1" cellspacing="0" cellpadding="0">
    <tr>
      <td height="40"> <a href="#tab-1">Tab 1</a></td>
    </tr>
    <tr>
      <td height="40"><a href="#tab-2">Tab 2</a></td>
    </tr>
    <tr>
      <td height="40"> <a href="#tab-3">Tab 3</a></td>
    </tr>
    <tr>
      <td height="40"> <a href="#tab-4">Tab 4</a></td>
    </tr>
  </table>

</div>


<div class="tab">
  <div id="tab-1" class="vertical_tabs" style="display:block;">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet purus urna. Proin dictum fringilla enim, sit amet suscipit dolor dictum in. Maecenas porttitor, est et malesuada congue, ligula elit fermentum massa, sit amet porta odio est
      at velit. Sed nec turpis neque. Fusce at mi felis, sed interdum tortor. Nullam pretium, est at congue mattis, nibh eros pharetra lectus, nec posuere libero dui consectetur arcu. Quisque convallis facilisis fermentum. Nam tincidunt, diam nec dictum
      mattis, nunc dolor ultrices ipsum, in mattis justo turpis nec ligula. Curabitur a ante mauris. Integer placerat imperdiet diam, facilisis pretium elit mollis pretium. Sed lobortis, eros non egestas suscipit, dui dui euismod enim, ac ultricies arcu
      risus at tellus. Donec imperdiet congue ligula, quis vulputate mauris ultrices non. Aliquam rhoncus, arcu a bibendum congue, augue risus tincidunt massa, vel vehicula diam dolor eget felis.</p>
  </div>
  <div id="tab-2" class="vertical_tabs">
    <p>Donec semper dictum sem, quis pretium sem malesuada non. Proin venenatis orci vel nisl porta sollicitudin. Pellentesque sit amet massa et orci malesuada facilisis vel vel lectus. Etiam tristique volutpat auctor. Morbi nec massa eget sem ultricies
      fermentum id ut ligula. Praesent aliquet adipiscing dictum. Suspendisse dignissim dui tortor. Integer faucibus interdum justo, mattis commodo elit tempor id. Quisque ut orci orci, sit amet mattis nulla. Suspendisse quam diam, feugiat at ullamcorper
      eget, sagittis sed eros. Proin tortor tellus, pulvinar at imperdiet in, egestas sed nisl. Aenean tempor neque ut felis dignissim ac congue felis viverra. </p>

  </div>
  <div id="tab-3" class="vertical_tabs">
    <p>Duis egestas fermentum ipsum et commodo. Proin bibendum consectetur elit, hendrerit porta mi dictum eu. Vestibulum adipiscing euismod laoreet. Vivamus lobortis tortor a odio consectetur pulvinar. Proin blandit ornare eros dictum fermentum. Class aptent
      taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur laoreet, ante aliquet molestie laoreet, lectus odio fringilla purus, id porttitor erat velit vitae mi. Nullam posuere nunc ut justo sollicitudin interdum. Donec
      suscipit eros nec leo condimentum fermentum. Nunc quis libero massa. Integer tempus laoreet lectus id interdum. Integer facilisis egestas dui at convallis. Praesent elementum nisl et erat iaculis a blandit ligula mollis. Vestibulum vitae risus dui,
      nec sagittis arcu. Nullam tortor enim, placerat quis eleifend in, viverra ac lacus. Ut aliquam sapien ut metus hendrerit auctor dapibus justo porta. </p>
  </div>
  <div id="tab-4" class="vertical_tabs">
    <p>Proin sollicitudin tincidunt quam, in egestas dui tincidunt non. Maecenas tempus condimentum mi, sed convallis tortor iaculis eu. Cras dui dui, tempor quis tempor vitae, ullamcorper in justo. Integer et lorem diam. Quisque consequat lectus eget urna
      molestie pharetra. Cras risus lectus, lobortis sit amet imperdiet sit amet, eleifend a erat. Suspendisse vel luctus lectus. Sed ac arcu nisi, sit amet ornare tellus. Pellentesque nec augue a nibh pharetra scelerisque quis sit amet felis. Nullam
      at enim at lacus pretium iaculis sit amet vel nunc. Praesent sapien felis, tincidunt vitae blandit ut, mattis at diam. Suspendisse ac sapien eget eros venenatis tempor quis id odio. Donec lacus leo, tincidunt eget molestie at, pharetra cursus odio.
      </p>
  </div>
</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

Using video instead of static slides in HTML5

I am interested in adding a video background with text overlay on my website, similar to what can be seen here: Although I understand it involves CSS, I am struggling to achieve the desired effect. Here is the code snippet I have been using: video#bgvid ...

Ways to make a div fill the whole screen and allow for scrolling as well

Issue I'm facing an issue with the login.php screen and the addphoto.php screen. I want these screens to cover the entire page, but despite using the following code: .login-screen, .form-screen { position: fixed; top: 0; left: 0; disp ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

Ways to update list item text with jQuery

I am attempting to create a button that can replace the content of a list item. Although I have looked at other solutions, I keep encountering this error message: Uncaught TypeError: Object li#element2 has no method 'replaceWith' I have experime ...

What is the best way to get padding to work on text that wraps using CSS?

Take a look at this simple example: https://codepen.io/cpcpcpcpcpx/pen/VwZWoyJ Here's what it includes: .wrapper { width: 200px; } h1 { font-size: 32px; font-family: Tahoma, Helvetica, sans-serif; line-height: 50px; } .header-text { ba ...

The combination of AngularJS, jQuery, mobile angular ui, and phonegap results in disappointment

I'm embarking on my first venture into mobile app development. I'll be utilizing AngularJS, Mobile Angular UI, jQuery, and PhoneGap for this project. Here is a snippet of my code: <!doctype html> <html> <head> <script s ...

Preview multiple images while uploading in a React JS application

In order to achieve multiple image upload with preview using React JS, I attempted the code below. However, I encountered an error in the console: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This ...

Limit Content to be contained within a Bootstrap Container/Div

How can I shrink the content inside a container without distorting images? When the screen size decreases, all the images and content inside start to lose their alignment and sizes begin to change. I am aware that this may make the content harder to see. ...

What is the equivalent function for jQT.goTo?

I need help transitioning a jqtouch app to jquery mobile. I am unsure about the proper way to convert this code. showMainMenu: function() { Inventory.loadDealers(); Inventory.enableMenu(false); jQT.goTo('#mainmenu'); ...

Utilize the Masonry layout script on dynamically generated elements from AJAX requests

I have been implementing a Masonry script with the following code: var $container = $('.grid'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector : '.grid-item', columnWidth : '.grid-sizer', ...

Angular application making a $http.post request to change the date to a UTC date

I encountered an issue while trying to send data to my REST api that includes a date parameter. During debugging, I noticed that my date parameter is a JS Date object with the correct date in my timezone: Tue Apr 04 2017 00:00:00 GMT+0530 However, once it ...

Guide on transferring Javascript array to PHP script via AJAX?

I need to send a JavaScript array to a PHP file using an AJAX call. Here is the JavaScript array I am working with: var myArray = new Array("Saab","Volvo","BMW"); This JavaScript code will pass the array to the PHP file through an AJAX request and displ ...

Escaping JSON in HTML syntax

Can JSON be safely included in an HTML tag? The only allowed characters for the JSON input are "':{},[a-z][0-9]. Is there a risk of breaking JSON or HTML with this approach? What precautions should be taken when using JSON in both HTML and JavaScript? ...

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Add some pizzazz to your design using jQuery!

I have been working on a web application using asp.net c#. I have a div element where I applied the following style to it at the server side: spanNivelRiesgo1.Attributes.Add("style", "display:none; visibility:hidden"); Now, I have a radiobutton list and ...

Unselecting an "all selected" checkbox

I need help with my checkbox functionality. Currently, I have a checkbox that selects all options when clicked, but if one option is deselected, the "Select All" option remains checked. Any guidance on how to address this issue would be greatly appreciated ...

Extract the ID from the array, save it, and then delete it from the local storage

I am currently developing a mobile application using Angular, JavaScript, Ionic, and Cordova. Within one of my functions, I make use of an array called existingEntries, which is stored as a variable. categories: Array [276] [0...99] 0: Object id ...

Develop a pair of jQuery plugins that are able to communicate with one another

My mind is currently in disarray. I am interested in developing two unique jQuery plugins: A tab plugin A slider plugin. These plugins need to be able to communicate with each other. For example, clicking on a tab should activate the corresponding index ...

Custom filtering in jqGrid with an integrated filtering toolbar

Hey there! I'm currently using the latest version of jqGrid and I was curious if it's possible to implement local filtering with custom rules. In the past, I had to manually add this feature because the version I was using didn't support it. ...

SVG Filter: The image is not completely covered by a width and height of 100%

Here's a basic SVG Filter. Click the example below to toggle the appearance of the filter: var image = document.querySelector('image'); var url = 'https://i.picsum.photos/id/202/2 ...