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

Understanding how to utilize and manipulate this JSON data using JavaScript

In my code, there is a variable that contains the following data: { "Rows": [ { "New":1, "CachedNumberType":0, "Date":1327479615921, "Type":2, "Number":"123456", "Duration ...

Disabling the current date on date pickers in material ui: A step-by-step guide

In my current React project, I am utilizing material-ui-date-pickers and need to prevent users from selecting today's date. This is important in the context of manufacturing products, managing expiration dates, and handling billing processes. Since a ...

What is the most effective way to retrieve distinct values in Mongoose?

I am looking to extract unique values from a collection. Here is an example: const userID = `user1`; const users = await Chat .find({'$or': [{to: userID}, {from: userID}]}) .select(`-_id to from`) .lean(); // users will contain: [ {from: ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

How to disable or enable a submit button in jQuery 1.8

Recently, I upgraded from jquery version 1.5.2 to 1.9 and encountered an issue with my disabled buttons not functioning properly. The buttons should become enabled after the form fields are filled out, allowing the user to either remove or save the infor ...

Ways to eliminate a particular element from the React state

I need help removing a specific item from my React state. Current scenario: When certain checkboxes are selected, I update their state accordingly. My useEffect hook has the checkboxes state as its dependency, and every time there is a change, I add cont ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

Storing values globally in NodeJS from request headers

What is the most effective way to store and access the value from a request header in multiple parts of my application? One approach could be as shown in the following example from app.js: app.get('*', (req, res) => { global.exampleHeader ...

Error message 'Access is Denied' occurs when using Angular.js xhr.open()

Currently, I am developing an angular web application that needs to be compatible with IE10. One of the requirements is to make a cross-domain call to our enterprise salesforce server. When using Chrome (not officially supported but commonly used for devel ...

What is the proper file format for a form action in CSS?

What I Currently Have: In my Index.html file, there are a total of 4 form elements including text fields and a dropdown. Upon submission by the user, the data is processed in confirm.html using a separate JavaScript file for formatting before being displa ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Is there a way to dynamically adjust @keyframes properties through JavaScript?

I am looking to dynamically change the top value of the keyframes based on a JavaScript variable x. While I have experience changing CSS with JavaScript, this particular challenge has me stumped. Code: var x = Math.floor((Math.random() * 1080) + 1); ...

A guide on incorporating jQuery alert messages into Angular 2

Whenever I submit a form by clicking on the "send message" button, I want to display an Alert message using jQuery. However, currently, I have to double click for the alert message to appear. How can I make it so that the alert message is shown with just o ...

Transition smoothly between images using CSS in a continuous loop

Is it possible to create a looped fade effect between images using only CSS, without the use of JavaScript? I attempted to achieve this by utilizing keyframes but was unable to succeed. Any guidance or assistance would be greatly appreciated. Thank you! ...

What is the best way to apply a class to a jQuery element only if a specific condition is met, and then remove it if the condition is no longer

Is there a more concise method to accomplish the same task? const selectAllCheckbox = $("input.select_all"); const isChecked = selectAllCheckbox.prop("checked"); isChecked ? selectAllCheckbox.parent().addClass("selected") : selectAllCheckbox.parent().r ...

Keep an ear out for socket.io within an Angular application

I am trying to connect socket.io with my angular application. I have come across some examples of creating a service that can be accessed by the controller, and I understand that part. However, I am looking for a solution where all controllers can respond ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

How to programmatically close a Liferay dialog box

I am currently dealing with a Liferay dialog box. My goal is to close this dialog box and then redirect the URL to a specific page. This is how I am attempting to achieve it: <aui:column columnWidth="16" > <%if(UserGroupRoleLocalServiceUtil.has ...

Visual Studio Code encounters a Node.js error stating "Module not found"

I have been struggling to run my Node.js program in VSCode. Despite trying various solutions found on StackOverflow, none of them seem to be working for me. I even attempted the Json file method, but unfortunately, that didn't work either. internal/mo ...

What are some ways to troubleshoot the UI of a Nativescript app?

As a newcomer to NativeScript technology, I often encounter challenges while developing applications. Whether it's troubleshooting why a textview is not displaying properly, identifying layout overlaps, or detecting other distortions in the UI, debugg ...