Need Java Script help!

  • 1
  • Question
  • Updated 2 years ago
  • Answered
Archived and Closed

This conversation is no longer open for comments or replies and is no longer visible to community members.

I found this outstanding weather pen: https://codepen.io/socrates/pen/waYPXx. The problem is that it displays some default location weather (Westport) and offers the option to input your desired location. I need it to display different default location that I would enter from the 'back.'

I stripped HTML/CSS a bit to leave only what' necessary. If anyone with JS skill could fix that location 'issue,' it would be greatly appreciated:

(the entire code)
<!doctype html><html>
<head>
<meta charset="utf-8">
<title>Weather New</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"; type="text/javascript"></script>
<style>
@import url('http://fonts.googleapis.com/css?family=Roboto:400,300,100');
@import url('https://cdnjs.cloudflare.com/ajax/libs/weather-icons/1.3.2/css/weather-icons.min.css');

h1,
h2,
h3,
h4 {
color: white;
font-family: 'Roboto';
font-weight: 100;
line-height: 1.1;
letter-spacing: 0.025em;
margin: 0; padding: 0;
}
a {
color: white;
opacity: 0.54;
text-decoration: none;
}
a:hover,
.active {opacity: 1;}

.wrapper {
width: 480px;
margin: 0 auto;
}
.searchbar,
.button {
height: 45px;
margin: 1em 0 4em;
padding: 0;
font: 400 1rem 'Roboto';
letter-spacing: 0.025em;
text-transform: uppercase;
color: white;
border: none;
}
.searchbar {
float: left;
width: 380px;
border-bottom: solid thin white;
color: #E8E8E8;
color: rgba(255, 255, 255, 0.7);
}

.searchbar::-webkit-input-placeholder {color: white; opacity: 0.35;}
.searchbar::-moz-placeholder {color: white; opacity: 0.35;}
.searchbar:-ms-input-placeholder {color: white; opacity: 0.35;}
.searchbar:-moz-placeholder {color: white; opacity: 0.35;}

.button:focus,
.searchbar:focus {outline: none; color: white;}
.searchbar:focus::-webkit-input-placeholder {color: white; opacity: 0.7;}
.searchbar:focus::-moz-placeholder {color: white; opacity: 0.7;}
.searchbar:focus:-ms-input-placeholder {color: white; opacity: 0.7;}
.searchbar:focus:-moz-placeholder {color: white; opacity: 0.7;}

.button {
float: right;
width: 100px;
}
.panel {
width: 100%;
display: inline-block;
}
.weather {
width: 100%;
margin-top: 20px;
display: inline-block;
}
.city {
text-align: left;
border-bottom: solid thin white;
text-transform: uppercase;
color: #E8E8E8;
color: rgba(255, 255, 255, 0.7);
}
.group {
width: 165px;
margin-bottom: 20px;
text-align: right;
float: right;
clear: both;
}
.temp {
font-size: 4.5em;
font-weight: 300;
line-height: 0.75;
}
.celsius,
.fahrenheit,
.divider {
font-size: 1.75rem;
vertical-align: super;
}
.divider {
margin: 0 0.05em;
}
.forecast {
display: table;
text-transform: uppercase;
width: 100%;
}
.block {
display: table-cell;
padding: 1.5em 0 0 0;
text-align: center;
}
.high {
font-weight: 300;
margin: 0.25em 0;
}

.secondary {opacity: 0.7;}
.transparent {background: transparent;}
.hot {background: #FF5722;}
.warm {background: #FF6F00;}
.cool {background: #2196F3;}
.cold {background: #3F51B5;}
.color404 {background: #161616;}
.button-hot {background: #BF360C;}
.button-warm {background: #B34E00;}
.button-cool {background: #0D47A1;}
.button-cold {background: #1A237E;}
.button404 {background: black;}
</style>
<script>
function titleCase(str) {
  str = str.split(' ');
  var length = str.length;
  for (var i = 0; i < length; i++) {
    str[i] = str[i][0].toUpperCase() + str[i].substring(1);
  }
  return str.join(' ');
}

function fullDay(str) {
  if (str === 'Tue') str = 'Tuesday';
  else if (str === 'Wed') str = 'Wednesday';
  else if (str === 'Thu') str = 'Thursday';
  else if (str === 'Sat') str = 'Saturday';
  else str = str + 'day';
  return str;
}

$(function() {
  
  var $wrapper = $('.wrapper'),
    $panel = $wrapper.find('.panel'),
    $city = $panel.find('#city'),
    $weather = $panel.find('.weather'),
    $group = $panel.find('.group'),
    $dt = $group.find('#dt'),
    $description = $group.find('#description'),
    $wind = $group.find('#wind'),
    $humidity = $group.find('#humidity'),
    $temperature = $weather.find('#temperature'),
    $temp = $temperature.find('#temp'),
    $icon = $temp.find('#condition'),
    $tempNumber = $temp.find('#num'),
    $celsius = $temp.find('#celsius'),
    $fahrenheit = $temp.find('#fahrenheit'),
    $forecast = $weather.find('#forecast'),
    $search = $wrapper.find('search'),
    $form = $search.find('form'),
    $button = $form.find('#button');

  $.ajax({
      dataType: 'json',
      url: 'http://ip-api.com/json'
    })
    .then(function(data) {
      var yourLocation = data.city + ',' + data.zip + ',' + data.countryCode;
      getWeather(yourLocation);
    });

  function getWeather(input) {

    var appid = '58b6f7c78582bffab3936dac99c31b25';
    var requestWeather = $.ajax({
      dataType: 'json',
      url: 'http://api.openweathermap.org/data/2.5/weather',
      data: {
        q: input,
        units: 'imperial',
        appid: appid
      }
    });
    var requestForecast = $.ajax({
      dataType: 'json',
      url: 'http://api.openweathermap.org/data/2.5/forecast/daily',
      data: {
        q: input,
        units: 'imperial',
        cnt: '6',
        appid: appid
      }
    });

    $fahrenheit.addClass('active').removeAttr('href');
    $celsius.removeClass('active').attr("href", '#');
    $icon.removeClass();
    $button.removeClass().addClass('button transparent');

    requestWeather.done(function(data) {

      var weather = document.getElementById('weather');
      if (data.cod === '404') {
        $city.html('city not found');
        setBackground('color404', 'button404');
        weather.style.display = 'none';
      } else weather.style.display = '';

      var dt = new Date(data.dt * 1000).toString().split(' ');

      $city.html(data.name + ', ' + data.sys.country);
      $tempNumber.html(Math.round(data.main.temp));
      $description.html(titleCase(data.weather[0].description));
      $wind.html('Wind: ' + data.wind.speed + ' mph');
      $humidity.html('Humidity ' + data.main.humidity + '%');
      $dt.html(fullDay(dt[0]) + ' ' + dt[4].substring(0, 5));

      $celsius.on('click', toCelsius);
      $fahrenheit.on('click', toFahrenheit);

      function toCelsius() {
        $(this).addClass('active').removeAttr('href');
        $fahrenheit.removeClass('active').attr('href', '#');
        $tempNumber.html(Math.round((data.main.temp - 32) * (5 / 9)));
      }

      function toFahrenheit() {
        $(this).addClass('active').removeAttr('href');
        $celsius.removeClass('active').attr("href", '#');
        $tempNumber.html(Math.round(data.main.temp));
      }

      function setBackground(background, button) {
        $('body').removeClass().addClass(background);
        $button.off().hover(function() {
          $(this).removeClass('transparent').addClass(button);
        }, function() {
          $(this).removeClass().addClass('button transparent');
        });
      }

      if (data.main.temp >= 80) setBackground('hot', 'button-hot');
      else if (data.main.temp >= 70) setBackground('warm', 'button-warm');
      else if (data.main.temp >= 60) setBackground('cool', 'button-cool');
      else setBackground('cold', 'button-cold');

      switch (data.weather[0].icon) {
        case '01d':
          $icon.addClass('wi wi-day-sunny');
          break;
        case '02d':
          $icon.addClass('wi wi-day-sunny-overcast');
          break;
        case '01n':
          $icon.addClass('wi wi-night-clear');
          break;
        case '02n':
          $icon.addClass('wi wi-night-partly-cloudy');
          break;
      }

      switch (data.weather[0].icon.substr(0, 2)) {
        case '03':
          $icon.addClass('wi wi-cloud');
          break;
        case '04':
          $icon.addClass('wi wi-cloudy');
          break;
        case '09':
          $icon.addClass('wi wi-showers');
          break;
        case '10':
          $icon.addClass('wi wi-rain');
          break;
        case '11':
          $icon.addClass('wi wi-thunderstorm');
          break;
        case '13':
          $icon.addClass('wi wi-snow');
          break;
        case '50':
          $icon.addClass('wi wi-fog');
          break;
      }
    });

    requestForecast.done(function(data) {

      $celsius.on('click', toCelsius);
      $fahrenheit.on('click', toFahrenheit);

      var forecast = [];
      var length = data.list.length;
      for (var i = 1; i < length; i++) {
        forecast.push({
          date: new Date(data.list[i].dt * 1000).toString().split(' ')[0],
          fahrenheit: {
            high: Math.round(data.list[i].temp.max),
            low: Math.round(data.list[i].temp.min),
          },
          celsius: {
            high: Math.round((data.list[i].temp.max - 32) * (5 / 9)),
            low: Math.round((data.list[i].temp.min - 32) * (5 / 9))
          }
        });
      }

      function toCelsius() {
        doForecast('celsius');
      }

      function toFahrenheit() {
        doForecast('fahrenheit');
      }

      function doForecast(unit) {
        var arr = [];
        var length = forecast.length;
        for (var i = 0; i < length; i++) {
          arr[i] = ("<div class='block'><h3 class='secondary'>" + forecast[i].date + "</h3><h2 class='high'>" + forecast[i][unit].high + "</h2><h4 class='secondary'>" + forecast[i][unit].low + "</h4></div>");
        }
        $forecast.html(arr.join(''));
      }

      doForecast('fahrenheit');
    });
  }

  $form.submit(function(event) {
    var input = document.getElementById('search').value;
    var inputLength = input.length;
    if (inputLength) getWeather(input);
    event.preventDefault();
  });

});
</script>
</head>

<body>
<div class="wrapper">
  <div class="panel">
    <h2 class="city" id="city"></h2>
    <div class="weather" id="weather">
      <div class="group secondary">
        <h3 id="description"></h3>
      </div>
      <div class="group secondary">
        <h3 id="wind"></h3>
        <h3 id="humidity"></h3>
      </div>
      <div class="temperature" id="temperature">
        <h1 class="temp" id="temp"><i id="condition"></i> <span id="num"></span><a class="fahrenheit active" id="fahrenheit" href="#">&deg;F</a><span class="divider secondary"></span></h1>
      </div>
      <div class="forecast" id="forecast"></div>
    </div>
  </div>
</div>
</body>
</html>
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb

Posted 2 years ago

  • 1
Photo of Wendi Borden

Wendi Borden, Champion

  • 6,028 Points 5k badge 2x thumb
Hey Darius,

Not sure for certain what you're looking for here.. I copied your code and hosted it and it looks nice. It's displaying my current city (without touching it) correctly. What is it you're trying to do here? It looks like it's using http://ip-api.com/json to get my location, and you could change it there if you wanted. Where do you want the default to come from (the 'back')?
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb
Wendi, I do not get my location by default. It shows some Westport, US location. The only way to get mine is to type it in (I removed this feature as I do not need it; I want it to show my location be default; this feature is in the original pen code). I was using 'simpleWeather' widget before where I manually typed in my ZIP in the code. But that widget is very unreliable and fails to get data quite often, which results in an error message. So, I was hoping to be able to do something similar with this one; simply get an option to input my location manually within the code.

UPDATE: I tried the code above at home and it did better. I got my location displayed automatically. Apparently my browser was blocking my location. I am gonna try this with an actual display at work next week. In a way I do not like it after all. I need it to be more controlled; therefore, I still prefer manual input over automatic. But thank you Wendi very much for your help. This code looks very nice and has useful features. I am hoping to switch over to this one when location issue gets resolved.
(Edited)
Photo of Wendi Borden

Wendi Borden, Champion

  • 6,028 Points 5k badge 2x thumb
If you just want to tell it in the JavaScript what to display.. (if I understand correctly?) edit this little bit:

//Comment out the call to ip-api.com
/*  $.ajax({
      dataType: 'json',
      url: 'http://ip-api.com/json'
    })
    .then(function(data) {
      //var yourLocation = data.city + ',' + data.zip + ',' + data.countryCode;
 var yourLocation = 'Cookeville,38501,US';
      getWeather(yourLocation);
    });
*/

//Fill in your own location. Format is city,zip,country
//Not sure how crazy you can get here, but it worked fine for the 2 cities I tried
  var yourLocation = 'Livingston,38570,US';
  getWeather(yourLocation);
(Edited)
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb
THIS!!! it worked! Thank you Wendi, I really appreciate that. Now I see background changing colors according to the temperature (I suppose). Will take a look at this next week at work.
Photo of Wendi Borden

Wendi Borden, Champion

  • 6,028 Points 5k badge 2x thumb
Awesome :) No prob! The ip-api.com call is retrieving your location based off your external IP address. You can just type in the browser too to see quite a bit of info (it's kinda neat). It's right a lot of the time, but not always. I'm in Eastern TN and one of our work IPs represents itself as California *lol*
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb
Need some little JS help again.

I have this working very well:

<script> var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth(),
    day = date.getUTCDate(),
hours = date.getHours(),
minutes = date.getMinutes(),
    months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];


document.getElementById('month').innerHTML = months[month];
document.getElementById('year').innerHTML = year;
document.getElementById('day').innerHTML = day;
document.getElementById('hours').innerHTML = hours;
document.getElementById('minutes').innerHTML = minutes;
</script>

What I trying to achieve is having separate DIVs to show certain values of the date. This would works for 24h format. But I need this to work with 12h format as well. For that I am missing AM PM value. Ideally, I would love having this on it is own in a separate DIV. Adding AM PM value to minutes would also do.

I have tried this an that, but nothing worked.
Photo of Robb

Robb, Official Rep

  • 76,676 Points 50k badge 2x thumb
Darius,

Unfortunately I can't offer much assistance on custom code. Let's hope Wendi can save the day like last time!
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb
Ignore it! I just found some major flaw with this code. I am working on the new version of it.
Photo of Wendi Borden

Wendi Borden, Champion

  • 6,028 Points 5k badge 2x thumb
Awe and I was just going to take a breather from work to have a look.. hehe :)
If you find you still need something, feel free to post. I'll see if I can help :)
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb
Wendi, I like this code because it is simpler from the other examples I have. If you really want and do not mind, then I still need AM PM versions. Also, the major flaw is that it does not refresh automatically. It just keeps showing the last refresh time. If you think you can fix those then go ahead. It still can be useful. And promise to post the final presentation code. It is interesting.
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb
Cool, I've got it working now:

<script type="text/javascript">var tday=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var tmonth=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function GetClock(){
var d=new Date();
var nyear=d.getFullYear();
var nmonth=d.getMonth();
var nday=d.getDay();
var ndate=d.getDate();
var nhour=d.getHours();
var nmin=d.getMinutes();
var nsec=d.getSeconds(),ap;

if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}

if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;

document.getElementById('yearbox').innerHTML=nyear;
document.getElementById('monthbox').innerHTML=tmonth[nmonth];
document.getElementById('monthbox').innerHTML=tmonth[nmonth];
document.getElementById('datebox').innerHTML=ndate;
document.getElementById('hourbox').innerHTML=nhour;
document.getElementById('minbox').innerHTML=nmin+ap;
}

window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>

But there is still a tiny bump. How do I make it to put "0" in front of single digit hour or minute values? So it shows, for example, "03" instead of "3"
(Edited)
Photo of Darius - PRODO.us

Darius - PRODO.us, Champion

  • 26,850 Points 20k badge 2x thumb
LOL the answer was right there in the code:

if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;

 All I needed is to add a couple more lines:

if(nmin<=9) nmin="0"+nmin;
if(ndate<=9) ndate="0"+ndate;
if(nhour<=9) nhour="0"+nhour;
if(nsec<=9) nsec="0"+nsec;

 All is working now just as I wanted! Man, I am better at this then I thought I was ))))
(Edited)