Srujana
Srujana

Reputation: 35

How to use a onload event in html, to call a function in a js file

I have a html file, where I need some items to be loaded from the server, for which I use a function in the js file. Now, instead of having that code in the tag in the html file, could I have that function in the js file, and call it through a onload attribute on any of the tags in HTML(as soon as the page loads)?

My HTML page is:

<script>
$.getScript(path + "js/jsfile.js");
</script>

<link rel="stylesheet" href="jqueryMobile/jquery.mobile-1.4.5.min.css">
<script src="jqueryMobile/jquery-1.11.2.min.js"></script>
<script src="jqueryMobile/jquery.mobile-1.4.5.min.js"></script>

<header data-role="header">
   <a href="#" class="ui-btn ui-icon-back ui-btn-icon-left"
    data-role="button" onclick="currentPage.back();">Back</a>
   <!--some header tags were here-->
</header>

<div data-role="content" style="padding: 15px" >
   <!--some button tags were here-->
</div>

As soon as this page gets loaded, I need the getColor() function to be executed and get the result fetched into the html page.

My jsfile.js page is:

currentPage = {};

currentPage.init = function() {
  WL.Logger.debug("listofenvironments :: init");
};

currentPage.back = function(){
  WL.Logger.debug("Login :: back");
  pagesHistory.push(path + "pages/otherpage.html");
  $("#pagePort").load(path + "pages/" + "otherpage.html");
};

function getColor(){
  //some coding goes on here....
}

I have tried using the onload event on the tag in my html page, but it is not working. While the currentPage.back() function is working fine.

Upvotes: 0

Views: 2125

Answers (2)

wallop
wallop

Reputation: 2571

Kindy go through some tutorials. These are basic questions you neednt have to look for stackoverflow. However find below the answer

<body onload="myFunc()">
</body>

//in your jsfile
function myFunc() {
    //your code
}

onLoad gets called after both your dom and resources get loaded, if you want the function to be called only after dom is loaded and resources need not be loaded use jquery ready function

$(document).ready(function(){
  //your code
});

Upvotes: 2

saikiran.vsk
saikiran.vsk

Reputation: 1796

Add below lines in your jsfile.js

$(document).ready(function(){
 getColor();//ready function will be executed after document elements are loaded.
});

Hope this will work for you.

Upvotes: 2

Related Questions