why is my function evaluating to null?
#1
I started this project again from scratch, because my first attempt is complete junk and I want to do this right from the start.

I apologize for making another thread about this project, but the previous attempt I made absolutely failed and was complete garbage and I figured the right thing to do would be to start this project from scratch and so I hope I did a good job of asking a different question about my project.

So when I run this code I notice none of the functions run:

Code:
$(function() { // Makes sure that your function is called once all the DOM elements of the page are ready to be used.
   
    // Called function to update the name, happiness, and weight of our pet in our HTML
    checkAndUpdatePetInfoInHtml();
 
    // When each button is clicked, it will "call" function for that button (functions are below)
    $('.treat-button').click(clickedTreatButton);
    $('.play-button').click(clickedPlayButton);
    $('.exercise-button').click(clickedExerciseButton);
 

 
   
  })
 
    // Add a variable "pet_info" equal to a object with the name (string), weight (number), and happiness (number) of your pet
    var pet_info = {name:"Ryan", weight:"0", happiness:"0"};
 
    function clickedTreatButton() {
      // Increase pet happiness
      // Increase pet weight
      document.getElementById('happiness').innerText = parseInt(document.getElementById('happiness').innerText) + 1;
      document.getElementById('weight').innerText = parseInt(document.getElementById('weight').innerText) + 1;
      console.log("this code runs");
      checkAndUpdatePetInfoInHtml();
    }
   
    function clickedPlayButton() {
      // Increase pet happiness
      // Decrease pet weight
      document.getElementById('happiness').innerText = parseInt(document.getElementById('happiness').innerText) + 1;
      document.getElementById('weight').innerText = parseInt(document.getElementById('weight').innerText) - 1;
      console.log("this code runs");
      checkAndUpdatePetInfoInHtml();
    }
   
    function clickedExerciseButton() {
      // Decrease pet happiness
      // Decrease pet weight
      document.getElementById('happiness').innerText = parseInt(document.getElementById('happiness').innerText) - 1;
      document.getElementById('weight').innerText = parseInt(document.getElementById('weight').innerText) - 1;
      console.log("this code runs");
      checkAndUpdatePetInfoInHtml();
    }
 
    function checkAndUpdatePetInfoInHtml() {
      checkWeightAndHappinessBeforeUpdating(); 
      updatePetInfoInHtml();
    }
   
    function checkWeightAndHappinessBeforeUpdating() {
      // Add conditional so if weight is lower than zero, set it back to zero
    }
   
    // Updates your HTML with the current values in your pet_info dictionary
    function updatePetInfoInHtml() {
      $('.name').text(pet_info['name']);
      $('.weight').text(pet_info['weight']);
      $('.happiness').text(pet_info['happiness']);
    }
 

When I run it in my debugger, here's what I get:

Code:
TypeError: document.getElementById(...) is null2 [url=https://homework-9.glitch.me/script.js]script.js:22:74[/url]
    clickedTreatButton https://homework-9.glitch.me/script.js:22
    jQuery 2
    
    dispatch
    
    handle

So my question is why are all of my functions evaluating to null?

Thanks.
Reply
#2
(04-05-2020, 10:34 PM)QMark Wrote: So my question is why are all of my functions evaluating to null?

Well the next step in debugging an error... google.

take your debugger output and look for non-specific information.

For example, debugger output:


Code:
TypeError: document.getElementById(...) is null2 [url=https://homework-9.glitch.me/script.js]script.js:22:74[/url]
    clickedTreatButton https://homework-9.glitch.me/script.js:22
    jQuery 2
    
    dispatch
    
    handle

The relevant information is TypeError: document.getElementById(...) is null. Everything else is your url, your script name, your function name. Which other people won't have in their code. So throw that code straight into google, and you should have somewhere to start.
Reply
#3
(04-06-2020, 01:12 AM)MuddyBucket Wrote:
(04-05-2020, 10:34 PM)QMark Wrote: So my question is why are all of my functions evaluating to null?

Well the next step in debugging an error... google.

take your debugger output and look for non-specific information.

For example, debugger output:


Code:
TypeError: document.getElementById(...) is null2 [url=https://homework-9.glitch.me/script.js]script.js:22:74[/url]
    clickedTreatButton https://homework-9.glitch.me/script.js:22
    jQuery 2
    
    dispatch
    
    handle

The relevant information is TypeError: document.getElementById(...) is null. Everything else is your url, your script name, your function name. Which other people won't have in their code. So throw that code straight into google, and you should have somewhere to start.

When I made this thread I was about to add in that I had googled it and people with similar errors don't appear to have the same or very close problem with their programs.

But I am gonna finish this project tomorrow for certain because its due at 7PM tomorrow night and I cannot leave it until the last minute.

I need to keep working on JavaScript on code academy but honestly I think code academy teaches me more than my professor's class does long term and definitely is more rewarding in terms  of skill.

Anyways, here's my updated code because I realized that the error I gave was the wrong way of doing it:

Code:
$(function() { // Makes sure that your function is called once all the DOM elements of the page are ready to be used.
   
    // Called function to update the name, happiness, and weight of our pet in our HTML
    checkAndUpdatePetInfoInHtml();
 
    // When each button is clicked, it will "call" function for that button (functions are below)
    $('.treat-button').click(clickedTreatButton);
    $('.play-button').click(clickedPlayButton);
    $('.exercise-button').click(clickedExerciseButton);
 

 
   
  })
 
    // Add a variable "pet_info" equal to a object with the name (string), weight (number), and happiness (number) of your pet
    var pet_info = {name:"Ryan", weight:"0", happiness:"0"};
 
    function clickedTreatButton() {
      // Increase pet happiness
      // Increase pet weight
      document.querySelector(".happiness").innerHTML = document.querySelector(".happiness").innerHTML + 1;
      document.querySelector(".weight").innerHTML = document.querySelector(".weight").innerHTML + 1;
      console.log("this code runs");
      checkAndUpdatePetInfoInHtml();
    }
   
    function clickedPlayButton() {
      // Increase pet happiness
      // Decrease pet weight
    
      document.querySelector(".happiness").innerHTML = document.querySelector(".happiness").innerHTML + 1;
      document.querySelector(".weight").innerHTML = document.querySelector(".weight").innerHTML + 1;
      console.log("this code runs");
      checkAndUpdatePetInfoInHtml();
    }
   
    function clickedExerciseButton() {
      // Decrease pet happiness
      // Decrease pet weight
     
      document.querySelector(".happiness").innerHTML = document.querySelector(".happiness").innerHTML + 1;
      document.querySelector(".weight").innerHTML = document.querySelector(".weight").innerHTML + 1;
      console.log("this code runs");
      checkAndUpdatePetInfoInHtml();
    }
 
    function checkAndUpdatePetInfoInHtml() {
      checkWeightAndHappinessBeforeUpdating(); 
      updatePetInfoInHtml();
    }
   
    function checkWeightAndHappinessBeforeUpdating() {
      // Add conditional so if weight is lower than zero, set it back to zero
    }
   
    // Updates your HTML with the current values in your pet_info dictionary
    function updatePetInfoInHtml() {
      $('.name').text(pet_info['name']);
      $('.weight').text(pet_info['weight']);
      $('.happiness').text(pet_info['happiness']);
    }

In this case the code will run but it does not change the values on screen. I looked for that on google but get answers like this one that don't seem relevant:

https://stackoverflow.com/questions/4855...html5-code

I tested it in the debugger and it turns out the code inside the body of the function is running. But its not running the specific lines of code within the function corresponding to each button.

What do I do about this?
Reply
#4
To be honest, it's difficult to debug your code when you've only provided half of it. Where's the CSS and HTML? The original issue could have been something as simple as embedding the JS in the wrong spot, or a typo. Now I've got new code, no error, and there's no point in me coding something to use the script, if the error is in the HTML.
Reply
#5
(04-07-2020, 05:54 AM)MuddyBucket Wrote: To be honest, it's difficult to debug your code when you've only provided half of it. Where's the CSS and HTML? The original issue could have been something as simple as embedding the JS in the wrong spot, or a typo. Now I've got new code, no error, and there's no point in me coding something to use the script, if the error is in the HTML.

HTML:
Code:
<!DOCTYPE html>
<html>
  <head>
    <title>Your Giga Pet</title>
    <meta name="description" content="A cool thing made with Glitch">
    <link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="script.js" defer></script>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <header>
      <h1>
        This is your Giga Pet
      </h1>
    </header>

    <main>
      <section class="pet-image-container">
         <!-- Replace pet image with your own pet image -->
        <img class="pet-image" src="https://cdn.glitch.com/3aa98e05-3216-497c-a251-210ae4713a83%2Fhound.jpg?1541715339220">
      </section>
      <section class="dashboard">
        <div>Name: <strong><span class="name">Ryan</span></strong></div>
        <div>Weight: <strong><span class="weight"></span> pounds</strong></div>
        <div>Happiness: <strong><span class="happiness"></span> tail wags (per min)</strong></div>
        <div class="button-container">
          <button class="treat-button">
            Treat
          </button>
          <button class="play-button">
            Play
          </button>
          <button class="exercise-button">
            Exercise
          </button>
        </div>
      </section>
    </main>

    <!-- Your web-app is https, so your scripts need to be too -->
    <script src="https://code.jquery.com/jquery-2.2.1.min.js"
            integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00="
            crossorigin="anonymous"></script>
  </body>
</html>

CSS:

Code:
* {
    box-sizing: border-box;
  }
 
  body {
    font-family: helvetica, arial, sans-serif;
    margin: 25px;
  }
 
  main {
    display:block;
    height:175px;
  }
 
  header {
    border-bottom: 1px solid black;
  }
 
  h1 {
    font-weight: bold;
    color: #000;
  }
 
  .bold {
    font-weight: bold;
  }
 
  p {
    max-width: 600px;
  }
 
 
  li {
    margin-bottom: 5px;
  }
 
  footer {
    padding-top: 25px;
    border-top: 1px solid black;
  }
 
  footer a {
    float:left;
    margin:5px;
  }
 
  .pet-image {
    height:250px;
  }
 
  .dashboard div {
    display:block;
  }
 
  .pet-image-container {
    float:left;
    padding:10px;
  }
 
  .dashboard {
    float:left;
    padding:20px;
  }
 
  .button-container {
    margin-top:20px;
  }
 
  .button-container button {
    width: 100px;
      margin-right: 10px;
      text-align: center;
      display: inline-block;
      float: left;
    font-size:15px;
    background-color: #1e2835;
    border-color: #404853;
    cursor:pointer;
    background-image: linear-gradient(to bottom,rgba(246,246,246,.1)0%,rgba(30,40,53,0)66%);
    color: #fafafa;
  }

Does that help?
Reply
#6
Update!!!

Here's the jsfiddle for it:

https://jsfiddle.net/7bca4nve/
Reply
#7
Hi I got the code working. I just had to add and subtract directly to pet_info['happiness'] and pet_info['weight'].

I have a different problem with the same program but I am hoping I can get it fixed by tonight.
Reply
#8
Hey so sorry, I just now got 5 minutes to take a look at this. And I can't spend too much more time on it so I'm not going to beat around the bush and try to come up with hints. Your current issue appears to be this section of code:

Code:
    // Updates your HTML with the current values in your pet_info dictionary
    function updatePetInfoInHtml() {
      $('.name').text(pet_info['name']);
      $('.weight').text(pet_info['weight']);
      $('.happiness').text(pet_info['happiness']);
    }

It should be:

Code:
    // Updates your HTML with the current values in your pet_info dictionary
    function updatePetInfoInHtml() {
      $('.name').text(pet_info['.name']);
      $('.weight').text(pet_info['.weight']);
      $('.happiness').text(pet_info['.happiness']);
    }

This now updates your html page with the values. However you have a logic issue still. Instead of 1+1=2, you're getting 1+1=11. I don't have time to look at this right this moment... can do so in maybe an hour or two... but off the top of my head I would say it's probably pulling a "String" value from the html, so it assumes you're appending the String value of 1 to a string, it doesn't try to convert the string to an integer and add it by default. This is just a guess... I don't actually know/program in Javascript. There's probably a way to force, or cast, the string to an int - but l don't know it off the top of my head and don't have any more time right now to mess with it.

Also, JS fiddle has a neat feature, if you hover over the yellow dot next to the line it tells you whats wrong. It's how I found this first error so quickly. Took me longer to write this response than find the issue.
Reply
#9
(04-07-2020, 11:01 PM)MuddyBucket Wrote: Hey so sorry, I just now got 5 minutes to take a look at this. And I can't spend too much more time on it so I'm not going to beat around the bush and try to come up with hints. Your current issue appears to be this section of code:

Code:
    // Updates your HTML with the current values in your pet_info dictionary
    function updatePetInfoInHtml() {
      $('.name').text(pet_info['name']);
      $('.weight').text(pet_info['weight']);
      $('.happiness').text(pet_info['happiness']);
    }

It should be:

Code:
    // Updates your HTML with the current values in your pet_info dictionary
    function updatePetInfoInHtml() {
      $('.name').text(pet_info['.name']);
      $('.weight').text(pet_info['.weight']);
      $('.happiness').text(pet_info['.happiness']);
    }

This now updates your html page with the values. However you have a logic issue still. Instead of 1+1=2, you're getting 1+1=11. I don't have time to look at this right this moment... can do so in maybe an hour or two... but off the top of my head I would say it's probably pulling a "String" value from the html, so it assumes you're appending the String value of 1 to a string, it doesn't try to convert the string to an integer and add it by default. This is just a guess... I don't actually know/program in Javascript. There's probably a way to force, or cast, the string to an int - but l don't know it off the top of my head and don't have any more time right now to mess with it.

Also, JS fiddle has a neat feature, if you hover over the yellow dot next to the line it tells you whats wrong. It's how I found this first error so quickly. Took me longer to write this response than find the issue.

I know. I already saw the issue with it appending a 1 to the end of that and fixed the logic issue. The correct code is:

Code:
$(function() { // Makes sure that your function is called once all the DOM elements of the page are ready to be used.
   
    // Called function to update the name, happiness, and weight of our pet in our HTML
    checkAndUpdatePetInfoInHtml();
 
    // When each button is clicked, it will "call" function for that button (functions are below)
    $('.treat-button').click(clickedTreatButton);
    $('.play-button').click(clickedPlayButton);
    $('.exercise-button').click(clickedExerciseButton);
    $('.reset-button').click(clickedResetButton);
 

 
   
  })
 
    // Add a variable "pet_info" equal to a object with the name (string), weight (number), and happiness (number) of your pet
    var pet_info = {name:"Ryan", weight:0, happiness:0};
 
    function clickedTreatButton() {
      // Increase pet happiness
      // Increase pet weight
      pet_info['happiness']+=1;
      pet_info['weight']+=1;
      checkAndUpdatePetInfoInHtml();
    }
   
    function clickedPlayButton() {
      // Increase pet happiness
      // Decrease pet weight
      pet_info['happiness']+=1;
      pet_info['weight']-=1;
      checkAndUpdatePetInfoInHtml();
    }
   
    function clickedExerciseButton() {
      // Decrease pet happiness
      // Decrease pet weight
      pet_info['happiness']-=1;
      pet_info['weight']-=1;
      checkAndUpdatePetInfoInHtml();
    }


    function clickedResetButton() {
      // Decrease pet happiness
      // Decrease pet weight
      pet_info['happiness']=0;
      pet_info['weight']=0;
      checkAndUpdatePetInfoInHtml();
    }
 
    function checkAndUpdatePetInfoInHtml() {
      checkWeightAndHappinessBeforeUpdating(); 
      updatePetInfoInHtml();
    }
   
    function checkWeightAndHappinessBeforeUpdating() {
      // Add conditional so if weight is lower than zero, set it back to zero
      if (pet_info['happiness'] <= 0) {
        pet_info['happiness'] = 0;
      }
      if (pet_info['weight'] <= 0) {
        pet_info['weight'] = 0;
      }
    }
   
    // Updates your HTML with the current values in your pet_info dictionary
    function updatePetInfoInHtml() {
      $('.name').text(pet_info['name']);
      $('.weight').text(pet_info['weight']);
      $('.happiness').text(pet_info['happiness']);
      $('.reset').text(pet_info['reset']);
    }
Reply
#10
It appears to be working for me? Was there any outstanding issues?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to split this JS function into smaller ones of make function work? QMark 0 5,522 05-01-2020, 10:58 PM
Last Post: QMark
  why doesn't the howOld() function work? QMark 8 13,497 04-05-2020, 01:37 AM
Last Post: QMark
  Why learn PHP? Syntax 2 13,874 12-05-2015, 03:34 PM
Last Post: Syntax