Using jQuery to set menu active states for a sprite-based navigation with distinct class names

I'm curious about how to accomplish this using JQuery. I have a menu where each item must have a unique class name in order for the CSS to properly display a sprite background position shared by all items. When an item is clicked, I also need to activate a unique active state class name. What would be the most efficient approach to achieve this? Below is my code:

HTML

<div id="menu">
    <a href="javascript:void(0);" class="trailer">Trailer</a>
    <a href="javascript:void(0);" class="bios">Bios</a>
    <a href="javascript:void(0);" class="photos">Photos</a>
    <a href="javascript:void(0);" class="synopsis">Synopsis</a>
    <a href="javascript:void(0);" class="news">News</a>
</div>

CSS

#menu a { background: url(../images/menu.png) no-repeat; height:16px; overflow:hidden; display:block; text-indent:-10000px; float:left; margin-left:63px;}
#menu a:first-child { margin-left: 0;}
#menu a.trailer { width: 91px;}
#menu a.trailer:hover, #menu a.trailer_active { background-position: 0px -20px;}
#menu a.bios { width: 50px;  background-position: -153px 0;}
#menu a.bios:hover, #menu a.bios_active { background-position: -153px -20px;}
#menu a.photos { width:86px; background-position: -272px 0;}
#menu a.photos:hover, #menu a.photos_active { background-position: -272px -20px;}
#menu a.synopsis { width:103px; background-position: -423px 0;}
#menu a.synopsis:hover, #menu a.synopsis_active { background-position: -423px -20px;}
#menu a.news { width:62px; background-position: -579px 0;}
#menu a.news:hover, #menu a.news_active { background-position: -579px -20px;}

Answer №1

try implementing this jQuery script:

$('ul.nav>li').click(function() {
  $(this).addClass('current')
}

and modify your 'current' styles in the CSS as shown below:

#menu li.active:hover, #menu li.active.current { background-position: 0px -20px;}

replace the underscore with a period for the desired effect

Answer №2

When a user clicks on a link, the script appends '_active' to the class name of the link if it does not already end with '_active'.

var re = /_active$/g;

$('#menu').delegate('a[class]', 'click', function ()
{
    var $this = $(this),
        className = this.className;

    if (className.match(re)) return;

    // remove _active from siblings
    $this.siblings().attr('class', function (i, val)
    {
        return val.replace(re, '');
    });

    // add _active to self
    this.className = className + '_active';
});

See the demo: http://jsfiddle.net/mattball/xppZu/

Please note that this code assumes that there are no other classes applied to the links.

Answer №3

Hmm, it seems like I may have misunderstood the question or perhaps my fellow forum members are making things more complicated than necessary.

$('#nav').on('click', 'a', function() {
    $(this).addClass('active').siblings().removeClass('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

I am unable to return JSON data from an AJAX request

I've been working on a price calculator within Joomla and have created a plugin for my ajax function. It appears to be functioning correctly, but I'm unable to display the data once it's retrieved. Below is the jQuery code I'm using f ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

Divide the screen evenly with a split, where one side is filled with an image

As a newcomer, I'm curious about how to split the screen in half with a form on the left and an image taking up the full height on the right. Is there a simple way to achieve this? For reference, here is a link showing exactly how I envision it: Exam ...

Step-by-step guide on incorporating edit, update, and discard functionalities within an Angular Material table component (mat-table)

I am currently working on implementing edit, update, and discard functions in an angular material table. While I have been able to successfully edit and update the table row wise, I am struggling with how to discard table rows. If you would like to see wh ...

show the text on the screen rather than in an input field

Currently, I have a code snippet that includes 3 sliders and displays the total sum of those values in an input box. However, I am looking to modify it so that the value is displayed directly on the page without the input box. The layout should feature t ...

The window.onload function is ineffective when implemented on a mail client

Within my original webpage, there is a script that I have created: <script> var marcoemail="aaaaaa"; function pippo(){ document.getElementById("marcoemailid").innerHTML=marcoemail; } window.onload = pippo; </script> The issue a ...

Is there a way to create a JavaScript-driven search filter that updates automatically?

My website showcases a lineup of League of Legends champion icons, with one example shown below: <div class = "champion"> <p>Aatrox <img class = "face_left" src = "images/small/Aatrox.png"> <div class = "name" onmouseover="if(cha ...

What is the best way to adjust the size of an image using CSS, especially with flexbox

I'm attempting to arrange 3 images in a row using flexbox. I also need to adjust the size of the first image because it is too large. However, my CSS styles are not being applied correctly. Each image is enclosed in its own div with a class of flex-it ...

Is there a way to create a dropdown menu that appears to emerge from behind a button?

I am struggling with the stack order of my dropdown menu. Despite using z-index, it appears in front of the button instead of behind it. I want it to look like it is coming out from behind the button. Here is my code: .subnav-wrapper { position: relat ...

Should Angular Flex Layout be considered a top choice for upcoming development projects?

Should I consider using Angular Flex Layout for upcoming projects, even though it is considered deprecated? Despite its deprecation, there are still a high number of weekly downloads on npmjs.com. I am in the process of starting a new Angular project usin ...

Preventing Bootstrap modal from automatically closing in Laravel 5.1 when authentication fails

Whenever my bootstrap modal for login fails, it redirects to auth/login and closes the modal. How can I prevent the modal from closing when authentication fails and avoid the redirect back to auth/login? This is my login form: <form action="{{ URL::to ...

Displaying content conditionally - reveal a div based on user selection

I have a dropdown menu and need to determine whether to display a specific div using the value selected via v-if. <select class="custom-select custom-select-sm" id="lang"> <option value="1">English</option> <option value="2">Sv ...

Upon opening index.html in the browser, the jQuery code fails to execute, as no errors are displayed in the console

I am struggling to make a simple toggleClass() function work in jQuery and I can't seem to figure out why. This is just a beginner exercise for me with jQuery. The code works perfectly when I test it as a snippet or manually in the console, but when I ...

jquery carousel slider dynamically append

I have been tasked with creating a dynamic carousel using jQuery AJAX, and my supervisor recommended that I utilize the .append() method. Below is the HTML code for my carousel: <div id="myCarousel"> </div> <div cla ...

Ways to implement a user interface modification immediately following a jQuery effect event

My jQuery UI element has a bounce effect with a color change. After the bounce finishes, I want to set the color back to normal. Is there a way to achieve this? $(div).effect("bounce", { times:2 }, 200); Are there any event handlers in jQuery that are ...

When jQuery fails to detach() due to the presence of an input tag

I have a situation where I am trying to rearrange elements within a table. Everything works fine, until I introduce a tag, which triggers this error message:</p> <pre><code>Error: this.visualElement is undefined Source File: http://192. ...

What are the steps for applying a Bootstrap class to an element?

I keep encountering this error in the console: Uncaught DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('si col-md-4') contains HTML space characters, which are not valid in tokens. Below is a ...

Issues with the background-image scroll feature not functioning as intended

Can anyone help me out with a CSS issue I'm having? I've set an image as my background on a webpage and I want it to scroll with the page. Even though I followed some online tutorials, it's still not working for me. It's been a while si ...

Other elements are unable to conceal Material UI InputBase

Displayed below is a navigation bar that sticks to the top, followed by rows of InputBase components from material-ui. Despite setting the background color of the nav bar to white, the input always appears above the nav. This strange behavior stopped when ...

Struggling to set a background image for multiple div elements

Hey everyone! I'm working on a small school project website and I've run into an issue with the background on multiple div elements. Here's my HTML code snippet: <div class="bloc-1-text"> <h3> </h3&g ...