Creating a dynamic background color that pulses with animation

I recently created a script to animate the menu li element when hovering over the corresponding a element. Everything is functioning as expected, but now I'm looking to enhance the effect by having it continue as long as the mouse remains over the a element.

What type of function should I implement to achieve this behavior?

This is what my script currently looks like:

 jQuery(document).ready(function($){
        $(".main-navigation a").mouseover(function() {
        $(this).parent().animate({
    backgroundColor: "green"
    }, "normal"),
    $(this).parent().animate({
    backgroundColor: "transparent"
    })
    .mouseleave(function() {
    $(this).parent().animate({
    backgroundColor: "transparent"
    }, "normal")
    });
    });
});

http://jsfiddle.net/neugu8r9/

Answer №1

To achieve this effect, you have the option to utilize CSS's @keyframes feature instead of relying on jQuery.

ul {
  position: relative;
  width: 250px;
  height: 50px;
  padding: 0;
  margin: 0;
  list-style: none;
}
li a {
  width: 100%;
  height: 100%;
  line-height: 50px;
  text-align: center;
}
li a:before {
  position: absolute;
  content: '';
  width: 100%;
  height: 100%;
  display: block;
  z-index: -1;
}
li {
  position: relative;
  height: 50px;
  width: 250px;
  text-align: center;
  border: 1px solid black;
}
a:hover:before {
  -webkit-animation: pulse 0.8s ease-in-out infinite alternate;
  animation: pulse 0.8s ease-in-out infinite alternate;
}
@-webkit-keyframes pulse {
  0% {
    background: transparent;
  }
  50% {
    background: green;
  }
  100% {
    background: transparent;
  }
}
@keyframes pulse {
  0% {
    background: transparent;
  }
  50% {
    background: green;
  }
  100% {
    background: transparent;
  }
}
<nav class="main-navigation">
  <ul>
    <li><a>Menu-item#1</a></li>
    <li><a>Menu-item#2</a></li>
    <li><a>Menu-item#3</a></li>
    <li><a>Menu-item#4</a></li>
  </ul>
</nav>

Answer №2

Check out this comprehensive jQuery solution, I hope it proves to be beneficial for you:=)

jQuery(document).ready(function($){
    var intervalID;

    $(".main-navigation ul li a").hover(function(){ 

        var that = $(this); 
        var opacityToggle = function(){
            if(!that.children('.green').length){
                $(that).prepend('<span class="green"></span>');
                $('.green').animate({opacity:1},500);
            }
            else if(that.children('.green').length){

                $('.green').animate({opacity:0},500,function(){
                    $('.green').remove();
                });
            }

        }

        intervalID = setInterval(opacityToggle, 500);    

    },function(){
        $('.green').remove();
        clearInterval(intervalID);
        intervalID = 0;    
    });
});
ul{
    list-style:none;
}

li a {
    height:100%;    
    text-align:center;
    position:relative;
    width:inherit;
    display:block;

}

li {
    height: 50px;
    width: 250px;
    text-align: center;
    border: 1px solid black;

}

.green{
    position:absolute;
    background-color:green;
    width:100%;
    height:100%;
    display:block;
    opacity:0;
    z-index:-1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="main-navigation">
    <ul>
        <li><a>Menu-item#1</a></li>
        <li><a>Menu-item#2</a></li>
        <li><a>Menu-item#3</a></li>
        <li><a>Menu-item#4</a></li>
    </ul>
</nav>

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 filter method in combination with slice array functions is not functioning properly

My search input is used to filter an array of users displayed in a table. The table has pagination set up so that only 10 users are shown per page. Oddly enough, the search filter only seems to work on the first page. Once I navigate to another page, the ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...

Develop an Interactive Newsfeed Pop-up Feature for Laravel 4 Using JavaScript - A User-Friendly Addition to

I'm attempting to trigger the newsfeed dialog for a user who clicks on a button (to post something on their Facebook wall). The code I have sets up a logged in and authenticated Facebook user using Laravel 4 with laravel-oauth2 package. However, when ...

Laravel has not been properly initialized

Recently, I've been exploring Laravel 5.3 and vue.js and I'm trying to make a GET request to fetch some user data from my database. I'm utilizing components in this project. Here is a snippet from my app.js file: require('./bootstrap ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

What is an alternative approach to passing arguments to an event handler in a React render component without using a lambda function?

In my React app, I've learned that using lambda functions in the property of a render component can harm application performance. For example: <ConfirmSmsModal modal={args.modal} smsCheck={async (code: string) => { return await this._vm ...

Updating a value within destructuring and a loop: A step-by-step guide

My Goal: I aim to modify a value in an object that is part of an array element. Take a look at the code snippet below for a clearer understanding. An issue arises when I update the object's value through reference instead of creating a new copy, cau ...

Obtain an identifier to be used as dynamic data in an ajax request with jQuery

I am struggling to extract the id from links that trigger the same ajax function. I have over 30 links generated dynamically, as shown below: <a href="javascript:void(0)" id="105">Item 105</a> <a href="javascript:void(0)" id="379">Item 3 ...

Incorporating a function from a separate .js file into an index.ejs view using app.js

graphs.js: contains a function that initiates an API call and retrieves an object containing an HTML link for embedding a graph. app.js: includes the following (graphs.js has been imported): var express = require("express"); var app = express(); var grap ...

Aligning a element at the center is not functioning properly when using margin: 0 auto;

I'm having trouble aligning elements to the center when applying margin: 0 auto. You can view the code here: https://jsfiddle.net/helloworld123/vhhx1o7n/ The goal is to align the elements in the center of the page (.entry-wrap should be centered) and ...

Orchard's TinyMce now supports a drop event with jQuery integration

Currently in the process of constructing a website using Orchrad. I have implemented the tinymce4 html editor for building landing pages without any issues thus far. However, my current challenge involves capturing the jQuery drop event within the TinyMce ...

Caution: session_start(): Unable to initialize session cookie - headers have already been sent by (output initiated at

A warning message is displayed on the login page: "It's working in localhost but not in remote host" Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at on line 8) Warning: sess ...

Utilize v-for to dynamically showcase a variety of images on your

My goal is to showcase several JPG pictures located in the src/assets/images folder by utilizing the v-for directive. However, it seems like the browser is having trouble locating them. Interestingly, manually adding the pictures with the same paths works ...

Modifying .css properties in jQuery with fixed values

In the PHP code snippet below, I utilized regex to adjust the font-size and line-height of an html page. Now, I am looking to achieve a similar functionality in jQuery. Is it possible to store static values for an entire method like .css() in jQuery? This ...

Here is a way to transfer the form data from the modal component to the submit handler

I am currently developing a VUE application that includes displaying a team table with information fetched from the backend using axios and django rest_framework. Everything is functioning properly. However, I encountered an issue when clicking on "new ca ...

Understanding the float property in CSS

Check out this CSS example: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Jenware | Personalized Gifts</title> <style type="text ...

What steps should I take to ensure my three.js project is compatible with iPhone testing?

I recently developed a new AR project that allows users to interact with AR content through their phone camera on a website. However, I am facing an issue where I cannot easily test my website on an iPhone whenever I make changes to the code. Currently, ...

What makes styling a success button in @material-ui so challenging?

I am currently utilizing the user interface framework found at https://material-ui.com/ My primary aim is to obtain a success Button and Chip. Can anyone provide insight on achieving this goal without resorting to less-than-ideal methods like those discus ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...