Search code examples
javascriptjqueryhtmlrefresh

failed to refresh DIV with JavaScript


I want to auto-refresh of certain DIV (darksky widget id="1") in 10 seconds.

I tried many times but failed. please see below and comment what is logical wrong.

here my poor code.

function autoRefresh_sample_div2() {
  var currentLocation2 = window.location;
  $("#1").fadeOut('slow').load(currentLocation2 + ' #1').fadeIn("slow");
}
setInterval('autoRefresh_sample_div2()', 10000); //10 seconds
<div class="row col-lg-9">
  <div class="col-lg-1">
    <table class="table">
      <thead class="thead-dark">
        <tr>
          <th scope="col" style="text-align: center">#</th>
        </tr>
      </thead>
    </table>
  </div>
  <div class="col-lg-8 mb-2">
    <table class="table">
      <thead class="thead-dark">
        <tr>
          <th scope="col" style="text-align: center">Graph</th>
        </tr>
      </thead>
    </table>
  </div>
  <div class="col-lg-3 mb-2">
    <table class="table">
      <thead class="thead-dark">
        <tr>
          <th scope="col" style="text-align: center">Weather NOW</th>
        </tr>
      </thead>
    </table>
  </div>
  <div class="col-lg-1 my-auto">
    <h1 class="display-4 text-center">1</h1>
  </div>
  <div class="col-lg-8"><iframe class="embed-responsive embed-responsive-21by9" src="http://naver.com/"></iframe></div>
  <div class="col-lg-3 my-auto" id="1">
    <script type='text/javascript' src='https://darksky.net/widget/default-small/36.2385,127.2047/ca12/en.js?width=100%&height=70&title=Full Forecast&textColor=333333&bgColor=FFFFFF&transparency=false&skyColor=undefined&fontFamily=Default&customFont=&units=ca'></script>
  </div>

</div>


Solution

    1. Not recommended to have numeric IDs
    2. Your load does not re-execute the iframe script from the weather channel

    So I took the weather JS and looked to see what it did.

    I added their expected ID to your div and then reload the script with a random value to stop the caching instead of loading your whole page and extracting the div from it.

    I tried to attach to the "load" event of the head to fade in, but I use a timeout instead

    const weather = new URL('https://darksky.net/widget/default-small/36.2385,127.2047/ca12/en.js?width=100%&height=70&title=Full Forecast&textColor=333333&bgColor=FFFFFF&transparency=false&skyColor=undefined&fontFamily=Default&customFont=&units=ca');
    
    const reloadWeather = () => {
      $('script[id="weather"]').remove();
      weather.searchParams.set("rdn", new Date().getTime());
      $('<script id="weather">').attr('src', weather).appendTo('head');
      setTimeout(() => { $("#customize-script-container").fadeIn("slow") },1000) ;
    };
    
    let tId;
    $(function() {
      tId = setInterval(() => {
        $("#customize-script-container").fadeOut('slow', reloadWeather)
      }, 10000);
      reloadWeather()
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="row col-lg-9">
      <div class="col-lg-1">
        <table class="table">
          <thead class="thead-dark">
            <tr>
              <th scope="col" style="text-align: center">#</th>
            </tr>
          </thead>
        </table>
      </div>
      <div class="col-lg-8 mb-2">
        <table class="table">
          <thead class="thead-dark">
            <tr>
              <th scope="col" style="text-align: center">Graph</th>
            </tr>
          </thead>
        </table>
      </div>
      <div class="col-lg-3 mb-2">
        <table class="table">
          <thead class="thead-dark">
            <tr>
              <th scope="col" style="text-align: center">Weather NOW</th>
            </tr>
          </thead>
        </table>
      </div>
      <div class="col-lg-1 my-auto">
        <h1 class="display-4 text-center">1</h1>
      </div>
      <div class="col-lg-8"></div>
      <div class="col-lg-3 my-auto" id="customize-script-container"></div>
    
    </div>

    To have more than one weather channel, you have to get an API key, write a server side call with the key OR hack their code.

    The JS file contains the following

    var customContainer = document.getElementById("customize-script-container");
    if(customContainer === null)
      document.write("<iframe id='ds_b75d85c2dee419f1bfdd9ce0243df27f' type='text/html' frameborder='0' height='70' width='100%' src='https://darksky.net/widget/default-small/36.2385,127.2047/ca12/en?domain="+encodeURIComponent(window.location.href)+"&auth=1581324702_72b56ef770251e4ad0661834a512e6e9&width=100%25&amp;height=70&amp;title=Full%20Forecast&amp;textColor=333333&amp;bgColor=FFFFFF&amp;transparency=false&amp;skyColor=undefined&amp;fontFamily=Default&amp;customFont=&amp;units=ca'></iframe>");
    else
      document.getElementById("customize-script-container").innerHTML = "<iframe id='ds_b75d85c2dee419f1bfdd9ce0243df27f' type='text/html' frameborder='0' height='70' width='100%' src='https://darksky.net/widget/default-small/36.2385,127.2047/ca12/en?domain="+encodeURIComponent(window.location.href)+"&auth=1581324702_72b56ef770251e4ad0661834a512e6e9&width=100%25&amp;height=70&amp;title=Full%20Forecast&amp;textColor=333333&amp;bgColor=FFFFFF&amp;transparency=false&amp;skyColor=undefined&amp;fontFamily=Default&amp;customFont=&amp;units=ca'></iframe>";
    

    That is bad news for us, since they use document.write. I wanted to bypass that but came up with a cooler solution: Just rename each div when updating

    let tId, $divs, cnt = 0;
    
    const reloadWeather = () => {
      const $div = $(divs[cnt]);
      $('script[id="weather"]').remove();
      $("#customize-script-container").prop("id", "temp"); // rename the last div
      $div.prop("id", "customize-script-container"); // set the ID expected of the script
      const lat = $div.data("lat");
      const long = $div.data("long");
      let weather = new URL(`https://darksky.net/widget/default-small/${lat},${long}/ca12/en.js?width=100%&height=70&title=Full Forecast&textColor=333333&bgColor=FFFFFF&transparency=false&skyColor=undefined&fontFamily=Default&customFont=&units=ca`);
      weather.searchParams.set("rdn", new Date().getTime());
      $('<script id="weather">').attr('src', weather).appendTo('head');
      setTimeout(() => {
        $div.fadeTo("slow","1")
      }, 1000);
    };
    
    
    $(function() {
      divs = $(".weather");
      tId = setInterval(() => {
        if (cnt >= divs.length) cnt = 0;
        const $div = $(divs[cnt]);
        if ($div) {
          $div.fadeTo("slow",0, function() {
            reloadWeather();
            cnt++;
          })
        } else {
          console.log("div", cnt, "not found")
        }
      }, 10000);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <div class="col-lg-3 my-auto weather" data-lat="36.2385" data-long="127.2047"></div>
    <div class="col-lg-3 my-auto weather" data-lat="55.1234" data-long="100.1234"></div>