Is there a way to modify the CSS of the sequential number element when it is clicked on?

I've successfully utilized jQuery to create sequential numbering for my menu items.

Upon clicking, the hyperlink text changes color to red. However, I'm facing an issue where I want the corresponding number to also change to red when the hyperlink is clicked and active.

For example, clicking on 'WHY YOU NEED IT' turns the text red perfectly. But I'm looking to have the background color of number 1 change to red as well.

I attempted to switch classes but it didn't produce the desired result.

Below is the provided JavaScript code:

jQuery(function ($) {
    $(".menu-solutions-menus-container ul li").each(function (i, el) { $(this).children('a').prepend("<number>" + (i + 1.) + "</number>");
});

$('.local-scroll').click(function (event) {
    event.preventDefault();
    
    var full_url = this.href;
    
    var parts = full_url.split('#');
    var trgt = parts[1];

    var target_offset = $('#' + trgt).offset();
    var target_top = target_offset.top;

    $('html, body').animate({
        scrollTop: target_top
    }, 500);
});

$('.menu-solutions-menus-container a').click(function () {
    $('.menu-solutions-menus-container a').removeClass('active');
    $(this).addClass('active');
});

$('.number').click(function () {
    $('.number').removeClass('active');
    $(this).addClass('active');
});

Here's the jsfiddle workspace. (Change jQuery version to jQuery 1.7.2 or above if you don't see the numbers.)

I'm particularly interested in implementing this feature on the secondary menu of this website.

Thank you in advance for your help.

Answer №1

Simply adjusting the class names should resolve the issue

modify

.active number {
    background: red;
}

To

a.active number {
    background: white;
}

Explanation and revision (edited)

The CSS selector .active number targets an html element number with a class of active, such as <number class="active" />. However, based on your HTML code, it appears that you intend for the parent <a> to have the class "active" with a child node of <number>.

To achieve this, the parent class should come first followed by a space to indicate a child element of the parent, then specify the target element.

For example:

a.active number {
    background: red
}

Additional notes for top bars:

There are a couple of adjustments required here. Firstly, the grey sections are background colors rather than borders. Secondly, the CSS selector is looking for a parent class of "active," but in your case, "active" is nested within the <li> elements.

<li id="menu-item-205" class="local-scroll menu-item menu-item-type-custom menu-item-object-custom menu-item-205">
    <a href="#what-we-offer" class="active"></a>
</li>

To address this, assign the active class to the li instead:

ul.shortcode_menu.solution-menu li.active {
    background: black;
}

I have replaced border-top with background: black assuming it aligns with your desired effect.

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

Using Responsive Design with Bootstrap and Media Queries

As a beginner in front-end development, I have recently learned about media queries and their functionality. Having previously studied Bootstrap, I can't help but wonder if media queries are actually necessary. After all, Bootstrap seems to offer simi ...

Invoke the prototype function through an onclick event after dynamically adding a button

Within my code, I have created two prototype functions named showPopup and buildView. The buildView function is responsible for generating dynamic HTML that includes a button. My intention is to invoke the showPopup function when this button is clicked. Ho ...

`Inconsistencies between Postman and AngularJS service responses`

When I make a call to the endpoint using Postman, I receive this response: https://i.stack.imgur.com/pH31G.png However, when I make the same request from my AngularJS service defined below: this.login = function (loginInfo) { return $http({ ...

The random number generator often omits both the upper and lower limits

I am working with an array that contains letters from A to H. However, when using a random number generator, I have noticed that the letters A and H are rarely selected. How can I adjust my approach to make sure these two bounds are included more often? ...

Unable to reinitialize MUI DatePicker after keydown event

Encountering an unusual behavior that defies explanation has left me puzzled. You can explore the code sandbox here. I am attempting to enable resetting a readOnly field by pressing DEL or BACKSPACE, but it seems to be ineffective. Oddly enough, I can suc ...

JS problem with using for and foreach loops in Node.js

I've been really stumped by this situation. Everything was running smoothly until 4 days ago when two of my cron daemon jobs suddenly stopped working. Instead of ignoring the issue, I decided to take the opportunity to rebuild and enhance the code. I ...

The paragraph element is refusing to align with the next paragraph element on the following line

The issue I'm facing is that the paragraph element is not displaying on a separate line from the other paragraph element. body { margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; backgr ...

Is it possible to send a search query to thesaurus.com using HTML code on a webpage?

I've created an HTML page with a text field and a submit button. When the user enters a word in the text field and clicks submit, a servlet fetches the input using request.getParameter(). Now, I need assistance implementing functionality to send this ...

Is my implementation of Model and Views in backbone.js accurate?

I'm new to backbone.js and I've just created my first page. I'm curious to know if I'm headed in the right direction with my approach (if there even is a "correct" way in software development). Is there a way to automatically bind mode ...

Retrieving values from all fields in a dynamic form using VuejsLet's say

In the process of developing an admin panel using Vuejs and tailwind CSS for managing exercises on a page, I have encountered some challenges. My current objective is to insert the dynamic form values into a Firebase real-time database. However, I am stru ...

clearInterval function is not functioning

Could this be a simple syntax error causing my frustration? The resizeTime variable seems to persist despite multiple attempts to clear it using clearInterval. Any thoughts on what may be going wrong here? Below is the code snippet: var resizeTime; // e ...

Utilizing Jquery to add a delay and animate the sliding up effect on a recently created element

I am looking to apply a slide-up effect to a newly created element after a specified delay. $("div[data-error='true']").delay(5000).slideUp(500, function () { $("#error-alert").remove(); }); $("div[data-success='true']").delay(5000 ...

Transforming localhost into a server name in a Node.js environment

Recently I began working on full stack development. I have a physical server and I want to upload my code to it so I can run the NodeJS server from there. This way, when people try to access my site, they will use or instead of localhost:port, which on ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Using AngularJS to update attributes in an HTML tag within a string

My string contains HTML tags : var str = "<div><p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src='urlAAA' height='400' width=&ap ...

The surprising twist of hasOwnProperty's behavior

I am currently working on a function that is designed to check whether an object contains keys such as 'id' or 'serif:id'. However, I have encountered some issues with its functionality. function returnIdPreferSerifId(object) { if ...

Experiencing Internal Server Error with Laravel and AJAX when using the save method on a model

My goal is to successfully send data from Ajax to a Laravel controller. However, I keep encountering an issue where I receive the error message AJAX error: error: Internal Server Error. After researching extensively, I discovered that in addition to the da ...

Are custom boolean attributes supported in HTML?

When working in HTML5, we have the ability to utilize custom data-* attributes. However, since these are considered attributes, they generally require a string value. Is there a different option within HTML that allows for custom properties, where boolean ...

Transforming a redux form onSubmit function into a promise-based structure

One of my goals is to promisify the onSubmit handling in my submitForm for redux form. You can find a similar example here. submitForm = () => { return this.props.submituserForm() .then(() => { console.log('test') }) ...

Why isn't this setState function activating?

I am working on creating a versatile notification React component for my application that can be accessed from any part of the code. I have written the following code, where I am attempting to find a workaround for exporting the showNotif function: func ...