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

Textbox value disappears after being updated

When I click on the edit link (name), the value from the database is displayed as a textbox. However, when I update another normal textbox (age), the value in the edit link textbox disappears. Strangely, if I input a new value into the edit link textbox, i ...

Is there a way to create a flexbox that combines a centered fixed child with a fixed child at the bottom?

I'm trying to create a layout using flexbox that looks like this: | | | | | CENTER FIXED ELEMENT | | | | BOTTOM FIXED ELEMENT | Here is the flexbox CSS I've attempted: .wrapper{ ...

Is it possible to utilize window.location.replace function within an iframe?

Is it possible to use window.location.replace to bypass history and target on-page anchors without page reloads, but encounter issues when working within iframes? The main problem seems to be a CSP (content security policy) violation for script-src ' ...

How to handle an undefined value in a jQuery ajax call when utilizing promises

I've been struggling with the issue of jQuery ajax calls returning values before they've been updated. Despite trying numerous solutions found through Google searches, none seem to work for me. The problem lies in getting an undefined value becau ...

The Problem with AJAX Error Handling Customization

Upon loading my webpage using Code Igniter and PHP, the JSON encoded query is returned successfully with data. I have managed to handle the scenario where no records are found by encoding a response in JSON format. However, I am unsure of how to transmit t ...

The unresponsive sticky navigation bar on a Joomla website is causing issues

I recently launched a new website that can be found here. The site includes the following JavaScript code: $(document).ready(function(){ $(window).bind('scroll', function() { var navHeight = $( window ).height() - 70; ...

Retrieving JQuery Results Based on List Items

Once I have obtained the list id from the navigation, my next step is to send the id to a PHP file that will return a JSON list. Below is the jQuery syntax I am using: $("#ul_navigation li").click(function(e) { idsec = this.id; alert(idse ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

Is it possible to personalize a select button for both iOS and Android mobile platforms?

I've implemented a dropdown on my website for the desktop version and it works fine. However, I want to replace this dropdown with a select button on iPad and iPhone, as I prefer how it looks on those devices. Is it possible to style the select butto ...

What causes the form to be submitted when the text input is changed?

I'm puzzled by the behavior of this code snippet that triggers form submission when the input value changes: <form> <input type="text" onchange="submit();"> </form> Typically, I would expect something along t ...

What is the best way to create a scrollable Material UI modal and dialog?

Having a problem with my mui modal where the top content is getting cut off and I can't scroll up. I've tried adding the {overflow:"scroll"} property to the modal but it's not working. Here's the code snippet I'm currentl ...

Issue with Jquery .on() causing toggleClass function to not trigger

Adding a column dynamically to a table on click with JS/Jquery is achieved as demonstrated below $("#btn").click(function(){ $('#week_title').append('<th>Week '+count+'</th>'); count++; $('.tag&ap ...

Significant performance disparity observed between Datatables in Internet Explorer compared to Chrome

I am facing a performance issue with a datatable that takes 4 seconds to render in Internet Explorer, while it loads quickly in Chrome. The ajax response from the server only takes less than 0.5 seconds to reach the client and it returns just 21 rows. I&ap ...

My JavaScript/Jquery functions are not running as expected

I need some help creating a simple image rotation feature. I have a folder named comics where the images are stored locally with names like comic_(number). However, when I click my buttons, nothing happens. The previous button doesn't even get disable ...

Tips for aligning the box beside another

How can I arrange 2 boxes in one line and the other 2 in the next line? Currently, they are all showing up on separate lines. Can anyone provide a solution to this issue? body{ background:#f4f4f4; color:#555; font-family:Bahnschrift SemiCond ...

Issue with parsley customized error message functionality not functioning as expected

I'm currently dealing with an issue related to the input field below: <input id="name" name="real_name" type="text" placeholder="ie. Your full name or company name" class="form-control input-lg parsley-validated" data-required="true" parsley-er ...

Looking for the top jQuery plugin for creating rounded corners on both divs and tables?

After experimenting with five different plugins, each with its own limitations, I'm still struggling to find one that meets my requirements. Specifically, I need a plugin that can round the corners of a div with a specified height, even if it has no c ...

CSS for a Div with a Subtle Curve at the Bottom

Is there a way to achieve this specific shape using CSS? I attempted to use the following resources, but they didn't provide me with the desired outcome. Curved border with stroke in pure CSS? http://jsfiddle.net/ECHWb/ .banner-img{ height: 661p ...

Hyperlink -> Boundary

Our homepage features various elements as part of the menu. Each element consists of a picture, title, and small description. The issue is that these menu items always display a border when the mouse hovers over them, despite attempts to hide it. You can ...

How can I access the fourth div element within the initial row of a multirow div container?

My current HTML structure is causing me some confusion. I am trying to create a CSS selector for the element with the text "DESIRED ELEMENT": <div class="TopDiv"> <div class="container"> <div class="row"> ...