Script Help for Webpage

This code is working great but I’d like to eliminate the need to click the “connect” button in order to populate the data to the webpage. When the webpage loads I’d just like it to automatically populate. Make sense? Any chance you could help me? Thank you!

<html>
<head>
  <title>
  </title>
</head>

<body>
  <br>
  <span id="current"></span><br>
  <span id="TempF"></span><br>
  <br>
  <button id="connectbutton" onclick="start()">Connect</button><br>
  <script type="text/javascript">
function start() {

    document.getElementById("connectbutton").innerHTML = "Waiting for data...";
    var deviceID = "x";
    var accessToken = "y";
    var eventSource = new EventSource("https://api.spark.io/v1/devices/" + deviceID + "/events/?access_token=" + accessToken);

     eventSource.addEventListener('open', function(e) {
        console.log("Opened!"); },false);

    eventSource.addEventListener('error', function(e) {
        console.log("Errored!"); },false);


    eventSource.addEventListener('current', function(e) {
        var parsedData = JSON.parse(e.data);
        var tempSpan = document.getElementById("current");
        tempSpan.style.fontSize = "28px";
        tempSpan.innerHTML = "Appliance Current: " + parsedData.data;
    }, false);
    eventSource.addEventListener('tempF', function(e) {
        var parsedData = JSON.parse(e.data);
        var tempSpan = document.getElementById("tempF");
        tempSpan.style.fontSize = "28px";
        tempSpan.innerHTML = "TemperatureF: " + parsedData.data;
    }, false);

  }
  </script><br>
</body>
</html>

Have you tried, before your start function:

window.onload = start;
1 Like

Thank you for the suggestion but unfortunately that's not working for me. Would you mind editing my code with your suggestion? I must be misplacing window.onload = start;

Thanks again!

Ok, so if I added the suggested window.onload = start; above the start function as recommended AND change out the .innerHTML with .style.visibility='hidden'; I get the data to load without the appearance of the button. :smile:

I'm sure there's got to be a much better way to go about this, but it does what I'm looking for. Thank you!

<script type="text/javascript">
window.onload = start;
function start() {

    document.getElementById("connectbutton") .style.visibility='hidden';

This is actually one of the most common ways to do this. The starting up, that is. Hiding the button on the other hand, is a bit useless. Why not just take it out, as in, delete that line? It’s not doing you any good when it’s hidden anyhow.