1

Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.

enter image description here

and here is how I am organizing these sections

<!DOCTYPE html>
<html lang = "en">
    <head>
        <title>HTML/CSS Responsive Theme</title>
        <meta charset = "utf-8">
        <link rel = "stylesheet" href = "main.css" type = "text/css">
        <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
        <script>

        function startFactorial(number)
        {
            function factorial(num)
            {
                if(num <= 1)
                    return 1;

                return num * factorial(num - 1);
            }
            document.factorials.factorialsfield.value = factorial(number);
        }

        function startMaxofFive(str)
        {
            //can actually find the max of n numbers not limited to 5
            function maxoffive(string)      
            {
                var nums = (string.match(/[-]?\d+/g));
                var b = nums.map(Number);
                return Math.max.apply(Math,b);
            }
            document.mof.moffield.value = (maxoffive(str));
        }
        </script>
    </head>
    <body>
        <section id = "first">
            <h3>Factorial</h3>
            <form name= "factorials">
                Enter a number <input type = "number" name = "factorialsfield" value = 0>
                <br><br>
                <input type = "button"  onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
            </form>
        </section>

        <br>

        <section id = "second">
            <h3>Max of Five Numbers</h3>
            <form name = "mof">
                Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
                <br><br>
                <input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
            </form>
        </section>

        <br>

        <section id = "third">
            <h3>Sum and Multiply</h3>
            <form name = "operations">
                Enter numbers to apply operations <input type = "text" name = "operationsfield"
            </form>
        </section>
    </body>
</html>

What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?

3
  • 1
    It's really unclear... what is "access those functions in my script without having to create another function" ?? For example?? Commented Mar 13, 2015 at 19:17
  • You shouldn't use screenshots to provide such informations. And if you need to make a screenshot, then make sure that you post only the relevant part and not all of your screens. Commented Mar 13, 2015 at 19:20
  • 1
    Sorry about that I posted in a hurry. I mean can I put the scripts in a separate place for the onclick event handlers to access? I only know how to use them by setting them equal to functions Commented Mar 13, 2015 at 19:27

4 Answers 4

1

Here's some suggestions:

  1. You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.

  2. Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }

  3. See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)

Example:

<form id="factorials" name="factorials">
    <!-- Skipping input -->
    <input type="submit" <!-- ... -> />
</form>

// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
    /* Your code here */
}
Sign up to request clarification or add additional context in comments.

3 Comments

awesome that bout sums up what I was looking for
Can I put the js file in separate file and have the src set to it? But put the script tag below the forms?
@user3043051 no, probably not using this event handler method. You can keep the script in the head and load the file though.
1

It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.

You can also move your scripts to a separate file and include it:

<script src="myscripts.js"></script>

This will help keep your code more neat and organized.

9 Comments

This doesn't work for events though, and I wouldn't consider this best practice
@Isaiah why do you believe that this won't work for events? Just moving the code into a js file without wrapping it into a function shouldn't change anything in the reachability of the functions.
Events have to be setup before a page loads; test it with an onclick event in any browser.
@Isaiah startFactorial(factorialsfield.value) of onClick="startFactorial(factorialsfield.value)" is evaluated a the time when the click happens so it doesn't matter.
@Isaiah I agree that the placement of script tags at the bottom is not considered a best practice ( but it is mistaken for one by people who excessively use js frameworks) but I have to disagree with event handler setup. That has to occur after the Dom has been parsed enough to actually have access to the relevant elements.
|
1

You always use functions to call functions. Sounds weird but thats how it is :P

You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:

<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>

Sorry if I understood your question wrong

1 Comment

Another technique is element_variable.event() , except that overrides an old event for the same element defined this way.
1

I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.

I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).

https://angularjs.org/

But this is just one of many options!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.