Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I give my `<div>` elements a animation entry when my website loads

I want my <div> contents to make a smooth entry when my website loads. They have to start appearing one after the other when the website loads. And also, the background image loads late as it is filtered by the weatherType. This is a localWeather webpage which gives you the weather information based on where you open the page.

Note:- Please post the code on other third party Web Development sites like codepen.io to access the API.

Here is my 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>
like image 308
Gaurav Thantry Avatar asked Jan 24 '18 08:01

Gaurav Thantry


2 Answers

First I would use animations to achieve smooth entry, not only switch elements to visible.

Second I wouldn't write elements manually, what if you have 20 of them? What about 1000?

Start with a frame like this then adjust to your case:

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}}

Here you can see it in action:

js fiddle

Modify animation and delay to your liking, also bind to your own parent and make a better selecor of children if you have more complex ones. This is just a demo but principle is the same you do the following:

  • You wanna leverage CSS to make proper (or find someone else's) animation and set default display of element to none (might wanna use visibility instead if your HTML breaks apart)

  • make a delay function with fixed delay step (i used step 1 * 1000 ms)

  • leverage childNodes forEach() and Object.keys() to avoid manually binding your CSS class with animation to elements

  • you can have rest of the style in different CSS class if you like

like image 192
DanteTheSmith Avatar answered Oct 13 '22 14:10

DanteTheSmith


While I cannot give you an exact answer as I'm about to go home. What you can do is dedicate a separate function for your animation feature. Then in your script, you will each assign a setTimeout event for each element, giving each of them a specific delay before showing. Then you can add a transition or animation property on your element.

CSS

.elements {
//css here
}

JS

//delay = time in ms before show, element = element to show.
function letAnimate(delay, element){
    window.setTimeout(function(){
        element.style.display = 'block';
    }, delay);
}

function startAnimate(){
     letAnimate(1000, el1); //your first element which will show 1s after function call
     letAnimate(2000, el2); //2nd element, will show after 2s
     letAnimate(3000, el3); //3rd, 3s, so forth so on
}


window.onload = function(){ startAnimate(); };
//make this jquery on() or addEventListener.
//You don't want this function to override window.onload event.
like image 25
Abana Clara Avatar answered Oct 13 '22 13:10

Abana Clara