I need help with JavaScript

Since the javascript is embedded in the HTML that was then run on the browser, you will only see console logs in the browser console. To get console logging in the visual code terminal, you would have to run the server-side applications which is out of scope in this course.

Hope this clears the confusion. :slight_smile:

Happy Learning!

2 Likes

Hello @enrico, hope you are great.

I’ve checked your code, looks good but I might need your html code to test it correctly, my console does not show any error on your code, thats why i want to see your html code.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Hello thanks a lot for your time!

the program works fine while using START and STOP button. The problem is with CLEAR button (which i would like to reset the timer so it can start back from zero.
When I click CLEAR timer stop and show zero BUT when I click START the timer start from where it was stopped and not from 0).

I don’t understand why since at the click of button CLEAR i stop the setInterval() and set seconds, minutes, etc to zero)

`$("#clear").click(function(){
  clearInterval(x)
  var s = 0;
  var m = 0;
  var h = 0;
  var d = 0;
  document.getElementById("timer").innerHTML = d + "d " + h + "h "
  + m + "m " + s + "s ";
  s += 1;


});`

This is the complete code

<!DOCTYPE html>
<html>


    <head>
        <meta charset="utf-8">
        <title>MY PAGE</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


        <style>

        body {

          background: url(https://cdn.pixabay.com/photo/2018/05/28/12/09/time-3435879_1280.jpg);
          font-family: Arial, sans-serif;
          font-size: 20px;
        }

        p{
          position: relative;
          right: 80px;
          font-size: 50px;
          font-weight: 900;
          text-align: right;
          color: #fff;
        }

        h1{

          position: relative;
          left: 40px;

          font-weight: bolder;
          font-size: 60px;
          font-weight: 900;
          margin-left;
          color: #fff;
        }

        button{
          padding: 20px 60px;
          border-radius: 3px;
          position: relative;
          left: 40px;
          font-size: 20px;
          background-color: #fff;
          color: 	#fec4c3;
          border-width: 0px;
          border-color: white;
          font-weight: 900;

        }

        </style>

    </head>
    <body>

      <h1> TIMER </h1>

      <p id="timer" ></p>

      <button class="start" id="start">START</button><br>
      <button class="stop" id="stop">STOP</button>
      <button class="clear" id="clear">CLEAR</button>

    <script>

    // define seconds, minutes etc to 0
    var s = 0;
    var m = 0;
    var h = 0;
    var d = 0;

      var x;

    // on click start the timer (if timer was stopped it keeps the values so when started again it continues)
    $("#start").click(function(){


  if(x>0){
  clearInterval(x);
  }
    // function to repeat every second
    x= setInterval(function() {

    // update seconds, minutes etc
    if(s >= 59 && m >= 59 && h >= 23){

    d += 1;
    h = 0;
    m = 0;
    s = 0;
    document.getElementById("timer").innerHTML = d + "d " + h + "h "
    + m + "m " + s + "s ";
    }

    else if(s >= 59 && m >= 59){

    h += 1;
    m = 0;
    s = 0;
    document.getElementById("timer").innerHTML = d + "d " + h + "h "
    + m + "m " + s + "s ";
    }

    else if(s >= 59){

    m +=1;
    s = 0;
    document.getElementById("timer").innerHTML = d + "d " + h + "h "
    + m + "m " + s + "s ";
    }

    else {
    document.getElementById("timer").innerHTML = d + "d " + h + "h "
    + m + "m " + s + "s ";
    s += 1;

    }


  }, 1);
// onclick stop the repeat of the function -> stop the timer
$("#stop").click(function(){clearInterval(x);});

$("#clear").click(function(){
  clearInterval(x)
  var s = 0;
  var m = 0;
  var h = 0;
  var d = 0;
  document.getElementById("timer").innerHTML = d + "d " + h + "h "
  + m + "m " + s + "s ";
  s += 1;


});


  });


     </script>
    </body>
</html>

Thanks again!

The error is in your clear function, you had declared your variables s, m, h, d as global variables (beginning of your script code), but in your function, you declared them again, if you delete the var keyword from them, it will work now.

You are declaring the same variables in your function, so they are being taken as internal variables of your function, so basically your function will not “reset” the value of the first global variables, it will just create 4 internal variables of the same name.

So when you click the start button, your start function will continue with the last value of the global variables s, m, h, d.

$("#clear").click(function(){
  clearInterval(x)
//reset global variables
  s = 0;
  m = 0;
  h = 0;
  d = 0;
  document.getElementById("timer").innerHTML = d + "d " + h + "h "
  + m + "m " + s + "s ";
  s += 1;


});

Hope you find this useful.
If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

thank you so much :slight_smile: now finally I got it!

1 Like

Hi Mauro,

This is really neat! I don’t see it in Atom, what is this you’re showing us?

I wanted to say to someone: I did the first javascript exercise with great success: the indenting and bulleting of the list, it looks just like Ivan’s :smiley:

Onward all!

1 Like

Hi Guys. I’m just wondering: In exercise 4 the answer says: “run your script”. I don’t know how to open the Javascript file so that it shows on the HTML website. How do I do that? I managed to do it the first time but I can’t repeat the process. Can anyone show me how?

Hi Guys. Can anyone tell me how to convert the Javascipt on your file to the HTML on your website? I don’t know how to do that again. I only did it once. I'm Stuck

Hi @JCrypto,

You need to create a HTML file first. In this HTML file, you need to have two such tags
<script> //my javascript code <script>

Between these two tags, you need to put your javascript code. Then you can go ahead and open the HTML file in your browser and the script will run automatically.

Hope this clears the doubt.

Happy Learning! :smiley:

1 Like

Thanks.

I just want to clarify: When I am doing the exercises that require me to print to the consul, am I supposed to be working from the chrome browser or the atom app. If I’m working from the atom app, then how do I ensure that what I write in the Atom file goes into the consul? I can’t link the two together.

2 Likes

You need to ‘run’ the javascript in a browser. If using chrome you can right click on the browser window and choose ‘inspect’. You will see a tab for the console which records anything that you console.log.

You either then need to load or reload your html file and the output will be displayed as below.

You can leave the console open and load different files via the browser file/open file option.

The file I ran was just this code.

<html>
<script>
	console.log("Hello World!");
</script>
</html>

You can just put the name of the javascript file between the tags also like this if the script is in the same directory as the html file. There would normally be other html, this is just to run simple javascript code.

<html>
<script src="test.js"></script>
</html>
1 Like

Hi @JCrypto,

Hope you’re having a great day.

You won’t see console logs in your atom console. The only way you can see it is if you run a local node server and console log through it which is out of the scope of this course.

If you have your JS file with all your javascript code, you need to place it in a HTML file and then open the HTML file in your browser. Thus, no matter how big your Javascript code is, we can see all the outputs on the chrome console.

Find below code for reference

My HTML –

<html>

<head>
    <title>This example of using form to add item to array comes from IvanOnTech JS course.</title>
    <script src="/Users/malik/Downloads/myJscode.js"></script> //your js file location on your desktop
</head>

<body>

    <h1>My favorite fruits</h1>

    <input class="fruitInput" type="text" placeholder="add fruit">
    <button>Add</button>

    <ol class="fruitList">
    </ol>
</body>

</html>

My JS file (myJscode.js) –

const listValues = [120, 4, 9, 7, 2, 8, 3, 1, 1100];
var lowestValue = listValues[0];
var highestValue = listValues[0];
// console.log(lowestValue)
for (num in listValues) {
    num = Number.parseInt(num)
    if (listValues[num] < lowestValue) {
        lowestValue = listValues[num]
    }
}
console.log(lowestValue)

for (num in listValues) {
    num = Number.parseInt(num)
    if (listValues[num] > highestValue) {
        highestValue = listValues[num]
    }

}
console.log(highestValue)

So, the conclusion is, no matter how big the project, in the end, we always inject our JS code into the HTML code for the browser to read it and execute it. The only way we can execute JS files outside of HTML and browser is through a node server instance (you will learn it in advance courses).

Hope this helps. Happy Learning! :smile:

1 Like

What is the difference between parseFloat and parseInt?

Question regarding quizes. I am using CodePen for the JS quizes and excercises. Should I be using Atom as Jason format?

var x=prompt(“Insert the value of bread:”);

var y=prompt(“Insert the value of Milk:”);

var s=prompt(“Insert the value of Chees:”);

var z=prompt(“Insert the value of Tougrt:”);

var e=(x+y+s+z);

console.log(“Shopping tour price:”+“€”+e);

Shopping tour price:€1234…with x=1 y=2…s=3…z=4

  • / and - works in the equation but not +
    somb know ?

Hi all,

I had posted this on the beginners and help area but actually think this is a better place for it.

I’m working on my first project in my course progression and have chosen to make a rock, paper, scissors game in Javascript.

I can get the computer to randomly select an option, and I’ve managed to get the buttons on the page to link to the relevant options, but I can’t get the score to update. The array elements aren’t being updated by the code in the playRound function, but the display is correct (I can manually modify the array in the console and the page will update when I next press a button). Any ideas about what I’m missing?

The code is below:

<html>
<head>

  <title> Rock, Paper, Scissors </title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href=https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css>

    <style>

    body{
      display: flex;
      flex-direction: column;
      align-items: center;
      align-content: center;
    }

    #playerScore, #computerScore{
      display: inline-block;
    }

    </style>


</head>

  <body>

    <h1 style="margin-top:100px;font-size:80px;"> Arena </h1>

    <div style="margin:20px;">
      <p style="font-size:40px;" id="playerScore"><strong> Player </strong> 0 </p>
      <p style="font-size:40px;" id="computerScore"> 0 <strong> Computer </strong> </p>
    </div>

    <div style="font-size:30px;">
      <button style= "background-color: white;" id="rockButton"> Rock </button>
      <button style= "background-color: white;" id="paperButton"> Paper </button>
      <button style= "background-color: white;" id="scissorsButton"> Scissors </button>
    </div>

    <div style='font-size:40px;' class='score'>

    </div>
    <div style='font-size:40px; margin-top:20px;' class='message'>

    </div>

    <div style="font-size:20px; margin-top:20px;" class="victor">

    </div>

      <script>

const choices = ['Rock','Paper','Scissors'];
const buttons = document.querySelectorAll('button');
const message = document.querySelector('.message');
const score = document.querySelector('.score');
const scores = [0,0];

for (let i = 0 ; i < buttons.length ; i++){
    buttons[i].addEventListener('click', playGame);
}

function playGame(e){
  let playerChoice = e.target.innerText;
  let computerChoice = choices[Math.floor(Math.random()*choices.length)];

  //on button click, computer should select random number
  //random number is converted to rock/paper/scissors via array index

  //function playRound tested successfully in console (with manually entered choices)
  //scoring doesn't work properly

  function playRound(playerChoice, computerChoice) {
    if (playerChoice === computerChoice){
      document.getElementById("victor").innerHTML = "It's a tie!";
    }
    else if (playerChoice === 'Rock'){
      if (computerChoice === 'Paper'){
        document.getElementById("victor").innerHTML = 'you lose! Paper beats Rock!';
        scores[1] += 1;
      }
      else {
        document.getElementById("victor").innerHTML = 'you win! Rock beats Scissors!';
        scores[0] += 1;
      }
    }
    else if (playerChoice === 'Paper'){
      if (computerChoice === 'Scissors'){
        document.getElementById("victor").innerHTML = 'you lose! Scissors beats Paper!';
        scores[1] += 1;
      }
      else{
        document.getElementById("victor").innerHTML = 'you win! Paper beats Rock!';
        scores[0] += 1;
      }
    }
    else {
      if (computerChoice === 'Rock'){
        document.getElementById("victor").innerHTML = 'you lose! Rock beats Scissors!';
        scores[1] += 1;
      }
      else{
        document.getElementById("victor").innerHTML = 'you win! Scissors beats Paper!';
        scores[0] += 1;
      }
    }
  }
  document.getElementById("playerScore").innerHTML = '<strong> Player </strong>' + scores[0] ;
  document.getElementById("computerScore").innerHTML = scores[1] + '<strong> Computer</strong>';
  //output player and computer's selections
  messenger('<strong>' + playerChoice + '</strong> VS <strong>' + computerChoice + '</strong><br>');
  }

  function messenger(selectionMessage){
  message.innerHTML = selectionMessage;
  }


    </script>

  </body>

</html> 

Thanks in advance,

Ciaran

Hey @sto, hope you are great.

now try to define your e variable on 0 first, then add the other values to it.

var e = 0
var e =+ (a+b+c+d)
console.log(e)

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Hey @Ciaran, hope you are great.

You have a nested function (playRound inside playGame) this could lead into issues with you variables playerChoice and computerChoice, I suggest to separate them, playRound should be outsite and invoce it inside playGame maybe. Also too many IF and Else could be not the best case, have you think to use a swtich instead?

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Thanks very much for the help!! That got it working :slight_smile:

Hi Ciaran,

I think there are two issues, possibly three.

  1. You’ve declared the playRound function within a function and I don’t think it’s being called. If I insert a console.log(a line number) just below the function statement it doesn’t log anything to the console. I think all that is happening is that part of the code is completely bypassed until you output the player and computer selection.
  2. Your “victor” id is a class in your html. It needs to be an id if getElementById is to set any text in it.
  3. I couldn’t really follow your if, else if, else though they may work if you remove the function statement and the enclosing { and }. I made it work this way.
if(condition a === something && condition b === something else)
{
    update score and message;
}
else if (condition a === something && condition b === another  thing)
{
    update score and message;
}

I messed about with it for a bit and I think this works or it did before I pasted it in!

Hope that helps

Funkmaster JH :grin:

<html>
<head>

  <title> Rock, Paper, Scissors </title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href=https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css>

    <style>

    body{
      display: flex;
      flex-direction: column;
      align-items: center;
      align-content: center;
    }

    #playerScore, #computerScore{
      display: inline-block;
    }

    </style>


</head>

  <body>

    <h1 style="margin-top:100px;font-size:80px;"> Arena </h1>

    <div style="margin:20px;">
      <p style="font-size:40px;" id="playerScore"><strong> Player </strong> 0 </p>
      <p style="font-size:40px;" id="computerScore"> 0 <strong> Computer </strong> </p>
    </div>

    <div style="font-size:30px;">
      <button style= "background-color: white;" id="rockButton"> Rock </button>
      <button style= "background-color: white;" id="paperButton"> Paper </button>
      <button style= "background-color: white;" id="scissorsButton"> Scissors </button>
    </div>

    <div style='font-size:40px;' class='score'>

    </div>
    <div style='font-size:40px; margin-top:20px;' class='message'>

    </div>

    <div style="font-size:20px; margin-top:20px;" id="victor">I'm here</div>

      <script>

const choices = ['Rock','Paper','Scissors'];
const buttons = document.querySelectorAll('button');
const message = document.querySelector('.message');
const score = document.querySelector('.score');
const scores = [0,0];

for (let i = 0 ; i < buttons.length ; i++){
    buttons[i].addEventListener('click', playGame);
}

function playGame(e){
  let playerChoice = e.target.innerText;
  let computerChoice = choices[Math.floor(Math.random()*choices.length)];
console.log(66);
  //on button click, computer should select random number
  //random number is converted to rock/paper/scissors via array index

  //function playRound tested successfully in console (with manually entered choices)
  //scoring doesn't work properly

  console.log(74);
    if (playerChoice === computerChoice)
    {
    console.log("Tie");
      document.getElementById("victor").innerHTML = "It's a tie!";
    }
    else if (playerChoice === 'Rock' && computerChoice === 'Paper')
    {
    	console.log("Lose, paper beat rock");
        document.getElementById("victor").innerHTML = 'you lose! Paper beats Rock!';
        scores[1] += 1;
    }
    else if (playerChoice === 'Rock' && computerChoice === 'Scissors')
    {
        document.getElementById("victor").innerHTML = "you win! Rock beats Scissors!";
        scores[0] += 1;
    }
    else if (playerChoice === 'Paper' && computerChoice === 'Scissors')
    {
        document.getElementById("victor").innerHTML = 'you lose! Scissors beats Paper!';
        scores[1] += 1;
    }
    else if (playerChoice === 'Paper' && computerChoice === 'Rock')
    {
        document.getElementById("victor").innerHTML = 'you win! Paper beats Rock!';
        scores[0] += 1;
    }
    else if (playerChoice === 'Scissors' && computerChoice === 'Rock')
    {
    	document.getElementById("victor").innerHTML = 'you lose! Rock beats Scissors!';
        scores[1] += 1;
    }
    else 
    {
    	document.getElementById("victor").innerHTML = 'you win Scissors beats Paper!';
    	scores[0] += 1;
    }
  
  document.getElementById("playerScore").innerHTML = '<strong> Player </strong>' + scores[0] ;
  document.getElementById("computerScore").innerHTML = scores[1] + '<strong> Computer</strong>';
  //output player and computer's selections
  messenger('<strong>' + playerChoice + '</strong> VS <strong>' + computerChoice + '</strong><br>');
  }


  function messenger(selectionMessage){
  message.innerHTML = selectionMessage;
  }


    </script>

  </body>

</html> 

1 Like