What is the best way to add animation to my `<div>` elements when my website is first loaded?

I am looking for a way to enhance the appearance of my <div> contents when my website loads. They should gradually appear one after the other as the website loads. Additionally, the background image should load slowly due to being filtered by the weatherType. This is a webpage dedicated to local weather that provides real-time weather information based on the user's location.

Note:- To access the API, please share the code on third-party Web Development platforms like codepen.io.

Here's the Code:

$(document).ready(function() {
  $(".text-center").fadeIn();
            var lon, lat, weatherType, ftemp, ktemp, ctemp, wspeed;

            if (navigator.geolocation) {

                navigator.geolocation.getCurrentPosition(function(position) {
                        lon = position.coords.longitude;
                        lat = position.coords.latitude;
                        var api = 'https://api.openweathermap.org/data/2.5/forecast?lat=' + lat + '&lon=' + lon + '&appid=bb4b778076b0c8c79c7eb8fcd1fd4330';
                        $.getJSON(api, function(data) {
                            // $("#data").html(api);
                            var city = data.city.name;
                            weatherType = data.list[0].weather[0].description;
//weatherType="clear sky";
                            ktemp = data.list[0].main.temp;
                            console.log(ktemp);
                            ftemp = (9 / 5 * (ktemp - 273) + 32).toFixed(1);
                            ctemp = (5 / 9 * (ftemp - 32)).toFixed(1);
                            wspeed = data.list[0].wind.speed;
                            wspeed = (wspeed * 5 / 18).toFixed(1);
                            /* $("#city").addClass("animated fadein",function(){
 $("#city").html(city);
 }); */
 $("#city").addClass("animated fadein");
 $("#city").html(city);
                            $("#weatherType").html(weatherType);
                            $("#temp").html(ctemp + " &#8451;");
                            //$("[name='my-checkbox']").bootstrapSwitch();
                            $("#degree-toggle").attr("value", $("<div/>").html("&#8457;").text());
                            var celsius = true;
                            $("#degree-toggle").on("click", function() {
                                if (celsius === true) {
                                    $("#temp").html(ftemp + " &#8457;");
$("#temp").fadeIn();
                                    $("#degree-toggle").attr("value", $("<div/>").html("&#8451;").text());
                                    celsius = false;
                                } else {
                                    $("#temp").html(ctemp + " &#8451;");
$("#temp").fadeIn();
                                    $("#degree-toggle").attr("value", $("<div/>").html("&#8457;").text());
                                    celsius = true;
                                }
                            });
                            $("#wspeed").html(wspeed + " kmph");
weatherType=weatherType.toLowerCase();
                            if (weatherType === "clear sky")
                                $("body").css("background-image", "url('https://static.pexels.com/photos/281260/pexels-photo-281260.jpeg')");
                            else if (weatherType === "few clouds")
                                $("body").css("background-image", "url('https://clearalliance.org/wp-content/uploads/2015/01/CLEAR-see-clear-flowers-e1422658973500.jpg')");
                            else if (weatherType === "cloudy")
                                $("body").css("background-image", "url('http://www.gazetteseries.co.uk/resources/images/5360796/')");
else if (weatherType === "sunny")
    $("body").css("background-image","url('https://i2-prod.examiner.co.uk/incoming/article10372520.ece/ALTERNATES/s1227b/JS75768352.jpg')");
else if (weatherType==="showers")
    $("body").css("background-image","url('http://ak8.picdn.net/shutterstock/videos/1479838/thumb/1.jpg')");
                          else if(weatherType==="overcast clouds") 
                                $("body").css("background-image","url('https://patchegal.files.wordpress.com/2012/07/img_2406.jpg')");
                          else if(weatherType==="light rain")
                               $("body").css("background-image","url('https://i.ytimg.com/vi/LbAigABOm_E/maxresdefault.jpg')");
                        else
    $("body").css("background-image","url('https://www.almanac.com/sites/default/files/image_nodes/thanksgiving-weather.jpg')");
                        });
                    });
                }
            });
.text-center{
  display: none;
}
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&amp;lang=en" /><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>
     <div class="text-center" id="content">
      <div> <h1><b>Weather Today</b></h1></div><br/>
       <h2>Location : <span id="city"></span></h2> <br/>
       <h2>Weather : <span id="weatherType"></span></h2><br/>
       <h2>Temperature : <span id="temp">
     </span>
 <input type="button" id="degree-toggle"  checked="checked">
      </h2><br/>
     <h2>Wind Speed : <span id="wspeed"></span></h2><br/>
      </div>
    </body>
</html>

Answer №1

To create a seamless entry effect, I would incorporate animations instead of simply toggling element visibility.

Manually writing elements can be tedious and impractical, especially when dealing with a large quantity like 20 or even 1000.

Here is a basic framework to start with, which you can customize to fit your specific scenario:

HTML

<div id="elementsInThis">
  <div class="K">ELEMENT 1</div>
  <div class="K">ELEMENT 2</div>
  <div class="K">ELEMENT 3</div>
  <div class="K">ELEMENT 4</div>
  <div class="K">ELEMENT 5</div>
  <div class="K">ELEMENT 6</div>
  <div class="K">ELEMENT 7</div>
  <div class="K">ELEMENT 8</div>
  <div class="K">ELEMENT 9</div>
</div>

JS

var delay = 0;

function animate(element, delay){
    window.setTimeout(function(){
        element.style.display = 'block';
    }, delay*1000)
}

var elements = document.getElementById("elementsInThis").childNodes;
var onlydivs = Object.keys(elements).forEach(function(index, element){
    if (elements[element].nodeType !== Node.TEXT_NODE) 
    animate(elements[element], delay++);
});

CSS

.K{
  display: none;
  background: red;
  border: solid 2px black;
  animation-name: appear;
  animation-duration: 4s;
  animation-fill-mode: forwards;
}

@keyframes appear{from{left:-300px;opacity:0} to{left:0;opacity:1}}

See the implementation in action here:

js fiddle

Adjust the animation and delay according to your preferences, as well as bind them to your own parent element and select children more efficiently for complex scenarios. While this is a demonstration, the underlying principle remains the same:

  • Utilize CSS for animation effects and ensure default display of elements is set to none (consider using visibility depending on HTML structure)

  • Create a delay function with a set interval between each element's appearance

  • Use childNodes, forEach(), and Object.keys() to automate binding your CSS animation classes to elements

  • You can separate additional styling into different CSS classes if needed

Answer №2

Unfortunately, I won't be able to provide an exact solution right now as I'm preparing to leave. However, one approach you can take is to create a dedicated function for your animation feature. Within your script, you can then use setTimeout to assign specific delays to each element before displaying them. You can also incorporate transition or animation properties on the elements to enhance the visual effect.

CSS

.elements {
//place your CSS styles here
}

JS

//delay = time in milliseconds before showing, element = element to display.
function animateWithDelay(delay, element){
    window.setTimeout(function(){
        element.style.display = 'block';
    }, delay);
}

function initiateAnimation(){
     animateWithDelay(1000, el1); //first element shown after 1 second
     animateWithDelay(2000, el2); //second element shown after 2 seconds
     animateWithDelay(3000, el3); //third element shown after 3 seconds, and so on
}


window.onload = function(){ initiateAnimation(); };
//consider using jquery on() or addEventListener instead of overriding window.onload event.

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 and inserting multiple objects into a table in Sails JS while bypassing any existing rows

Is there a way to insert an array of objects into a table while avoiding duplicate rows? I have a model defined as follows: //Test.js module.exports={ tableName:'test', connection: 'mysqlServer', attributes:{ id:{ type: ...

Leverage Angular to highlight updated items within a list

My goal is to synchronize data, so I have a data object that holds the current state. Whenever this state changes, I want to mark the object with an attribute for filtering purposes during syncing. Here is the structure of the object: data = { type1: [ ...

streamlined method for accessing page parameters in nested components using the next.js application router

In my next.js application, I have a deep hierarchy of nested components. I currently use the params.lang parameter for translations, but I find myself passing it down to every nested component. Although there are hooks available, I prefer rendering them ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...

Integrating a Find Pano functionality into a Kolor Panotour

I used a program called Kolor to create a panorama. Now, I am attempting to integrate the "find pano" feature, which involves searching through the panoramic images for display purposes. I have come across an HTML file that contains the search functionalit ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

Are there any alternative methods to avoid duplication of Navbar link margin classes in Tailwind CSS?

It feels really repetitive to have to add margin classes to each LI manually on a non-dynamically generated menu. It almost seems as messy as using inline style attributes... Is there a more efficient way to handle this? While it may not be a big deal fo ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Update the button text dynamically when clicked without using an identifier or a class

If we take a look at my button in the following code: <input type="button" value="BLUE" name="button_blue" /> My goal is to have the value="BLUE" changed to value="RED" or any other desired value when the button is clicked. ...

Declaring module public type definitions for NPM in Typescript: A comprehensive guide

I have recently developed a npm package called observe-object-path, which can be found on GitHub at https://github.com/d6u/observe-object-path. This package is written in Typescript and has a build step that compiles it down to ES5 for compatibility with ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

Is there a way to access the value of a string variable with unicode characters from a different function than the one where it was originally defined?

Is there a way for me to access the 'result' variable outside of the initial function? The value of 'result' is a Unicode character like 'ﺏ' and I am still learning, so I could use some assistance. Thank you. Below is ...

Performing a double running of an Express GET request with an :id parameter

I'm working on an API using node and express, where the main aim is to capture the :id parameter from the request and store it in a variable. This will allow me to query a specific table in my SQLite database based on that particular id. However, I am ...

Looking for assistance in streamlining my jQuery code for bootstrap tab pane. Any takers?

Having trouble setting a specific tab as active when navigating from different links. I have found a solution, but it involves writing code for each individual tab. Can someone offer assistance in simplifying the code? <table class="nav nav-tabs"> ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

Pattern matching excluding "two or more" white spaces

Looking for a unique regular expression that meets the following criteria: No spaces allowed at the beginning or end of a line Only one space permitted between words The previous attempt using "^[АЯ-Ёа-яё0-9' ']+$" didn't q ...

Unable to change the value of selected items in checkbox event within a React context

Today marks the beginning of my journey into developing a React application. I am currently faced with the challenge of retrieving the row ID of a checked checkbox in a React table. Utilizing hooks, I have managed to transfer the states to another compone ...

I cannot understand why I keep receiving <input type="email" value="required"> when all I want is <input type="email" value="" required>

Currently, I am working with PHP code and here is my complete PHP code: echo "<input type=\"email\" class=\"profil_input_text form-control\" name=\"user_email\" pattern=\"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(& ...

Is TinyMCE creating unexpected <g> tags?

When I save content in the TinyMCE WYSIWYG editor, I notice that the HTML tag below keeps appearing throughout the text: <g class="gr_ gr_283 gr-alert gr_spell gr_run_anim gr_inline_cards ContextualSpelling ins-del multiReplace" id="283" data-gr-id="28 ...