0

Sorry , this might be a stupid question but I dont really get why this won't work for me. I just want to be able to write the result from myitem in to a simple div. I have used a function onmouseover to get it to work. but that can't be neccessary. And i know how to show it in an alert.

But how do one get myitem to show in a div?

help is much appreciated!:)

<!DOCTYPE html>
<html lang="sv">

<head>
    <meta charset="utf-8">
    <title> class </title>

    <script>
        class item {
            constructor(name, price, quantity) {

                
                this.name = name;
                this.price = price;
                this.quantity = quantity;

            }
            
            sum() {
                return this.price * this.quantity;
            }
        }
        myitem = new item("apple", 10, 2);


        // This doesnt work //   document.getElementById("example1").innerHTML = myitem.sum();  
        // This doesnt work //        document.getElementById("example1").innerHTML = (myitem.sum());   

        
        //this down below works
         function myfunction () {
             
             document.getElementById("example2").innerHTML = myitem.sum();
         }

            // This works //     alert(myitem.sum());
    </script>
</head>

<body>

    <div id="example1"> example1 </div>
    <br/>
      <div id="example2" onmouseover="myfunction();"> example2 </div>

</body>

</html>
mqgajver
  • 39
  • 5
  • `
    example1
    ` isn't rendered by the time your script is running, see https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery
    – Mike S. Dec 18 '20 at 13:11
  • oh, so just because I had script before the "body" it was not runned as I wanted it to be ? thanks. I got it working for me now :) – mqgajver Dec 18 '20 at 13:16

1 Answers1

1

You aren't calling the function until the event happens, and the comments where it doesn't work is because you are running the script before the DOM is loaded. You can use the window event DOMContentLoadedwhich fires once the DOM is loaded or you can move your script to below your Html body, if you go with the window event DOMContentLoaded you can do something like the following:

class item {
        constructor(name, price, quantity) {
            
            this.name = name;
            this.price = price;
            this.quantity = quantity;

        }
        
        sum() {
            return this.price * this.quantity;
        }
    }
    myitem = new item("apple", 10, 2);


    //this down below works
     function myfunction () {             
         document.getElementById("example2").innerHTML = myitem.sum();
     }

     //wait for the DOM to load and then call the function
     window.addEventListener("DOMContentLoaded", function(){
         myfunction();
     });
Ryan Wilson
  • 7,490
  • 1
  • 17
  • 31