Text color animation effect for menu

Here is the layout of my menu:

<nav>
    <a href="#">
        <span class="black">Home</span>
        <span class="red active">Home</span>
    </a>
    <a href="#">
        <span class="black">Longer menu item</span>
        <span class="red">Longer menu item</span>
    </a>
    <a href="#;">
        <span class="black">Two words</span>
        <span class="red">Two words</span>
    </a>
    <a href="#">
        <span class="black">About</span>
        <span class="red">About</span>
    </a>
    <a href="#">
        <span class="black">Contact</span>
        <span class="red">Contact</span>
    </a>
</nav>

The active menu item is styled in red. When a user clicks on a link, the red color should transition smoothly from the active menu item to the clicked link, changing the color as it moves along.

Experience the effect in action with this fiddle. Click on the second link, then the third link to see the transition.

While the transition from left to right works perfectly, the initial red text moves along with the color instead of staying fixed. How can I fix this?

I am open to any suggestions on enhancing this effect.

Edit:
To clarify, I am looking to achieve this effect on text rather than hover. When you move the mouse from left to right on the first row, you'll see the desired effect. I want this effect to occur on click, not just hover.

There are two scenarios to consider:

  1. When a menu item is clicked on the right side of the active link -> the color effect should transition to the right.
  2. When a menu item is clicked on the left side of the active link -> the color effect should transition left.

Answer №1

Maybe you intended to reference this: http://jsfiddle.net/t1w4gy0w/3/

Updated for both variations: http://jsfiddle.net/t1w4gy0w/4/

Enhanced for quicker user interaction: http://jsfiddle.net/t1w4gy0w/5/

$('.blackholder').parent().on('click', function(event) {

    if ($(this)[0] === $('.red.active').parent()[0]) {
        return;
    }

    var animFull = function (obj) {
        obj.addClass('top').finish()
        .css('width', '0').animate({ width: '100%'}, {
            duration: 1000,
            queue: false,
            complete: function () {
                $(this).removeClass('top');
            }
        });
    };

    var moveRight = function (atag) {
        animFull(
            $('.red.active').removeClass('active').siblings('.black')
        );

        animFull(
            $(atag).children('.red').addClass('active')
        );
    };

    var animZero = function (obj) {
        obj.addClass('top').finish()
        .animate({ width: '0'}, {
            duration: 1000, queue: false,
            complete: function () {
                $(this).removeClass('top').css('width', '100%'); 
            }
        });
    };

    var moveLeft = function (atag) {
        animZero(
            $('.red.active').removeClass('active')
        );

        $(atag).children('.red').addClass('active');
        animZero(
            $(atag).children('.black')
        );
    };

    if ($('.red.active').parent().position().left < $(this).position().left) {
        moveRight(this);
    } else {
        moveLeft(this);
    }

});
.blackholder {
    color: #000;
}
.black.top, .red.top {
    z-index: 3;
}
.black {
    z-index: 1;
    color: #000;
    left: 0;
    position: absolute;
}
.red {
    color: red;
    left: 0;
    position: absolute;
}
.red.active {
    z-index: 2;
}
<nav>
    <a href="javascript:void(0);">
        <span class="blackholder">Home</span>
        <span class="black">Home</span>
        <span class="red active">Home</span>
    </a>
    <a href="javascript:void(0);">
        <span class="blackholder">Longer menu item</span>
        <span class="black">Longer menu item</span>
        <span class="red">Longer menu item</span>
    </a>
    <a href="javascript:void(0);">
        <span class="blackholder">Two words</span>
        <span class="black">Two words</span>
        <span class="red">Two words</span>
    </a>
    <a href="javascript:void(0);">
        <span class="blackholder">About</span>
        <span class="black">About</span>
        <span class="red">About</span>
    </a>
    <a href="javascript:void(0);">
        <span class="blackholder">Contact</span>
        <span class="black">Contact</span>
        <span class="red">Contact</span>
    </a>
</nav>

If modifications are needed, such as adding comments to the code, please let me know in the comments section.

Answer №2

Are you searching for a transition effect from red to black and vice versa? Check out this demo link: http://jsfiddle.net/t1w4gy0w/2/

$('.black').on('click', function (event) {
    $('.red').animate({
        width: 0
    }, {
        duration: 1000,
        queue: false
    }).removeClass('active');
    $(this).parent().find('.red').addClass('active').animate({
        width: '100%'
    }, {
        duration: 1000,
        queue: false
    });
});

Don't forget to update the CSS as well.

.red {
    top: 0;
    right: auto;
    left: 0;
    width: 0;
    color: red;
    display: none;
    position: absolute;
    z-index: 5;
    overflow: hidden;
}
.red.active {
    left: 0;
    right: auto;
    display: block;
    width: 100%;
}

Answer №3

Perhaps

$('.black').on('click', function(event) {
    $('.red').css({'width': 0}).removeClass('active');
    $(this).siblings('.red').addClass('active').animate({ width: '100%'}, {
        duration: 1000,
        queue: false
    });
});

If you're aiming for a color slide to the left, adjust the position of .red to the left. Currently, it seems like width = 0 is moving towards the right corner.

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 functionality of JQuery is not effective when trying to retrieve a radio button value within a partial view

Trying to extract a value from a radio button to toggle another component in a modal popup. I attempted to accomplish this by including JQuery code in a partial view within the modal popup, but unfortunately, it didn't work as expected. Interestingl ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...

What are the steps for implementing CSS in Markdown?

How can I incorporate a CSS class into a Markdown file? For example, using <i class="icon-renren"></i> (from the fontawesome library) should display an icon when its CSS file is imported in HTML. Is there a way to achieve this in Markdown? ...

I ran into an issue trying to modify the color and thickness of the divider line in MaterialUI

Check out my code on codesandbox here. I'm trying to adjust the line thickness and color of the separator in my MaterialUI project, but I'm having trouble getting it to work. I've looked at a few examples, but nothing seems to be working for ...

A group of iframes are cropping at the bottom

Currently, I am encountering a problem with using iframes to manage the navigation aspects on my website. Despite setting the iframe to have "overflow: visible;", it still crops the bottom of my content. The strange thing is, both iframes on the same page ...

What's causing my struggle to override the bootstrap nav-link class in next.js?

I am facing an issue where I need to customize the active state of bootstrap .nav-link in the code snippet below: <li className="nav-item"> <a className={`${styles.navLink} nav-link`} role="tab" data-to ...

I'm having trouble with my fullscreen menu. Is there something I missed when setting it up?

Hi there! I'm currently working on my website and I seem to have run into an issue with the code. I'm still new to coding, so I would appreciate some assistance in identifying where I went wrong. I've been going through the code diligently t ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Is there a more efficient method for implementing React OnChange for each field?

When calling an API, receiving a payload and loading it into state in React, we often encounter situations where we have multiple fields to update. This can lead to creating numerous onChange functions for each field. Is there a more efficient pattern tha ...

Using a variety of different font styles within a single sentence

I'm looking to add a title with text in one of my divs, but I want the title to be in 3 different font sizes. Any suggestions on how to achieve this without starting a new paragraph for each size change? Here's an example of what I'm trying ...

Ajax fails to send requests to PHP after changing the URL directory

After struggling to find a solution to my query, I have come to the realization that it has not been asked before. Despite enabling rewrite rules on my apache2 server in the .htaccess file located in the root directory, I am facing an issue with my ajax sc ...

Issue encountered: Unable to locate module: Error - Unable to resolve '@cycle/run' with webpack version 2.2.1

I am attempting to run a hello world application using cycle.js with webpack 2.2.1. The following error is being displayed: ERROR in ./app/index.js Module not found: Error: Can't resolve '@cycle/run' in '/Users/Ben/proj/sb_vol_cal ...

Having trouble generating a mock constructor for the user model

While attempting to simulate my user model in order to test my service, the nest console is throwing a TypeError. I am unsure of how to properly 'emulate' the constructor of the user model. user.service.spec.ts import { Test, TestingModule } fro ...

Storing the result of an Angular $http.get request in a variable

As a newcomer to Angular, I am exploring how to retrieve a JSON object containing a list of individuals from CouchDB using a $http.get call. The JSON structure includes an id, names, and quotes for each person: { "total_rows": 2, "offset": 0, ...

Get rid of the "clear field" X button for IE11 on Windows 8

After trying out the suggestions provided in Remove IE10's "clear field" X button on certain inputs? .someinput::-ms-clear { display: none; } I successfully removed the X button on IE 11 running on Windows 7, but unfortunately it didn&a ...

What is the best way to use JQuery to delete dynamically generated div elements after removing a record from the database?

I have generated dynamic Div(s) using data from a database and I need to be able to delete a specific div along with its elements when a record is removed from the database. I've implemented a deleteFile(id) function that uses AJAX to remove the div ...

When running collection.find().toArray(callback) in node.js with mongodb, the result is coming back

When I run my code, mydocuments.find({}).toArray is returning empty. I have seen some solutions posted but they don't apply to my situation since I am using MongoClient.connect. Any help would be greatly appreciated. var MONGOHQ_URL="mongodb://harish ...

Dynamic dropdown menu based on the location using JSON and jQuery

I need to create a series of dropdown menus for selecting country, state, and city. The country and state dropdowns are working fine, but I am having trouble populating the city dropdown. What could be missing in my code? Here is what I have so far: <f ...

Using the .json method in Angular 7 for handling responses

While attempting to implement the function getProblems to retrieve all problems within its array, I encountered an error message appearing on res.json() stating: Promise is not assignable to parameters of type Problem[]. It seems that the function is ...

Is it possible to consolidate React and React-DOM into a unified library instead of having them separate?

Is it possible to combine React.JS and React-DOM.JS into a single library? In all the web applications I've encountered, we always have to import both libraries separately. Have there been any cases where either of these libraries can be used on its ...