Attempting to keep a:active state active until another link is clicked

My goal is to have two links, "hot" and "update." When "hot" is clicked, it should turn red and "update" should turn black. Conversely, when "update" is clicked, it should turn red and "hot" should turn black.

This functionality works perfectly on a Fiddle, but unfortunately not on my website.

I searched for solutions on Stack Overflow, as this seems like a common issue. I tried implementing various solutions one by one, but none of them seem to work. They all function correctly in the Fiddle but not on my actual website.

Here is the HTML code:

<div id="Space" >
  <ul>
    <li role="presentation" class="sort">
      <a class="link" href="/?sort=score&page=1" style="text-decoration:none;">hot</a>
    </li>    
    <li role="presentation" class="date">
      <a class="link" href="/?sort=date&page=1" style="text-decoration:none;">update</a>
    </li>
  </ul>
</div>

JavaScript:

$(function() {
  var links = $('a.link').click(function() {
    links.removeClass('active');
    $(this).addClass('active');
  });
});

CSS:

a.link.active { color: red; }
a, a:visited { color: black }

Currently, the links do behave like a:active, where they briefly turn red when clicked, but then return to black. The desired behavior is for the clicked link to stay red until the other link is clicked.

Answer №1

When using <code>var links =, it may not function as expected.

One might assume it does this:

var links = $('a.link');

However, since it's being assigned to the actual click event, it doesn't work with that selector.

To correct the code, consider the following:

// A more secure document ready method to avoid clashes with other $ libraries
jQuery(function($) {
  $('a.link').click(function() {
    // Remove the class from all other links
    $('a.link').removeClass('active');
    // Add the class only to this link
    $(this).addClass('active');
  });
});

Alternatively, here is a version that maintains the var links:

// A more secure document ready method to avoid conflicts with other $ libraries
jQuery(function($) {
  var links = $('a.link');
  links.click(function() {
    // Remove the class from all other links
    links.removeClass('active');
    // Add the class only to this link
    $(this).addClass('active');
  });
});

You can view a working fiddle here: https://jsfiddle.net/cale_b/tqzt8f7s/1/

Answer №2

If you're looking to emphasize specific buttons based on the presence of certain queries in the URL, here's a solution for you. Highlight the "sort" button if the URL includes /?sort=score&page=1, and highlight the "date" button if the URL contains /?sort=date&page=1.

To achieve this, simply search for these strings within the (window.location.search) of your page. You can use the following code snippet:

const highlightType = (window.location.search).search('sort=score') !== -1 ? 'Highlight sort' :
    (window.location.search).search('sort=date') !== -1 ? 'Highlight date' :
    'Highlight Nothing';

You can then use this flag as a reference to stylize either one of your 'a' tags accordingly.

I trust that this explanation has been beneficial for you! (:

Answer №3

Give this javascript a shot

$(function() {
   $('a.link').click(function(e) {
            e.preventDefault();
       $('a.link').toggleClass('active');
   });
});

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

Ways to retrieve anchor tag values from an AJAX response without a defined class

if(ajaxRequest.readyState == 4) { var response = ajaxRequest.responseText; response=response.split('^^--^^'); var buname=response[5].split('^^|||^^'); //rest code } The AJAX request has returned the following code, now stored in the va ...

How come the parameters in my function are being displayed as boolean values in JSDocs when that is not the intended behavior?

I am documenting my journey of following the React tutorial for tic-tac-toe, and I'm puzzled as to why the parameters of my function are showing up as boolean values in JSDocs when they are not supposed to. When I hover over the function with my curs ...

Determine in AngularJS whether there is a checked checkbox in a table row

Here is my HTML code snippet: <tbody ng-repeat="notification in notifications"> <tr> <td rowspan="{{notification.specs.length+1}}">{{notification.notification_id}}</td> </tr> <tr ng-repeat="position in ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

Elastic_Frame | "Error: Unable to process action as property 'toLowerCase' is not defined"

Attempting to create a personal and project portfolio using Vu Khanh Truong's "elastic_grid" jQuery plugin for the actual portfolio. You can access it here. However, encountering some issues on my page: 1) The header for the portfolio section disappe ...

Changing font color of a selected item in Material-UI's textview

I have a select textview in my react app and I am wondering how to change the font color after selecting an item from this textview. <div> <TextField id="standard-select-currency" select fullWidth l ...

What is the best way to implement collision detection using raycasting?

For my university project, I am looking to implement collision similar to what is shown in this example. However, I am facing an issue where collision is only working on the top of the object. I referred to this for guidance. My goal is to add collision to ...

I am attempting to use $.map to transfer values into a new array, but unfortunately, it is not producing the desired result

This task seems easy at first glance, but unfortunately it's not working for me. Can someone please point out what I might be doing wrong? var oldArr = [0, 1, 2]; var newArr = []; /* * This function is supposed to add 1 to each element in the array ...

Troubleshooting the issue of "Mismatched transaction number*" in MongoDB and Node.js

While trying to add data, I encountered an issue with modifying two schemas using ACID transactions in MongoDB with Node.js. Upon running the program, an error was displayed: (node:171072) UnhandledPromiseRejectionWarning: MongoError: Given transaction n ...

Utilizing Vue components within SweetAlert2 content

I have a couple of basic Sweetalert2 pop-up modals within a Vue project. My goal is to incorporate a custom component into one of the alerts. For instance: <template> <h1>Greetings {{name}}</h1> </template> <script> module. ...

Choose and display a specific set of data from a JSON array

On this particular link, there is an array containing 100 sets of values. I have exhausted my brain trying to figure out how to access and display the "percent_change_24h" value for only the first 0..10 sets in order to calculate the average. <script&g ...

Utilizing inline JavaScript to automatically refresh a webpage at specified intervals and monitor for updates within a specific div element

I am currently working on creating an inline script that will automatically refresh a webpage at regular intervals and check for changes in a specific element. If the element meets certain criteria, then the script should proceed to click on a designated b ...

Adjust the URL in real-time within an AJAX JSON request

Hey there, I'm fairly new to javascript and ajax. I've been trying to figure this out on my own, but I can't seem to find all the information I need. Currently, I'm making a call to a PHP page using json, and I'd like to be able t ...

Oops! Looks like we have encountered an issue with reading the property 'checked' of nothing

Whenever I click the checkbox, an image should be displayed. Unfortunately, I encountered an error: Uncaught TypeError: Cannot read property 'checked' of null at (index):185 at dispatch (VM576 jquery.min.js:3) at i (VM5 ...

Create a layered panel underneath a button that covers a separate element

I am working on a layout that consists of an editor and multiple buttons positioned above it on the right side. My goal is to add a panel just below "Button2" that will overlay the editor. This panel should expand and collapse when "Button2" is clicked, wh ...

Move the item using drag and drop functionality into one of the dialog boxes

I am working on a project where I have story points represented as simple lines of statements. My goal is to be able to drag these lines into a dialog box that opens after clicking a specific button. As shown on the screen, I am looking to drag my storie ...

Attempting to create a dynamic effect with a div element, where a randomly generated string shifts to the left and new characters are continuously added at the end, resembling a scrolling motion

I recently delved into learning javascript, html, and css on Codepen. I've been working on creating a matrix code rain effect over the past few days. While I do have some experience with other programming languages, I encountered an issue when trying ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...

Verify whether an item is present in a jquery assembly

When initializing a jQuery collection, I start by doing $collection = $([]) As events unfold later on, I find myself frequently using $collection = $collection.add($element) This approach allows me to easily call functions like $collection.hide() on al ...

Adjust the input values based on the child elements within the main container

Here is a series of DIVs with unique IDs: <div id="2988"> <div class="site">YaHoot.com</div> <div class="logo">/images/yahootLogo.jpg</div> //[and so on] <input type="button" value="YaHoot" onclick="javascript: ...