Is there a way to ensure my function runs as soon as the page starts loading?

My goal is to have a function execute as soon as a person opens my page, without requiring any interaction. The function should trigger on page load, rather than waiting for a click event. Additionally, I want the function to repeat every 90 seconds. I've attempted to replace "click" with window.onload and body.onload, but being new to JavaScript, I'm struggling to achieve this. Any assistance would be greatly appreciated. Currently, all I have is the following code snippet:

// Animate an element by adding a class to it:
// Parameters: 
// anim: the class name to add
// time: animation duration (optional, falls back to the class)
// cb: an optional callback function to run once the animation ends
$.fn.animatecss = function(anim, time, cb) {

    if (time) this.css('-webkit-transition', time / 1000 + 's');
    this.addClass(anim);

    if ($.isFunction(cb)) {
        setTimeout(function() {
            // Ensure that the element is available inside the callback.
            $(this).each(cb);
        }, (time) ? time : 5000);
    }

    return this;
};

$(document).ready(function() {
    $('.box').click(function() {
        $(this).animatecss('blur-out', 5000, function() {
            console.log('callback');
        });
    });
});
.blur-out {
    -webkit-filter: blur(8px);
    -webkit-transform: scale(1.4, 1.4);
    -webkit-transition: all 5s ease-out;
    transition: all 5s ease-out;
    visibility: hidden;
}

.box {    
    background:#fff;  
    margin: 80px; 
   padding: 20px;    
    
}
    
<div class="box">
    <img src="http://companionplants.com/images/small-plant2.jpg">
</div>

Answer №1

$(document).ready(function() {
    $('.box').click(function() {
        $(this).animatecss('blur-out', 5000, function() {
            console.log('callback');
        });
    });

    
    // Include this line to trigger the click event
    $('.box').trigger('click');
});

For more information, visit: http://api.jquery.com/trigger/

Answer №2

To automatically start the animation after the page is loaded, just remove the event handler for click and keep the code for the animation as follows:

$(document).ready(function() {  
        
  $('.box').animatecss('blur-out', 5000, function() {
    
    console.log('callback');
    
  });

            
});

If you want this code to repeat automatically, you can place it in a recursive function with setTimeout like this:

$(document).ready(function() {
  
  function animate(){
    $('.box').animatecss('blur-out', 5000, function() {
      
      console.log('callback');

    });
            
    setTimeout( animate(), 60000);
  }
  
  animate();
            
});

I believe this solution will work for you without any errors. Give it a try!

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

Having issues with Sequelize and SQLite auto increment functionality. No errors when using AutoIncrement, but the auto increment feature is not working. On the other hand, errors arise when using

I am currently in the process of developing a discord bot, which includes 2 slash commands. One command is called /setup, used for adding the guildId and an adminChannel to a database. The other command is named /onduty, which is used for adding the user, ...

Using Material-UI to showcase a TextField with a labelWidth set to zero

I need to showcase a specific field on my website. https://i.stack.imgur.com/PJUW7.png However, the issue I'm facing is that even when the field is in focus, the border remains unaffected and does not get cut off by the label. https://i.stack.imgur ...

Enhancing list item appearance by replacing bullets with Font Awesome icons

I need to create a list similar to this example https://i.sstatic.net/w84xS.png Although I successfully replaced the bullet with a fontawesome icon, the result is not quite right as shown here https://i.sstatic.net/yqnbJ.png You may notice a difference ...

jQuery is an excellent tool for implementing drag and drop folder upload functionality, all without

I am creating a drag and drop file uploader with basic functionality. Here is the code: HTML: <div class="drop-box drop-area"> <form enctype="multipart/form-data" id="yourregularuploadformId"> <input type="file" name="files[]" ...

occupy the full width of the available screen space (from one end of the container to the other

Currently, I am utilizing the Flexbox enabled version of Bootstrap 4 Alpha 3. Check it out on Jsfiddle body { background-color: lightgreen; } [class^="col"] { background: gold; border: 1px solid tomato; } <link href="https://cask.scotch.io/boo ...

When attempting to modify an element in an array within a state-managed object, the input field loses focus

In attempting to address my issue, I have crafted what I believe to be the most concise code example. The main goal is to display a table on the page populated with exercise data retrieved from a database. This data is then assigned to an array of objects ...

Tips for refreshing only a portion of a webpage using JavaScript/jQuery

I have two distinct navigational sections on my website. The left column has its own navigation menu, while the right column (main content area) contains a separate set of links: My goal is to click on a link in the left-hand sidebar (such as "Resume", "E ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

Issue with Sheetjs: Date format is not recognized when adding JSON data to a

I am struggling to export JSON data to Excel while maintaining the correct date format of 2020-07-30 07:31:45. Despite trying suggestions from a helpful post on sheetjs, I still couldn't get it right. Here is an example of the JSON data: { "so ...

Display dynamic web content developed with JavaScript for public viewing

As a newcomer to the world of web development, I'm not sure if it's possible to achieve what I have in mind without using PHP. However, I'm willing to give it a shot. Currently, my webpage functions perfectly with JavaScript, HTML, and CSS, ...

accordions that are supposed to adapt to different screen sizes are

My custom responsive accordions are not functioning as expected. The requirement is to display headings and content for desktop view, but switch to accordions on smaller devices. I have managed to do this, however, when resizing the window, the functionali ...

Develop a custom script function for every instance of a @foreach loop

I have a challenge where I need to style automatically generated table rows by clicking on a button. Currently, my code appears as follows: @foreach($tours as $tour) <tr id="{{$tour->id}}"> <td> {{$tour->tournr}} &l ...

How can I keep images from getting cut off when using slick slider with a fixed background?

My current design includes a stylized slick-slider that extends beyond the top border: However, I have set a fixed background for .slick-list, ensuring only the content (text, picture, and button) scrolls: How can I avoid the picture being cropped in t ...

Loading google maps markers dynamically with ajax requests

I'm in the process of plotting around 120 markers on a Google Map by utilizing an ajax populated array containing google.maps.LatLng objects Here is my script <script type ="text/javascript"> $.ajaxSetup({ cache: false }); ...

Create various designs for a section of a webpage

My goal is to create a coding playground using flex-box to position different panels. Here is an example in JSBin, with the following html code: <div class="flex-box"> <div class="col" id="html-panel"> <p>html</p> </div& ...

Switching to a dropdown navigation option

Sorry for the repetition, but I haven't been able to find a solution to my problem yet, so here I am asking again. I am still getting the hang of html5 and css3, and while I've managed so far, I'm stuck now. I want to turn one of the option ...

Is it possible for Vue js to display an image from the /dist/ directory even if it is not present?

Currently, I am in the process of learning Vue.js + webpack and have started a project by following these steps: f:www\> npm install -g vue-cli f:www\> vue init webpack-simple my-project f:www\> cd my-project f:www\> npm in ...

Socket.io encounters emitting issue within express app.post function

I am working on integrating an express application with a frontend React application using socket connections. My goal is to trigger an event on the connected socket whenever a post request containing JSON data is sent to my server. However, I am facing a ...

Issue with Videogular: hh:mm:ss Date filter not functioning properly

I am currently working on integrating Videogular into my audio player application. Below are the settings provided in the example code on this particular page: <vg-time-display>{{ currentTime | date:'mm:ss' }}</vg-time-display> ...

Leveraging spread syntax and styling for array string interpolation in JavaScript

Imagine I have an array such as [1,2,3] and my goal is to insert its values into a string format like: the values are (?, ?, ?) Can anyone suggest a simple solution for this? I am aware of the spread operator ...[1,2,3], and it's feasible to conver ...