Alter the color of a link upon clicking with Jquery

I have written this code in HTML/CSS and jQuery:

$('.myFilters li').click(function() {
    $(".category").hide();
    var v = $(this).text()[0];
    $('.title li').hide().filter(function() {
        return $(this).text().toUpperCase()[0] == v;
        $(".category:first").show();
    }).show().first().find('a[data-toggle]:first').trigger('click');
})

$("a[data-toggle]").on("click", function(e) {
    e.preventDefault(); // prevent navigating
    var selector = $(this).data("toggle"); // get corresponding element
    $(".category").hide();
    $(selector).show();
});


$('.myFilters li:first').trigger('click');
The CSS snippet:
.myFilters,
.title {
margin: 0;
padding: 0;
}

/* more CSS styles here */

The JavaScript provided:
  • A
  • B
  • C
When a letter is clicked, the corresponding categories and companies are displayed. I am looking to change the color of the clicked letter and background of the category when clicked. Thank you for any assistance!

Answer №1

For a solution, check out this code snippet

$('.myFilters li').click(function() {
    $('.myFilters li').find('a').removeClass('red');
    $(this).find('a').addClass('red');
    $(".category").hide();
    var letter = $(this).text()[0]
    $('.title li').hide().filter(function() {
        return $(this).text().toUpperCase()[0] == letter;
        $(".category:first").show();
    }).show().first().find('a[data-toggle]:first').trigger('click');
})

$("a[data-toggle]").on("click", function(e) {
    e.preventDefault(); // prevent navigating
    var selector = $(this).data("toggle"); // get corresponding element
    $(".category").hide();
    $(selector).show();
});


$('.myFilters li:first').trigger('click');
//$('.title li:first a[data-toggle]').trigger('click');

Answer №2

Have you considered trying something similar to this code snippet? http://jsfiddle.net/wdg9khL5/ ?

$('.myFilters li').click(function() {
  $(".category").hide();
  var v = $(this).text()[0];
  var c = $(this).data("color");
  $('.myFilters li a').css("color", "black");
  $("a", this).css("color", c);
  $('.title li').hide().filter(function() {
      return $(this).text().toUpperCase()[0] == v;
      $(".category:first").show();
  }).show().first().find('a[data-toggle]:first').trigger('click');
})

$("a[data-toggle]").on("click", function(e) {
  e.preventDefault(); // prevent navigating
  var selector = $(this).data("toggle"); // get corresponding element
  $(".category").hide();
  $(selector).show();
});


$('.myFilters li:first').trigger('click');

$('.filter > ul > li > a').on("click", function(e){
   // Reset all link colors
   $('.filter > ul > li > a').css("color", 'red');
   $('.filter > ul > li').css("border", '1px solid red');

   $(this).css("color", 'green');
   $(this).parent('li').css("border", '1px solid green');
});

Answer №3

If you want to add a custom attribute called data-color, you can follow these steps:

When a user clicks on an element with the class "myFilters li", prevent the default action and do the following:
    //...
    Get the value of the data attribute "color" from the clicked element
    Change the color of the anchor tag inside the clicked element to the specified color
});

Check out this example on Fiddle

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

create undirected lists using an array

I am trying to convert an array of sentences into unordered HTML lists, with each list item containing a word from the sentence. For example: [I play piano the can'] t <ul> <li id = number</li> <li>I</li> <li>play< ...

Establishing the rotation attribute of an SVG circle to create an angular progress tracker

Exploring the code of an Angular component and came across how the r attribute for an svg circle is defined like this: [attr.r]="radius - stroke / 2" This seems to work, but I'm wondering why it's done this way. Isn't the r attribute suppo ...

J-Query J-Player does not autoplay

On my music site, I have integrated jPlayer for playing songs. The songs data is dynamic and added as users select from a list of 10 songs on each page. Although jPlayer adds the songs to the playlist, it does not autoplay. I have tried using playItem=0, p ...

The dropdown feature in the pug navigation bar is malfunctioning

The navigation bar at the top of the page is not functioning properly when attempting to access the drop-down menu items (Items, Brands, or Categories). The drop-down options fail to open on click. Screenshot of Navigation Bar Pug file: doctype html html ...

Incorporate a lesson featuring jQuery into your curriculum

Just starting out with jQuery and I have a form setup like this: <select name= "menus"> <option value="">--Select--</option> <option value="a">a</option> <option value="b">b</option> <option val ...

Trouble with fetching data from external API due to cross-origin restrictions

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ $.get({ url: "http://www.dnd5eapi.co/api/races/", data ...

Updating the data when session begins

I am having an issue with two PHP files (index.php & data.php). The first file sends data to the second file, which runs every second to display the data. However, the problem is that the data is not updating. Perhaps looking at the code will provide a be ...

When attempting to delete a resource using an HTTP request in Insomnia, I encountered a TypeError stating that it was unable to read the property 'id'

I recently started using Express and am in the process of setting up the Delete function for my database within the MERN stack. While testing my CRUD operations using Insomnia, I have encountered an issue specifically with the Delete operation. The proble ...

Effective methods for increasing the height of a column div upon hovering, while also maintaining the position of surrounding columns

Struggling to make this work for 48 hours with no success. Here's the challenge: there is a standard row with regular columns that have an additional product class: <div class="row"> <div class="col-lg-4 product"> // Content ...

Is there a tool available for viewing the HTML5 Web SQL database?

Is there a tool available, such as PHPMyAdmin, that allows users to easily view HTML5 Web SQL databases from their web browser? ...

Unable to include property in Mongoose find query object

After retrieving an object from the MongoDB database, I want to include an additional property before sending it as a response to the frontend using Express. obj = collection.find({}); obj[0].extra_property = "value"; res.send(obj); I am aware t ...

Having trouble showcasing two unordered lists side by side on a single line

In my Magento Go store, I am showcasing products using CSS only. Currently, the loop is set to display 5 products in a row and then close the <ul> tag. However, if there are more products, a new <ul> element is created. My fixed width only allo ...

Adjusting jQuery tab content heights to maintain consistent height across tabs and prevent varying heights

I am currently working on a tabbed view that is very similar to the demo found at the following link: http://jsfiddle.net/syahrasi/us8uc/ $(document).ready(function() { $(".tabs-menu a").click(function(event) { event.preventDefault(); $(this).pare ...

Error message: "PHP Object Oriented Programming: jQuery AJAX - Index Not

How can I resolve the undefined index error? Below is my code: On the Products Class: public function add(){ var_dump($_POST); $pname = $_POST['pname']; echo $pname; } AJAX code: $('#productsform').on('submit', ...

How do I resolve the problem of Bootstrap column heights? Setting columns to have an automatic height in Bootstrap grid

Currently working on a website and encountering an issue that needs to be resolved. I have included some reference photos below to illustrate the problem: We are getting this We want this. Thank you in advance for your help. When attempting to set the h ...

The functionality of checking all checkboxes is not functioning properly within a custom function

function toggleTreeView(id) { $("#TreeUL" + id).slideToggle(function() { if ($(this).is(':hidden')) { $("#treeCollapse" + id).addClass("glyphicon-plus"); $("#treeCollapse" + id).removeClass("glyphicon-minus"); } else { ...

Sort the data in Angular JS by one key, but ensure that results with another key set to 0 remain at the end

Here is an array of objects containing information about various car brands: $scope.cars = [ {"brand":"McLaren","price":70,"stock":0}, {"brand":"Renault","price":10,"stock":0}, {"brand":"Ferrari","price":100,"stock":3}, {"brand":"Lamborghini","pri ...

Implement a maximum height restriction on the children of the Select component in Material-UI

Currently, I am working with the Material-UI react library to create Dropdown menus by utilizing components like <FormControl>, <Select>, and <MenuItem>. The options array for these dropdown menus is quite extensive, and I am looking to s ...

Having trouble installing node-sass through npm

Currently, I am attempting to install the SASS compiler node-sass in order to compile SCSS code into CSS code. Despite following an online tutorial and replicating the same steps, I keep encountering errors. npm init --yes : this will generate a json file ...

Incorporating numerous CSS components into a data-bind using Knockout

I have a situation where I need to apply multiple css classes to a div using knockout. Here is the initial div: <div data-bind="css: {'case-header': model.caseHeader1, 'case-type-1': model.caseHeader2, 'case-type-2&apo ...