Is there a way to keep this function running endlessly when hovering?

Is there a way to modify this function so that the classes of my links continuously change colors while I hover over them, rather than changing only once?

<script type="text/javascript">
        $(".nav a").hover(function(e){
            var randomClass = getRandomClass();
            $(e.target).attr("class", randomClass);
        });
        $(".text a").hover(function(e){
            var randomClass = getRandomClass();
            $(e.target).attr("class", randomClass);
        });
    function getRandomClass(){
        var classes = new Array("green", "purple", "teal", "violet", "pink", "red", "yellow", "blue", "magenta", "orange");
        var randomNumber = Math.floor(Math.random()*11);
        return classes[randomNumber];
    }
    </script>

Any suggestions on how I can achieve this effect would be greatly appreciated. Thank you!

Answer №1

To implement a continuous function, you can use the setInterval method.

Here is an example:

var timer;

$(".content p").hover(function(e) {
  var event = e;
  timer = setInterval(function() {

    var randomStyle = getRandomStyle();
    $(event.target).attr("style", randomStyle);

  }, 200); //adjust the time interval in milliseconds as needed
}, function(e) {
  //clear the interval when the user moves the mouse away
  clearInterval(timer);
});

Answer №2

To dynamically change the class as you move your mouse over a link, simply switch from using the "hover" event to the "mousemove" event:

https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event

If you prefer to alter the class while hovering over the link without moving the mouse, consider using an interval to update it continuously:

How to keep an animation going while hovering over a specific element in jQuery?

Answer №3

Take a look at the following jsFiddle link

Click here for Fiddle

$(".text a").hover(function(e) {
    var evt = e;
    textInterval = setInterval(function() {

        var randomClass = getRandomClass();
        $(evt.target).attr("class", randomClass);

    }, 10); //modify this value to adjust the interval timing in ms 
}, function(e) {
    clearInterval(textInterval);
    var randomClass = getRandomClass();
    $(e.target).attr("class", randomClass);
});

function getRandomClass() {
    var classes = new Array("green", "purple", "teal", "violet", "pink", "red", "yellow", "blue", "magenta", "orange");
    var randomNumber = Math.floor(Math.random() * 11);
    return classes[randomNumber];
}

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

Creating a nx workspace for vanilla JavaScript (Error: module 'typescript' not found) - Step-by-step guide

Looking to set up a new workspace for plain React applications. How can I do it? Create Workspace npx create-nx-workspace@latest # version 15.2.1 # style: package-based # distributed caching: NO Installing the react-package npm install -D @nrwl/react Cr ...

Sending date and time data to a controller action using jQuery AJAX

How can I send a datetime value to a controller action using jQuery Ajax, while utilizing jQuery UI datepicker for textboxes and calendar controls? The current action is still set as controller/action/11/12/2011 which seems to not be functioning correctly ...

Why does my window scroll change when making a $.ajax call?

Encountering a peculiar bug... Whenever my JS code enters the success function after a jQuery $.ajax call, the scroll position on my window suddenly jumps to the bottom of the page. This is problematic for me as I'm developing a mobile page and want t ...

Tips for repairing buttons in the CSS container

The buttons in the CSS search-box are not staying fixed as intended. They should be within the search box, but instead, they are protruding out of the panel. I attempted to utilize z-index, but it did not produce the desired outcome. https://i.sstatic.n ...

Step-by-step guide on how to prioritize rendering the login page before the ngView in AngularJS in order to

As I begin my journey with Angular JS, I am eager to implement security measures in my application. My intention is to set up a log-in page as the default landing page for my single page application. Can anyone provide guidance or recommendations on how ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

The function __WEBPACK_IMPORTED_MODULE_1_react_dom___default.a.createPortal does not exist

Encountered Error: TypeError: __WEBPACK_IMPORTED_MODULE_1_react_dom___default.a.createPortal is not a function Modal.js:14 11 | 12 | 13 | function Modal(props) { > 14 | return ReactDOM.createPortal(JSX_MODAL, document.querySelector("#modal") ...

Is it secure to store the access token within the NextAuth session?

Utilizing a custom API built with Node.js and Express.js, I have implemented nextAuth to authenticate users in my Next.js application. Upon a successful login, the date is stored in the nextAuth session and can be accessed using the useSession hook. To acc ...

Is there a way to retrieve the client's IP address from the server side within a Next.js application?

How can I determine the user's time zone and location in order to generate a server-side page tailored to their specific location and time zone? I am struggling to retrieve the user's IP address from the request or the localhost IP address (127.0 ...

Display an image when the link is hovered over within a table

I'm looking for a way to display a scanned receipt image when hovering over a link within a table. I've written some code but it's not working as expected. Can anyone help me figure out what's wrong? Here is the current state of my cod ...

What is the best way to retrieve and display a PDF file through an API in VueJS?

I am looking to display a file from my API in my VueJS client. Specifically, when accessing a certain URL, the file (pdf, text, or image) should open if the browser supports it (similar to how Chrome opens PDFs). I want to achieve this using VueJS or just ...

Using javascript to navigate back to the previous page without redirecting to the main page

When utilizing an iframe, I've implemented a back button that triggers the following JavaScript code when clicked: document.getElementById("myframe").contentWindow.history.go(-1); // back While this works as intended, if there are no previous pa ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

Using Knex in ExpressJS to insert a list of entries into SQLite with unique field constraints

I'm currently facing an issue with inserting a list of exercises into an sqlite database. The app is built on express JS and I am utilizing sqlite3 and knex to handle interactions with the DB. My goal is to add a set of exercises into the table exerci ...

Submitting an HTML form to trigger a PHP function through AJAX

I am currently working on a task that involves POSTing an email address entered in an HTML form to a PHP script for storage in a database. The script should also handle error messages if the user inputs an invalid email address. I want to make this process ...

The HTML code does not display list items

I'm having trouble getting the image to display in the list element of my toolbar creation. Here is my CSS and HTML code: ...

Changing URL parameters without refreshing the page using query strings

Is there a method similar to how Google adds and removes parameters from the URL in Gmail without requiring a postback? For example, when you start composing a draft, a "?compose=new" parameter is added to the URL. I was considering using `history.pushSta ...

The Battle: AJAX FormData vs encodeURI

When utilizing jQuery's encodeURI(), the data transmitted through AJAX appears in this format: key1=true & key2=34 & ... In order to send an image via AJAX, I employ the FormData() method, resulting in the AJAX data without an image looking ...

What is the best way to ensure that all website users receive the same update at the same time using AngularJS and Firebase?

Imagine a scenario where I and my 3 friends are accessing the same website from different computers simultaneously. Each of us has a profile stored in an array like this: $scope.profilesRanking = [ {name:"Bob", score: 3000}, {name:"John", score: 2 ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...