-1

I am trying to get a very simple javascript project going, but I cannot get any function to execute. Here is a simple example. It is obviously just an example. I have tried everything I can think of to get the browser to recognize that I am trying to call a function that has been defined, but it never does anything but just display the text, rather than call anything. In the below example, I simply get a page with the text: "varTimesTwo(3);"

<!DOCtype html>
<html>
<body>

<script>
function varTimesTwo(oneVar){
    return (oneVar * 2)
}
</script>

varTimesTwo(3);
</body>
</html>
Paul
  • 26,170
  • 12
  • 85
  • 119

2 Answers2

1

your code is wrong, you have to place varTimesTwo(3); inside the script tag, like this:

 <!DOCtype html>
 <html>
  <body>    
  <script>
      function varTimesTwo(oneVar){
           return (oneVar * 2)
      }

       varTimesTwo(3);
   </script>
    </body>
</html>
  • Thank you for the prompt reply! However, this displays nothing. I'm trying to get the output of the function to display on page when loaded in a browser. – regexwhaaaaat Jan 31 '17 at 01:19
  • Try `document.write(varTimesTwo(3));` This tells the JavaScript interpreter to write the result of the function call into the document body. – asherber Jan 31 '17 at 01:23
0

Keep all JavaScript code in the script tags, or better yet, in a file separate from the html file using <script src="myjsfile.js"></script>

You can use document.write(string) to write a string to the document. This string is treated as HTML so you need to use <p>text</p> or <br> to get line breaks.

<!DOCtype html> 
<html>
<body>
<script> 
function varTimesTwo(oneVar){
     return (oneVar * 2) 
} 
document.write("3 times two is "+varTimesTwo(3));
</script>
</body> 
</html>

Alternatively, you can use window.alert(string) or simply alert(string) to pop up an alert box. But if you have turned off pop-ups in the browser, these will not pop up.

<!DOCtype html>
<html>
<body>
<script> 
function varTimesTwo(oneVar){
     return (oneVar * 2) 
} 
alert("3 times two is "+varTimesTwo(3));
</script>
</body> 
</html>

console.log(string) writes to the debugging console, which you can see on many browsers with either control-shift-J or F12.

The javascript debugging console is also useful for learning javascript without messing with input and output. Anything you type in the JS console is immediately executed, so you can define functions there and play with them without having to write additional code to write the output or read input.

Finally, these techniques are insufficient for most websites as they are actually used. Instead, what is done is to define an html container element and change the text or html that is inside. jQuery provides a browser-independent method of manipulating the document to change items on the page.

Community
  • 1
  • 1
Paul
  • 26,170
  • 12
  • 85
  • 119