Invoke JavaScript upon the loading of the page or a specific element

I need help with a script that changes the color of each character in an element ("logo p") to a random color when hovered over. How can I modify this script to run automatically on page load, so that all characters have random colors at all times?

$(document).ready(function() {
    // COLOURS ARRAY
    var colours = Array("#B0171F", "#FF3E96", "#FF00FF", "#8B008B", "#9400D3", "#BF3EFF",     "#B22222", "#FF0000", "#800000", "#8E388E", "#bc8f8f"), idx;
    $("#logo p").hover(function(){
        var header = $(this); 
        var characters = header.text().split('');
        header.empty();  
        var content = '';
        for(var i = 0; i < characters.length; i++) {
            idx = Math.floor(Math.random() * colours.length);
            content += '<span style="color:'+colours[idx]+'">' + characters[i] + '</span>';
        }
        header.append(content);
    }, function() {
        $(this).find('span').contents().unwrap();
    });
});

Answer №1

If you replace the use of hover with mouseenter and mouseleave, and trigger the mouseenter event on target elements during page load by using .trigger('mouseenter');, you can try the following:

$(function(){
    var colours = Array( "#B0171F", "#FF3E96", "#FF00FF", "#8B008B", "#9400D3", "#BF3EFF", "#B22222", "#FF0000",          "#800000", "#8E388E", "#bc8f8f" );
    $("#logo p").on('mouseenter', function(){
        var header = $(this), characters = (header.text()).split(''), content = '';
        header.empty();  
        for(var i = 0; i < characters.length; i++) {
            var idx = Math.floor(Math.random() * colours.length);
            content += '<span style="color:'+colours[idx]+'">' + characters[i] + '</span>'; 
        }
        header.append(content);
    })
    .on('mouseleave', function(){
        $(this).find('span').contents().unwrap();
    }).trigger('mouseenter');
});

Check out the demo here.

This code will work both on page load and when using hover(mouseenter/mouseleave), eliminating the need for separate handlers for load and hover.

Answer №2

Give .each a shot!

<script type="text/javascript">
$(document).ready(function() {
// ARRAY OF COLORS
var colors = Array("#B0171F", "#FF3E96", "#FF00FF", "#8B008B", "#9400D3", "#BF3EFF",     "#B22222", "#FF0000", "#800000", "#8E388E", "#bc8f8f"), idx;
$("#logo p").each(function(){
    var header = $(this); 
    var characters = header.text().split('');
    header.empty();  
    var content = '';
    for(var i = 0; i < characters.length; i++) {
        idx = Math.floor(Math.random() * colors.length);
        content += '<span style="color:'+colors[idx]+'">' + characters[i] + '</span>'; 
    }
    header.append(content);
}, function() {
    $(this).find('span').contents().unwrap();
});
});
</script>

Answer №3

Transform this into a reusable function and invoke it when the page loads:

$(document).ready(function () {

    function updateTextColors() {
        // AVAILABLE COLORS
        var colors = Array("#B0171F", "#FF3E96", "#FF00FF", "#8B008B", "#9400D3", "#BF3EFF", "#B22222", "#FF0000", "#800000", "#8E388E", "#bc8f8f"),
            index;
        $("#logo p").each(function(){
            var header = $(this);
            var characters = header.text().split('');
            header.empty();
            var content = '';
            for (var i = 0; i < characters.length; i++) {
                index = Math.floor(Math.random() * colors.length);
                content += '<span style="color:' + colors[index] + '">' + characters[i] + '</span>';
            }
            header.append(content);
        }, function () {
            $(this).find('span').contents().unwrap();
        });
    }
    updateTextColors();
});

Answer №4

Perhaps I may not fully comprehend the question, but you can simply run your code on document ready like this:

    $(document).ready(function() {
    var colors = Array("#B0171F", "#FF3E96", "#FF00FF", "#8B008B", "#9400D3", "#BF3EFF","#B22222", "#FF0000", "#800000", "#8E388E", "#bc8f8f"), index;
    var heading = $("#logo p");
    var textArray = heading.text().split('');
    heading.empty();  
    var newText = '';
    for(var i = 0; i < textArray.length; i++) {
        index = Math.floor(Math.random() * colors.length);
        newText += '<span style="color:'+colors[index]+'">' + textArray[i] + '</span>'; 
    }
    heading.append(newText);
});

Here is the Fiddle link

If you desire to have the colors constantly changing, you could place your code inside setInterval

Check out this updated Fiddle for that.

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

PHP for Instant NotificationsInstant notifications feature using PHP

My PHP project is facing a challenge - I need to implement real-time notifications for users, similar to the ones seen on Facebook or Google+. These notifications should display a count of new/unread notifications. In the past, my approach has been to mak ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Deploying NextJS to IISNode without the need for a custom server: A step-by-step guide

Is there a way to deploy my NextJS App on IISNode while preserving the SSR and SSG functionalities? I prefer not to use a custom server for rendering as it may affect the SSR and SSG capabilities. What configurations should be included in my web.config f ...

The jQuery .load method is having trouble loading a local HTML file within a Cocoa WebView

Having an issue with my Cocoa WebView where I'm attempting to load a local HTML file using jQuery.load(). My code snippet looks like this: $("#mydiv").load("test.html"); // The test.html file is located within the app's bundle Although no exce ...

What is the best way to combine jQuery objects in order to apply CSS styles collectively?

If I have a custom function that takes in multiple jQuery objects: customFunction($('.content'), $('h1'), $('input[type=button]')); The function is defined as follows: function customFunc ...

The kick command doesn't seem to be working on my Discord bot as it's not responding

I'm facing an issue where I want the gif reactions to be sent randomly when using the kick command, but my bot isn't responding and there are no errors in the terminal. Here is a snapshot of the path: https://i.sstatic.net/3DOXQ.png The code ...

javascript function not being invoked

Currently, I have incorporated the following HTML <html> <head> <Title>EBAY Search</title> </head> <script language="JavaScript" src="ajaxlib.js"></script> <body> Click here & ...

Toggling the `toggleClass` on a fixed element when clicking a link (such as in an off canvas menu) can

As per the following markup code, there is a sticky navigation bar (menu-bar) that reveals an off-canvas menu using CSS transitions when the button is clicked by adding a class (slide-wrapper__open) to the HTML element. HTML <div class="menu-bar"& ...

When the dropdown form options in HTML are clicked, they appear disproportionately large compared to the initial select box

Sorry if my wording is a bit off, I'm still relatively new to working with CSS and HTML. I've encountered an issue where the dropdown options appear much larger than the select box itself when clicked. I can't seem to figure out how to fix i ...

Make sure to allow the async task to complete before beginning with Angular JS

As I develop an app using MobileFirst v8 and Ionic v1.3.1, I encounter issues with timing in my code execution. Specifically, when the application initiates, the regular ionic angular code within my app.js file runs. This section of the code handles the i ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

Upon transmitting the information to the server, an error message pops up saying 'Uncaught TypeError: Illegal invocation'

I'm encountering an issue with sending an ajax request in my php-script. The jquery script I'm using selects certain fields from a form and sends them as arguments to a jquery function. However, upon sending the data to the server, I receive the ...

jQuery - Enclose selected text with <span> tags - resolving duplicate instance issue

This particular question is related to a similar inquiry asked on Stack Overflow regarding the application of tags to selected text. While the original question was answered, there was a significant flaw in the solution provided. The issue arose when the s ...

Trouble with nested components not refreshing correctly within VueJs

I've just started working with Vue and I'm currently developing a forum-style application that allows nested comments. Within this structure, there are two main components: PostForum and Comment. The PostForum component consists of an input box f ...

Attempting to align or position the wrapper div in the center or using a float with a width of

I'm struggling to align the main div in the center of the page with a 100% width or at least float it to the left. Can someone please advise on how to achieve this? http://jsfiddle.net/d36TC/6/ <div class="addInput"><div sytle="clear:both"& ...

Using jQuery and AJAX to pass a string as a parameter in an onclick event

echo "<button onClick='follow(".$name.");'></button>"; Struggling to pass a string as a parameter in the follow(user) function's onClick event in jQuery. It keeps getting called as a value instead. I've ...

Executing a jQuery function in vb.net codeBy utilizing vb.net, the jQuery

Encountering an unusual issue where I need to toggle the visibility of a div both server side and client side without being able to change it to a panel. To achieve this, I am currently using the following code to toggle its visibility client side: $(&ap ...

Attaching my CSS file to my Django Project

I am currently working on linking my CSS files to my Django Project but I seem to be encountering errors along the way. This is what my settings file looks like: STATICFILES_FINDERS = ( '/Users/IMAC/work3/Blog/Blog/polls/static', ' ...

What is the reason for the faster deletion performance of objects compared to arrays when using the splice method

Curious about the speed variations between arrays and objects, I decided to conduct a test involving filling, accessing, and deleting 100,000 items from both. Surprisingly, accessing and filling the array showed minimal difference with only about ~3ms gap. ...

Utilizing Java's IE/Chrome HTML-Renderer or managing file storage with JavaScript

I am currently in the process of developing a small application that operates offline only. I want to keep it simple and was considering using HTML, CSS, and JavaScript as they should suffice for my needs. However, I require access to the filesystem to sto ...