Don't forget the last click you made

Looking for a way to style a link differently after it has been clicked and the user navigates away from the page? Check out this code snippet I've been using:

$(document).ready(function(){
var url = document.URL;
function contains(search, find) {
    return search.indexOf(find) !== -1;
};
$('#topbar a').each(function(){
    var link = $(this).attr('href');
    var answer = contains(link,url);
    if(answer === true){
        $(this).addClass('check');
    }
    else{
        $(this).addClass('nocheck');
    };
});
});

This code effectively styles links in the navigation bar based on their current viewing status. However, one challenge arises when dealing with a specific case: Random.

In instances where a link leads to a randomly generated page without a set URL (due to a function that generates pages), how can you detect if the random link was previously clicked to apply the .check class?

Answer №1

If I understand correctly, the issue with your function lies in its handling of the random link. This link has an href value like http://mysite.com/random, but when clicked, the server redirects you to a different page, such as http://mysite.com/about-me. As a result, the active page's URL does not match the href of the random button, causing it to not receive the active state.

One could question whether the random button should even receive the active state since clicking it again may not take you to the same page. Nevertheless, let’s address how this can be resolved.

I see two possible solutions:

Server-Side Solution:
Instead of redirecting directly to http://mysite.com/about-me, consider redirecting to

http://mysite.com/about-me?random
. By adding this query parameter, the link’s behavior should remain unaffected (unless there are strict controllers or if that variable is utilized). With JavaScript, you can detect the presence of this variable in the URL and activate the random button accordingly.

Here’s an example implementation:

$(document).ready(function(){
  var url = document.URL;
  // Check for 'random' in URL
  if (url.indexOf('?random') >= 0) {
     $('#topbar a.random').addClass('active');
  }
  // Check all other links
  $('#topbar a:not(.random)').each(function(){
      if($(this).attr('href').indexOf(url) >= 0){
         $(this).addClass('active');
      }
      else{
         $(this).addClass('inactive');
      };
  });
});

Cookies Solution:
If server-side changes are not feasible, you can achieve this entirely through JavaScript using cookies. Upon clicking the random button, set a ‘random’ cookie to true before proceeding with the link action. When the page loads, check if this cookie is set to true – if so, deactivate it and mark the random button as active.

While using cookies is not always recommended (as they are sent with every page request, potentially raising privacy concerns), it could be a viable last resort option. If you prefer this approach and need further assistance, feel free to ask for help.

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

jquery is not providing any text content from the body

My current setup involves an ajax post that sends a website address to PHP for retrieval, and then I want jQuery to locate specific elements within the site and retrieve the text from those elements. While this method works fine for certain elements like h ...

Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve thi ...

The issue with updating values in the jQuery UI datepicker persists

When using the jquery datepicker ui, you may notice that the value attributes of the associated html fields do not update immediately. For example: http://jsfiddle.net/4tXP4/ Check out this link for more details: http://jqueryui.com/demos/datepicker/al ...

Incorporate an image into your webpage with the Fetch API by specifying the image link - JavaScript

I've been attempting to retrieve an image using the imageLink provided by the backend server. fetchImage(imageLink) { let result; const url = `https://company.com/internal/document/download?ID=${imageLink}`; const proxyurl = 'https:/ ...

Using the spread syntax to eliminate a property from an object within a ReactJs element

I'm trying to figure out if it's possible to remove a specific object property using spread syntax when rendering a React component. I want to achieve this without adding too much extra code. Currently, I am utilizing {reset,...inputName} In my ...

Code remaining stable post-execution of promise

I'm facing a problem with my Node.js application where I'm using promise-mysql and bluebird packages to make calls to a MySQL database. Despite following tutorials and successfully querying the database, I keep encountering a timeout error. The p ...

The start screen fails to display when clicking the restart button

I am struggling to get the restart button to display the start screen again. Even though I have called the restart function within the clearColors function, which should show the start screen, it hasn't been effective so far. Initially, in the fadeOut ...

What is the best method for overlaying text on individual images in a slideshow?

Currently, I am delving into the world of jQuery, experimenting with various slideshows and attempting to incorporate text and effects. In my endeavors, I stumbled upon this codepen that served as an excellent template. However, when I tried adding text o ...

Remove the div of the previous selection in jQuery and add the current selection by appending it, ensuring only one selection per row is allowed when

Here is a code snippet that includes buttons appending selections to the "cart" div upon clicking. The first script ensures only one selection per row when multiple buttons in the same row are clicked. In the second script, selections are appended to the ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

Is there a way to combine multiple array objects by comparing just one distinct element?

Is there a way to combine these two arrays into one? array1 = [ { image: 'image1', title: 'title1' }, { image: 'image2', title: 'title2' }, { image: 'image3', title: 'title3' }, ]; array2 = ...

Using Symfony2 to interact with ajax and display data

One of my goals is to use jQuery to display data when a link is clicked. I have the code ready, but it needs some additional jQuery for data retrieval and Twig code to actually display the data. This is the Twig: <a href class="list">List</a> ...

Getting the values of several labels using a class name - a comprehensive guide

Is there a way to retrieve the values of labels with the "timeAuction" class? I'm currently working on a JavaScript function that will target each label with the class name timeAuction and adjust its value. The number of labels with this class can va ...

Steps to obtain an Element binding from a Svelte component

Is it possible to retrieve the bounding client rect of an anchor element? I typically mark this using the syntax bind:this={someVariable}. However, when I add this code to a Svelte component, I receive a different object that Svelte uses to represent a c ...

What is causing the UI to change every time I add a tag to refresh the web view?

Recently, I added a pull-to-refresh feature to my React Native webview app using the react-native-pull-to-refresh library. After implementing the tag, I noticed that the UI got rearranged with the webview shifted down and the top half occupied by the pull- ...

Disable Button's Shadow when it is in an active state (clicked)

Check out the DEMO to see the button animation CSS in action. The CSS code for the button animations is as follows: .btnliner { /* CSS properties */ } /* More CSS properties */ .btnliner:hover { /* Hover effects */ } Here is the corresponding J ...

What is the best way to handle AJAX responses in an onchange event

I'm working on a form where the select option in the input (jurusan) is automatically filled based on the selected value. I need to know how to change the value that appears after selecting an option. For example, if I select option A, it displays th ...

The navigation is designed to only show up as I scroll down the page, but ideally it should be visible

I am trying to make the navigation bar appear on page load instead of when I scroll down the page. Currently, I am using this jQuery code: <script type="text/javascript> $(document).scroll(function() { if ($(this).scrollTop() == 20) { ...

Storing filtered data objects for future use

Introduction to my User Administration Page Currently, I am working on the User Administration page of my project and facing a minor issue. The page includes a table that displays material-ui's Usercard for each user in the system. These cards are ge ...

Discovering a way to showcase every event a user is linked to, employing Fullcalendar Rails

Here is the current model structure: class User < ActiveRecord::Base has_and_belongs_to_many :event_series has_many :events, through: :event_series end class Event < ActiveRecord::Base belongs_to :event_series end class EventSeries < Activ ...