1

I have to create an HTML page following certain guidelines. I am not asking anyone to do my homework for me but I am stuck on the first part.

Create and Initialize three arrays. Use for-loops to populate those arrays. Add an element to the end of one array.

I have created 2 arrays and used a pop element. But when I open the .htm it populates correctly but when pressing create it does the second part of my code. How do I separate the scripts?

<!DOCTYPE HTML>
   <html>
   <head>
   <title>Testing JavaScript for Loop</title>
   </head>

   <body>

   <p>The pop method removes the last element from an array.</p>

    <button onclick="myFunction()">Create</button>
    <button onclick="pop()">Pop</button>

    <p id="demo"></p>

    <script>


    var fruits = ["Banana", " Orange", " Apple", " Mango"];

    var newFruits = [];

    document.getElementById("demo").innerHTML = newFruits;

    function myFunction() {
        for (var i in fruits) {
            newFruits.push(fruits[i])
        }
        document.getElementById("demo").innerHTML = newFruits;
    }

    function pop() {
        newFruits.pop();
        document.getElementById("demo").innerHTML = newFruits;
    }
</script>


<br>
  <p>This one needs to add and element to the beginning.</p>

    <button onclick="myFunction()">Create</button>
    <button onclick="pop()">This button needs to add to beginning</button>

    <p id="veggie"></p>

<script>    


    var veggies = ["Broccoli", " Carrots", " Cucumber", " Beans"];

    var newVeggies = [];

    document.getElementById("veggie").innerHTML = newVeggies;

    function myFunction() {
        for (var i in veggies) {
            newVeggies.push(veggies[i])
        }
        document.getElementById("veggie").innerHTML = newVeggies;
    }

/*need this to put an element at the beginning of the list */

    function pop() {
        newVeggies.pop();
        document.getElementById("veggie").innerHTML = newVeggies;
    }
    </script>     





      </body>
    </html>
2
  • I don't think its being understood right. The first section of fruits doesn't work. If I push create it will do the bottom code where veggies is. I am trying to make them two separate happenings, one for fruits that removes the last one, then one for veggies that adds one to the beginning. Sorry if I didn't state the objective clearly. Commented Jun 17, 2015 at 19:09
  • Look at my answer. That is why. Commented Jun 17, 2015 at 19:09

4 Answers 4

1

Use return; before your function is closed, also put functions in head section.

Something like this :

   <html>
   <head>
   <title>Testing JavaScript for Loop</title>
   <script>
    function myFunction() {
        for (var i in fruits) {
            newFruits.push(fruits[i])
        }
        document.getElementById("demo").innerHTML = newFruits;
        return;
    }

    function pop() {
        newFruits.pop();
        document.getElementById("demo").innerHTML = newFruits;
        return;
    }
   </script>
   </head>

   <body>

   <p>The pop method removes the last element from an array.</p>

    <button onclick="myFunction()">Create</button>
    <button onclick="pop()">Pop</button>

    <p id="demo"></p>

    <script>
    var fruits = ["Banana", " Orange", " Apple", " Mango"];
    var newFruits = [];
    document.getElementById("demo").innerHTML = newFruits;
    </script>
</html>
Sign up to request clarification or add additional context in comments.

4 Comments

The functions are fine at the end of the body; this is a best practice, as it will wait for the DOM is loaded before executing any scripts without an onload handler.
Actually as you are saying it, DOM will not be fully loaded as there will be at least </HTML> after them, scripts being executed without being triggered by an event are matter for another story.
On top of what @JoshBeam said, I think its better to JS at the bottom of the html file anyway because of the way HTML is loaded. It will load the contents at the top of the file before things at the bottom. By putting scripts at the bottom, the content gets loaded first, giving the appearance of faster load times. this is especially tru in regards to separate .js files
HTML5 doesn't require an <html> tag, so it would be irrelevant to script execution. So as far as the JS is concerned, the DOM will be fully loaded. stackoverflow.com/a/5642982/2714730
1

Name you functions differently. by declaring myfunction() twice, JavaScript uses the last one. If you define the first function as fruits_myfunction() and the second as veggie_myfunction() you won't get this collision any more. It's not a matter of separating it. JavaScript's scoping is basically this: everything is global. Even if you where to separate the functions into separate files, you would still get this collision.

5 Comments

where do you see myfunction() declared twice?
@MladenOršolić Scroll down in the box. after <p id="veggie"></p>
Oh didnt even see the remaining part. Yep in this case youre absolutely right.
Cancel the first one I wrote, I found the missing spot, now the (Fruit) Pop button removes the (veggie) last in line and leaves the (fruit) top alone.
Make sure you also change the onclick attribute to also point to the new functions.
0

Following should work,

<!DOCTYPE HTML>
   <html>
   <head>
   <title>Testing JavaScript for Loop</title>
   </head>

   <body>

   <p>The pop method removes the last element from an array.</p>

    <button onclick="createFruits()">Create</button>
    <button onclick="popFruit()">Pop</button>

    <p id="demo"></p><br>
  <p>This one needs to add and element to the beginning.</p>

    <button onclick="createVeggies()">Create</button>
    <button onclick="popVegie()">This button needs to add to beginning</button>

    <p id="veggie"></p>

<script>    

    var fruits = ["Banana", " Orange", " Apple", " Mango"];

    var newFruits = [];

    document.getElementById("demo").innerHTML = newFruits;

    function createFruits() {
        for (var i in fruits) {
            newFruits.push(fruits[i])
        }
        document.getElementById("demo").innerHTML = newFruits;
    }

    function popFruit() {
        newFruits.pop();
        document.getElementById("demo").innerHTML = newFruits;
    }

    var veggies = ["Broccoli", " Carrots", " Cucumber", " Beans"];

    var newVeggies = [];

    document.getElementById("veggie").innerHTML = newVeggies;

    function createVeggies() {
        for (var i in veggies) {
            newVeggies.push(veggies[i])
        }
        document.getElementById("veggie").innerHTML = newVeggies;
    }

/*need this to put an element at the beginning of the list */

    function popVegie() {
        newVeggies.unshift("Brinjal");
        document.getElementById("veggie").innerHTML = newVeggies;
    }
    </script>     

      </body>
    </html>

First, never have two functions with the same name, javaScript is different than that of other languages(e.g., Java) where you have the luxury of method overloading. In case of two methods having same name, the second method in the code sequence will be executed when we talk of javaSript

Second, put all your custom javaScript code inside one <script> tag, preferably at the end of body, i.e., before "</body>" tag.

Third, even better practice is to put all ur custom javaScript code in a ".js" file and include it as,

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

This helps maintain all ur js code in a single file. Note, the path in the src attribute should be proper (relative path will do).

Fourth and final point, wonder why you are popping an element when you need to add it to the beginning of array. You should use unshift() operation.

Hope this helps.

1 Comment

This helped me so incredibly much, I appreciate it emmensely! I have unjumbled all of my code and now it reads and flows nicer! You are my savior!
0

Assuming your file structure is:

/index.htm

Create a file called index.js for example.

Paste in the contents of the script tag:

var fruits = ["Banana", " Orange", " Apple", " Mango"];

var newFruits = [];

document.getElementById("demo").innerHTML = newFruits;

function myFunction() {
    for (var i in fruits) {
        newFruits.push(fruits[i])
    }
    document.getElementById("demo").innerHTML = newFruits;
}

function pop() {
    newFruits.pop();
    document.getElementById("demo").innerHTML = newFruits;
}

Now your structure is

/index.htm
/index.js

In the htm file change the script tag to be:

<script type="text/javascript" src="/index.js">

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.