George Stoyanov
George Stoyanov

Reputation: 21

Two functions running at page load

I am trying to merge two functions in one file. The result will be when the page is loaded to run the functions and the result to appeared on the defined divs. If someone can tell me what I am doing wrong I will be really grateful.

function Calc(){
  var a;
  var b;
  var c;
  
  a=1;
  b=2;
  
  c=a+b;
  
  $("#FirstDiv").html(c);
}

function Name(){
   var Name;
   Name = "George";
  
  $("#SecondDiv").html(Name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="FirstDiv"></div>
<div id="SecondDiv"></div>

Upvotes: 1

Views: 74

Answers (3)

onepopcorn
onepopcorn

Reputation: 36

As others have told you the problem is that you are not calling the functions.

But consider converting each function into a IIFE This way you prevent global scope pollution (i.e. attaching functions to window or document scope) and execute the functions as soon as the script is parsed.

The thing will be something like this:

(function Calc($){
    var a;
    var b;
    var c;

   a=1;
   b=2;

   c=a+b;

  $("#FirstDiv").html(c);
})(jQuery)

(function Name($){
   var Name;
   Name = "George";

  $("#SecondDiv").html(Name);
})(jQuery)

Also if you pass jQuery to the IIFE you can be sure $ points to jQuery and not another library or whatever.

EDITED:

As @MisterPositive comments be sure to jQuery is already loaded. So, yes, wrap your code inside $(document).ready(function(){}) or add jQuery script tag in the header and your script before closing </body> tag (another way to ensure the page is loaded before execute your code)

Hope it helps!

Upvotes: 1

Neo
Neo

Reputation: 3399

If you are using jQUery use this fuction to safely execute your two functions.

<script>
$( document ).ready(function() {
    //call your functions here;
});
</script>

https://learn.jquery.com/using-jquery-core/document-ready/

Upvotes: 1

Eric G
Eric G

Reputation: 2617

You need to execute you functions on page load like so:

function Calc(){
  var a;
  var b;
  var c;
  
  a=1;
  b=2;
  
  c=a+b;
  
  $("#FirstDiv").html(c);
}

function Name(){
   var Name;
   Name = "George";
  
  $("#SecondDiv").html(Name);
}

Calc();
Name();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="FirstDiv"></div>
<div id="SecondDiv"></div>

Upvotes: 4

Related Questions