Guide to altering the color of an href element when clicked using Jquery

I am looking to modify the color of the selected language when clicked. See my code snippet below:

$(document).ready(function(){
    $("a[href*='lang']").click(function(e) {
        e.preventDefault();
        $('#header-top a').removeClass('active');
        $(this).addClass('active');
    }); 
});

JSP code:

<div id="header-top">
    <a href="/eidsar" title="Logo"> 
        <img class="logo" src="/eidsar/images/MobistarLogo.jpg" />
    </a>
    <ul class="lang-nav">
        <li><a class="active" href="?lang=en" title="en">EN</a></li>
        <li><a href="?lang=fr" title="fr">FR</a></li>
        <li><a href="?lang=nl" title="nl">NL</a></li>
    </ul>
</div>

CSS:

.lang-nav {
    padding: 0;
    list-style: none;
    margin-left: 1100px;
    line-height: 42px;
}

.lang-nav li {
    display: inline;
    margin: 0 5px;
}

.lang-nav li a {
    color: #999999;
    text-decoration: none;
}

.lang-nav li a:hover {
    color: #fff
}

.active {
    color: #fff;
}

However, using e.preventDefault(); prevents me from navigating to the ?lang=en link. How can I resolve this issue? Any suggestions are welcome.

I attempted to address this in the onload function:

<script>
function checkUrl(){
     var title = document.getElementById("nl").title;
     alert(title);
       if(title == "en"){
         document.getElementById("en").href = '?lang=en';
         document.getElementById("en").style.color = 'red';
         document.getElementById("fr").style.color = 'blue';
         document.getElementById("nl").style.color = 'green';
     }
        if(title == "fr"){
             document.getElementById("en").style.color = '#999999';
             document.getElementById("fr").style.color = 'red';
             document.getElementById("nl").style.color = '#999999';
             document.getElementById("fr").href = '?lang=fr';
         } if(title == "nl"){
             document.getElementById("en").style.color = '#999999';
             document.getElementById("fr").style.color = '#999999';
             document.getElementById("nl").style.color = 'red';
             document.getElementById("nl").href = '?lang=nl';
         }   
}
</script>
</head>
<body onload="checkUrl()" >
    <div>
        <div id="header-top">
            <a href="/eidsar" title="Logo"> <img class="logo"
                src="/eidsar/images/MobistarLogo.jpg" />
            </a>
            <ul class="lang-nav">
                <li><a id="en" href="?lang=en" title="en">EN</a></li>
                <li><a id="fr" href="?lang=fr" title="fr">FR</a></li>
                <li><a id="nl" href="?lang=nl" title="nl">NL</a></li>
            </ul>
        </div>
        <div id="header-bottom">
            <div style="visibility: hidden" id="header-content">
                <ul class="head-nav"></ul>
            </div>
        </div>
    </div>  

The challenge now is how to pass the ids in the onload function???

Answer №1

To change the color of a href after it has been clicked, you can achieve this without using JQuery. Here are some CSS tags to try out:

/* unvisited link */
a:link {
    color: #FF0000;
}

/* visited link */
a:visited {
    color: #00FF00;
}

/* mouse over link */
a:hover {
    color: #FF00FF;
}

/* selected link */
a:active {
    color: #0000FF;
}

Note: It is important that a:hover comes after a:link and a:visited in the CSS definition for it to work correctly! Also, a:active should come after a:hover for it to be effective. Remember, pseudo-class names are not case-sensitive.

Visit this link for more information on CSS Pseudo Classes

Answer №2

It appears that you are utilizing individual pages for each language. In this scenario, you can maintain the already colored link based on the specific language of the page. You can achieve this by using a class similar to the following:


.header-top a.inuse { color: #999999;}
and applying the 'inuse' class solely to anchor tags specific to that particular page in order to highlight only that link within that context.

Answer №3

The main issue at hand is that upon exiting the page, everything gets wiped out. To address this, you should check for matching URLs and set the appropriate class/color when the page loads, instead of relying on onclick actions which are redundant in this scenario where page navigation is essential.

In most cases, developers assign a class to a link using server-side code, leaving JavaScript unconcerned with it.

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

Determining age in a Class upon instance creation

Is there a way to encapsulate the age calculation function within the Member Class without resorting to global space? I want to automatically calculate and set an age when creating an instance. Currently, I have a function that works, but I'm curious ...

The behavior of React Native margin is applied internally within the object, rather than externally

Visit the link and then open the file login_screen/components/Form.js. Within this file, you will notice that the textInput is styled as follows: textInput: { flex:1, height: 50, marginBottom: 20 } If you observe closely, you'll see ...

Step by step guide on integrating current locations in Leaflet OpenStreetMap within an Angular application

I am currently working on an Angular application that incorporates a map using Leaflet OpenStreetMap. I want to display the real-time latitude and longitude for the map, which should update based on the location. Can someone advise me on how to add the cur ...

Replicating the existing div content into a textarea

I wanted to create a tool for my workplace as a learning project in html, CSS and JS. It's a timer that tracks how long I spend on tasks. Currently, I have the timer resetting itself but I'm facing an issue where the paused time is not being log ...

Display a progress bar in Bootstrap with a labeled indicator positioned above the bar and background to the

Is there a way to create a progress bar with a label positioned to the right using Bootstrap v5.2 Progress Bar? https://i.sstatic.net/gOWie.png I attempted to use negative margins to achieve this layout but faced issues when the label expanded due to lon ...

Order of setTimeout calls in React's execution sequence

I am currently trying to wrap my head around the functionality of this React component (which is designed to delay the rendering of its children): function Delayed({ children, wait = 500 }) { const [show, setShow] = React.useState(false); React.useEff ...

What is the solution for fixing the '$ not defined error' in a .js file with $ajax code?

var example = document.createElement("SCRIPT"); example.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"; var nodeScript= document.createTextNode("function test() {console.log('test message');$.ajax({ type: \"POST&bs ...

Creating an ASP.NET MVC application, the index table seems to extend beyond the confines of the page

Embarking on the journey of creating my first web app after years of mastering C# Windows Forms development in .NET has been a thrilling adventure. Following the guidance of the NerdDinner tutorial, I've tweaked certain components to align with my pro ...

React "react-transition-group" is malfunctioning

I am currently in the process of updating my project to the latest version of React and I have noticed that ReactCSSTransitionGroup is now considered deprecated. As recommended by React developers, I have switched to using the suggested package. Previously ...

The issue of blank spaces appearing in Outlook 2007 within conditional comments

Having been immersed in the world of coding HTML emails for several years, I've encountered numerous conditional comment-based 'bulletproof buttons' available online. While most of them do the job just fine, I've hit a roadblock with Ou ...

Problem with accessing state in React 16

In my code snippet below, I am encountering an issue. When the button is clicked and 'streaming' appears on the UI, the console.log within the 'process' function displays false. Can you help me identify what might be causing this discre ...

When using jQuery AJAX to Like/Dislike, a 500 (Internal Server Error) is returned, but the functionality works correctly upon reloading the

My website has a feature where users can press a Like Status button that uses AJAX to send data to the controller. When the button is clicked, it changes from "like" to "dislike" and all associated classes and form actions are updated accordingly. The is ...

While JSON Lint may declare the JSON data as valid, JSON.parse may still encounter an error when trying

I'm struggling to parse a simple JSON object. It's strange because when I check the validity of my JSON string on JSONLint (http://jsonlint.com/), it shows that it's valid. var data = '{"token":"9eebcdc435686459c0e0faac854997f3","email ...

Can someone explain why my Laravel route is consistently showing a 404 error?

Currently, I am attempting to perform an AJAX request for a form post type. However, the PHP parse script I am trying to send the data to is returning a 404 error as observed through Chrome developer tools. Below is the code snippet: <script type="text ...

Updating div content dynamically with Jquery and PHP variable

How can I continuously update a div with the current date and time using PHP variable and Jquery? Here is my PHP file containing the variable date: <?php $date = date('d/m/Y H:i:s'); ?> And here's the code in my HTML file: <!DOCT ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

Error: $e.data() is incompatible with yii.confirm box

After upgrading to yii 2 stable, the code I used for the confirm box is no longer working. The error message I am now encountering is: "$e.data() is not a function." Upon further investigation, it seems that the type of $e is a function. yii.allowAction ...

Filtering the values of an array nested within objects

Imagine having a vast database of 10,000 cards and attempting to filter them based on the banlist_info.ban_ocg === "Forbidden" { id: 15341821, name: 'Dandylion', type: 'Effect Monster', desc: 'If this card is sen ...

Extracting a text value from a div using jQuery instead of displaying it in an alert modal

Can someone help me figure out a simple way to display text in a div that indicates what has changed compared to an alert modal with the following code? I'm struggling to understand it. Thanks... $(function(){ var abc = $('selec ...

Can you please explain how to switch the focused slide by clicking on a specific slide in swiper.js?

When using swiper in centeredSlides mode with the loop option set to true, I want a clicked slide to become the centered slide in the swiper carousel. Swiper provides me with the index of the clicked slide, but how can I use it to change the centered slide ...