Search code examples
javascriptyahoo-api

How to call yahoo weather api javascript function from within a html doc


When placed in the head or body section of a html doc, these scripts immediately write to the document. How can I call their functionality from a button in the document. I have tried all the usual methods of calling a js function but none work. Please help, many thanks.

<script>
  var callbackFunction = function(data1) {
    var windy = data1.query.results.channel.wind;
    //alert(windy.chill);
document.write("Wind chill factor:" + windy.chill);

  };

</script>

<script src="https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='chicago, il')&format=json&callback=callbackFunction"></script>

Solution

  • Take a look at this code. I get the wind chill and store it in a variable. Then, I use the onclick attribute of a button to put that value in a div. Does this help?

    <script>
    var wind_chill;
      var callbackFunction = function(data) {
        var wind = data.query.results.channel.wind;
        wind_chill = wind.chill;
      };
      
    function get_wind_chill(){
      document.getElementById('wind_chill').innerHTML = "Wind chill factor:" + wind_chill;
    }
    </script>
     
    <script src="https://query.yahooapis.com/v1/public/yql?q=select wind from weather.forecast where woeid in (select woeid from geo.places(1) where text='chicago, il')&format=json&callback=callbackFunction"></script> 
    
    <div id="wind_chill"></div>
    <input type="button" onclick="get_wind_chill();" value="Get wind chill" />

    Note: This gets the wind chill when the page loads. If you need to get a new wind chill each time the button is clicked (without doing a page reload) then you will need to modify the above code.