Set the first link in a menu to be highlighted as active using jquery

In order to mark the first link in my menu as active, I need it to have specific CSS settings applied. Using jQuery to add these settings to every link when clicked on makes it a bit tricky (simple menu = clicking changes color). So, I want the first link initially marked in CSS (as shown in the code...) and when another menu link is clicked, the first link should return to normal CSS settings. Below is my code, open to any suggestions.

EDIT: By the way, the first link also has the attribute rel="sl1" ...if that information is helpful for the solution...

 $(document).ready(function()
                {

                    // The first link must be pre-marked upon page load
                    $('#menu-vertikal li:first-of-type').addClass('active-link');
                      $('#menu-vertikal li a').click(function () {
                      $('#menu-vertikal li.active-link').removeClass('active-link');
                      $('#menu-vertikal li').eq($(this).parent().index()).addClass('active-link');

                    }); 

                    // Code for toggling content

                    $('#menu-vertikal ul a').on('click', function(){
                           var target = $(this).attr('rel');
                           $("#"+target).show().siblings("div").hide();
                        });
                });

Answer №1

Implement a custom set of CSS styles for the active menu, then utilize jQuery's .addClass method to apply it.

$(document).ready(function() {

  $('li:first-of-type').addClass('current');
  $('li a').click(function() {
    $('li.current').removeClass('current');
    $('.content:visible').hide();
    $('.content').eq($(this).parent().index()).show();
    $('li').eq($(this).parent().index()).addClass('current');

  });

});
.current a {
  color: green;
}
.content {
  width: 100%;
  color: red;
  font-size: 36px;
  font-weight: bold;
  font-family: calibri;
  text-align: center;
}
.content:not(:first-of-type) {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Home</a>
  </li>
  <li><a href="#">About</a>
  </li>
  <li><a href="#">Contact</a>
  </li>
  <li><a href="#">Blog</a>
  </li>
</ul>

<div class="content">Content one</div>
<div class="content">Content two</div>
<div class="content">Content three</div>
<div class="content">Content four</div>

Note: It is recommended to use .addClass over inline CSS modifications like .css when dealing with multiple properties for better code organization.

Answer №2

If you want to customize the style of the first link in a vertical menu, consider using this snippet before the provided code:

$("#menu-vertikal ul:first-child a").css({
    // Add your specific CSS styles for the first link here
});

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

The href attributes are not being retrieving correctly

I'm currently working on extracting the URLs for each restaurant listed on this page and have developed a Python script for this purpose: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver ...

Utilize JavaScript declarations on dynamically added strings during Ajax loading

Is there a way to append HTML strings to the page while ensuring that JavaScript functions and definitions are applied correctly? I have encountered a confusing issue where I have multiple HTML elements that need to be interpreted by JavaScript. Take, for ...

Creating a dynamic 2x2 grid with centered responsiveness in Angular Ionic framework

I'm having trouble achieving a 2 x 2 grid that is centered on my screen. The code snippet below shows what I have so far in the HTML file. Just to provide some context, this project is meant for a native mobile application. <ion-header> <i ...

Extracting data from XML using my custom script

I attempted to extract a specific value from an XML feed, but encountered some difficulties. In addition to the existing functionality that is working fine, I want to retrieve the value of "StartTime" as well. Here is the relevant section of the XML: < ...

Error encountered during Nuxt build: Syntax error on Line 1 of the SCSS component file

I'm currently working on a project in node 18.7.0 that utilizes nuxt 2.15.8. Within my Vue component, I have the following SCSS code: <style lang="scss"> .Accordion { --Accordion__margin-top: 2.5rem; &__items { margin ...

What steps should I follow to make a sticker adhere to a div?

I'm currently in the process of designing a sticker that attaches to the top of a div, much like this: <div className="upgrade-premium"> <div className="upgrade-team"> <h1>Premium</h1> <p>100 ...

Instead of returning a single array of data from a form as expected, Jquery is returning two arrays

Having a bit of trouble with my code involving radio buttons and arrays using Jquery. I'm trying to record the selected values into one array, but it's creating separate arrays for each fieldset. Here's what I have: <script> $(doc ...

Content located on the right-hand side of the menu

I am currently working on a vertical navigation menu design, but I am facing some issues with aligning the text to start from the very left edge of the element. HTML <div class="jobs-links"> <ul> <li><a href="renovations. ...

Having trouble setting the focus on a text box following a custom popup

Presenting a stylish message box and attempting to focus on a textbox afterward, however, it's not functioning as expected. Below is the HTML code: <a class="fancyTrigger" href="#TheFancybox"></a> <hr> <div id="TheFancybox">& ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

Utilizing AngularJs to differentiate between arrays and strings within an HTML template

I'm currently facing a challenge with creating a dynamic HTML template. In order to present data in a table, I need to distinguish between a regular String and an Array. Firstly, the HTML template is embedded within another template using the data-ng- ...

In a Next JS project, the CSS Transition fails to activate when a class is dynamically added

In my Next.js project with Tailwind styling, I encountered an issue when using the globals.css file for more complex non-Tailwind CSS styling on a component. To better understand the problem, you can view the Code Sandbox here: https://codesandbox.io/p/sa ...

The equivalent of the $.curCSS method in jQuery version 1.10 is as follows:

While working with a library called mcdropdown from http://www.givainc.com/labs/, I encountered an issue with the $.curCSS method. The latest version of jQuery no longer supports this method and suggests using $().css instead. Following the documentation, ...

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...

Implementing script loading within the Angular scope

I'm attempting to load a custom script from the database based on client-side logic. I am having trouble figuring out how to make it function properly. Here is my controller code: 'use strict'; angular.module('youshareApp') . ...

Newbie Inquiry Renewed: What is the best way to convert this into a functional hyperlink that maintains the data received from the ID tag?

I have no prior training etc. If you are not willing to help, please refrain from responding as I am simply trying to learn here. <a id="player-web-Link">View in Depth Stats</a> This code snippet loads the following image: https://i.stack.i ...

The body can only stretch up to a certain percentage of its width, not a full 100%

Recently, I've been encountering an issue with my webpage where the body does not stretch 100% the width of the screen. I've tried numerous CSS rules to fix it, but nothing seems to be working. When you view the page in a browser, it appears to c ...

Ways to stop jQuery from stripping the <script> elements

Is there a way to stop jquery from removing my JS default behavior? function loadPageSuccess(data) { var data = $(data).find('#content'); alert($(data).html()); $("#content").html(data); $("#page").fadeTo(100,1); } function loadP ...

Rearrange the middle column to be the top column on smaller screens

I am trying to create a layout with 3 columns in a row. The challenge is to prioritize the middle column on top when viewed on small screens, with the left and right columns below it. To clarify, on large screens the order should be 1 2 3, while on small s ...

Aligning a div with absolute positioning vertically

There are two elements positioned side by side: an input field and a div. The div is absolutely positioned inside a relative element and placed to the right of the input. The input field has a fixed height, while the height of the div depends on its conte ...