Falling rain animation in JavaScript

I'm a beginner in the world of JavaScript and I'm trying to create a div on a webpage with a rain effect. I've managed to generate random blue points within the div, but I'm struggling to make them move downwards. Here's the code I have so far:

<html>
<head>

<style>
.punct
{
background-color:blue;
position:absolute;
width:2px;
height:6px;
}
</style>

<script type="text/javascript">


var cleft;
var ctop;

var x=document.getElementById ('content');
function strop (cleft,ctop,d)
{
if (x==null) x="<div class='punct' style='top:"+ctop+"px;left:"+cleft+"px'></div>";
else x=x+"<div class='punct' id='"+d+"' style='top:"+ctop+"px;left:"+cleft+"px'>    </div>";
document.getElementById ('content').innerHTML=x;
}

function randomFromInterval(from,to)
{
return Math.floor(Math.random()*(to-from+1)+from);
}

var y=30;
function start ()
{
if (y!=0){
var a;
var b;
cleft=a;
ctop=b;
a=randomFromInterval (20,1000);
b=randomFromInterval (10,50);
strop(a,b,y);
setTimeout (function () {start ()},500);
y--;
}
}


</script>

</head>
<body>
<div id='content' style='border:2px solid black; height:500px; width:1000px;'></div>
<button onclick='start()'>Start </button>
</body>
</html>

Answer №1

Here is a unique solution using only Javascript. This code slowly makes drops appear and removes them when they reach the bottom. For more details, you can check out this link.

function createDroplet(leftPos, topPos, dropID) {
    var droplet = document.createElement('div');
    droplet.className = 'drop';
    droplet.style.left = leftPos + 'px';
    droplet.style.top = topPos + 'px';
    droplet.id = dropID;
    document.getElementById('content').appendChild(droplet);
}

function randomInterval(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
var count, timer;

function newDroplet() {
    var xPosition = randomInterval(20, 480),
        yPosition = randomInterval(10, 50);
    createDroplet(xPosition, yPosition, count);
    count--;
    if (count > 0) {
        setTimeout(newDroplet, 500);
    }
}

function initiate() {
    count = 30;
    newDroplet();
    timer = setInterval(function() {
        var allDrops = document.getElementsByClassName('drop'),
            newPosition;
        if (allDrops.length == 0) {
            clearInterval(timer);
            return;
        }
        for (var j = 0; j < allDrops.length; j++) {
            newPosition = allDrops[j].offsetTop + 2;   
            if (newPosition > allDrops[j].parentNode.offsetHeight) {
                allDrops[j].parentNode.removeChild(allDrops[j]);
            }
            else {
                allDrops[j].style.top = newPosition + 'px';
            }
        }
    }, 30);  
}​

Answer №2

This solution utilizes Javascript only!

        <script type="text/javascript">
var cleft;
var ctop;

var x=document.getElementById ('content');
function addRippleEffect (cleft,ctop,d)
{
    if (x==null) x="<div class='ripple' id='"+d+"' style='top:"+ctop+"px;left:"+cleft+"px'></div>";
    else x=x+"<div class='ripple' id='"+d+"' style='top:"+ctop+"px;left:"+cleft+"px'></div>";

    document.getElementById ('content').innerHTML=x;
}

function generateRandomNumber(from,to)
{
    return Math.floor(Math.random()*(to-from+1)+from);
}

var y=130;
var speed = 2;

function startDropletsAnimation ()
{
    if (y!=0){
        var a;
        var b;
        cleft=a;
        ctop=b;
        a=generateRandomNumber(20,1000);
        b=generateRandomNumber(10,500);
        addRippleEffect(a,b,y);
        y--;
    }

    // Move existing droplets
    for (var i=1; i<=130; i++)
    {
        var element = document.getElementById(i.toString());
        if (element !== null)
        {
            var topPosition = parseInt(element.style.top) + speed + i*.0125;
            if (topPosition > 500) 
                topPosition -= 500;
            element.style.top = topPosition + "px";
        }
    }

    setTimeout (function () {startDropletsAnimation ()},10);
}

</script>

Answer №3

Check out this cool animation: http://jsfiddle.net/CBv5K/

<html>
<head>
<style> 
#demo
{
background-color:blue;
width:2px;
height:6px;
position:relative;
animation:rain .5s;
-moz-animation:rain .5s; /* Firefox */
-webkit-animation:rain .5s; /* Safari and Chrome */
-o-animation:rain .5s; /* Opera */
}

@keyframes rain
{
0%   {top:0px;}
10%   {top:50px;}
20%   {top:100px;}
30%   {top:150px;}
40%   {top:200px;}
50%   {top:250px;}
60%   {top:300px;}
70%   {top:350px;}
80%   {top:400px;}
90%   {top:4500px;}
100%   {top:500px;}
}

@-moz-keyframes rain /* Firefox */
{
0%   {top:0px;}
10%   {top:50px;}
20%   {top:100px;}
30%   {top:150px;}
40%   {top:200px;}
50%   {top:250px;}
60%   {top:300px;}
70%   {top:350px;}
80%   {top:400px;}
90%   {top:4500px;}
100%   {top:500px;}
}
... (more code here) ...

This example only simulates one raindrop, but by adjusting the points you can make the rainfall look smoother with CSS animations.

Answer №4

Here are two examples that I found which may be helpful for you:
Create Special Rain and Cloud Effects On Page
Implement Hard Raining Effect on the Page
You can access the source codes for these effects as well as explore more related resources by searching within the website.


A user shared the source files required to achieve these effects:

<script type="text/javascript" src="http://htmlfreecodes.com/codes/rain.js">
</script>

and also

<script src="http://javascriptbestcodes.com/codes/cloudandrain.js"></script>

Answer №5

To create a dynamic effect, you can utilize the jQuery animate function to adjust the top position of the div.

Example Code:

<script>
        var cleft;
        var ctop;

        var x=document.getElementById ('content');
        function strop (cleft, ctop, d)
        {
            if (x==null) x="<div class='punct' style='top:"+ctop+"px;left:"+cleft+"px'></div>";
            else x=x+"<div class='punct' id='"+d+"' style='top:"+ctop+"px;left:"+cleft+"px'>    </div>";
            document.getElementById ('content').innerHTML=x;
        }

        function randomFromInterval(from, to)
        {
            return Math.floor(Math.random()*(to-from+1)+from);
        }

        var y=30;
        function start ()
        {
            if (y != 0){
                var a;
                var b;
                cleft=a;
                ctop=b;
                a=randomFromInterval (20,1000);
                b=randomFromInterval (10,50);
                strop(a, b, y);
                $("#"+y).animate({"top":"480px"},1000)
                setTimeout (function () {start ()},1100);
                y--;
            }
        }
</script>

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

Troubleshooting issues with a Node.js application on Azure App Service

Seeking assistance with deploying my first Node.js app on Azure App Service. Despite following Microsoft's guides and tutorials, my app is not functioning as expected. Although I can see my project in the Azure portal, when I attempt to access it via ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

What is the process for dynamically populating a select dropdown based on the selection made in another select dropdown?

I need to dynamically populate the second select box based on the option selected in the first select box. Here's what I have tried so far, but it doesn't seem to be working as expected. HTML: <form id="step1"> <p> Creat ...

Conflicting behavior between jQuery focus and blur functions and retrieving the 'variable' parameter via the $_GET method

There is a simple focus/blur functionality here. The default value shown in the 'Name of Venue' input field changes when the user clicks on it (focus) and then clicks away(blur). If there is no text entered, the default value reappears. Input fi ...

The function Slice() does not function properly when used with two-dimensional arrays

I have been attempting to duplicate a 2D array by value using the slice() method in order to prevent any changes made to the new array from impacting the original. Oddly enough, it seems that this approach is effective with a 1-dimensional array but not wi ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

Vue - when multiple parents share a common child component

Is there a way in Vue.js for multiple parents to share the same child component? I am looking to have multiple delete buttons trigger a single modal with different content. For example: myfile.html: <table id="app" class="table table-striped table-s ...

Misunderstanding the Variable Scope Concept in Node.js

I am struggling to comprehend why the return of an array from another function is confined to only one block of code. For example: exports.join = function(req, res){ User.findById(req.user._id, function(err, user) { var dupe = []; //placeholder arr ...

The $scope variable fails to reflect updates in the view following a broadcast event triggered by a

I have been troubleshooting a similar issue and I can't seem to figure out why the update is not reflecting in the view. While I am able to see the scope variable updating in the catch events logs, the changes are not being displayed in the view. For ...

Gracefully Switching Between Various Functions

Suppose I have a collection of functions that perform various tasks: function doSomething() { console.log('doing something'); } function accomplishTasks() { console.log('accomplishing tasks'); } function executeAction() { console. ...

Tips for increasing a variable by one with each button click?

I have a simple JavaScript function called plusOne() that is designed to increment a variable by 1 each time a button is clicked, and then display the updated value on a webpage. However, I'm encountering an issue where the addition only occurs once. ...

Is there a way to access the Express parameters within my React component?

Currently, I am in the process of developing a React application that utilizes Express as its back-end infrastructure My express route is configured as follows app.get('/manage/:id', (req, res) => { // redirect to react application }); ...

Ensure that nested DTO objects are validated using class validator

Currently, I am utilizing the class validator to validate incoming data which comprises an array of objects that need validation individually. An issue that has arisen is that despite inputting everything correctly, I keep encountering errors. It appears ...

Tips for utilizing the .clone() method within a loop or for each individual element of an array

Due to certain requirements, I find myself in a situation where I need to customize the invoice template within the software I use. The invoices are generated in HTML format, prompting me to consider utilizing Stylish and Grease Monkey for this task since ...

In JavaScript, a true statement does not trigger a redirect

<label>Username:</label> <input name="username" id="username" type="text" value="testuser"> <label>Password:</label> <input name="password" id="password" type="password" value="test123"> <input value="Submit" name="su ...

The Bootstrap alert refuses to close when the close button is clicked

I'm attempting to utilize a Bootstrap alert for displaying a warning. The alert automatically fades and dismisses after a period of time, but I want to provide the user with the option to manually close it. I've included jQuery and js/bootstrap.m ...

Simple guide on how to use AJAX (without jQuery) and PHP to count the number of records

As a novice programmer, I am attempting to tally the number of records in a table. Despite perusing various code snippets, I am unable to seamlessly integrate them to pass the PHP result to my javascript code. Here is the current state of my code: showsca ...

"Encountering issues with calling a Node.js function upon clicking the button

I'm facing an issue with the button I created to call a node.js server function route getMentions, as it's not executing properly. Here is the code for my button in index.html: <button action="/getMentions" class="btn" id="btn1">Show Ment ...

What methods can be used to protect (encrypt using Java code) the information in a login form before it is sent to a servlet for

One major concern I have involves sending encrypted data (encrypted before sending the request) to a servlet. I attempted to call a function that encrypts passwords as an example, but I encountered difficulty passing values from JavaScript to Java code in ...