annedroiid
annedroiid

Reputation: 6637

How do I get a jquery function to run when the page is loaded?

I'm trying to create an html page that uses jquery to populate a table when the page loads. I have the function that gets the data, but currently for testing I just attached it to a button that I'm clicking to get the table to appear.

How do I get a jquery function to run when the page is loaded? In case it isn't obvious I'm a complete beginner when it comes to Jquery, so this may be something really obvious, but I've been trying to google it and I can't find a solution.

Upvotes: 0

Views: 58

Answers (3)

Atul Sharma
Atul Sharma

Reputation: 10645

jQuery(document).ready(function(){
  //some logic 
  newFunc();
  //logic

});

function newFunc(){
 //logic
}

However you can write code anywhere inside <script> tags and it will execute directly after including the jQuery file. But, the may not be as effective as above because at that time dom may or may not be created. So, better go the above way .. as it will only execute when page is loaded and DOM is created.

Upvotes: 1

Bhabani Das
Bhabani Das

Reputation: 380

Are you looking for something like this. You can do this in regular JS.

document.addEventListener('DOMContentLoaded', function() {
  console.log('document loaded');
});

But be aware this doesn't cover you from other dependent file loading like the js and png and others . They get loaded asynchronously . this just cover you for the dom content load

Upvotes: 0

Jay Ghosh
Jay Ghosh

Reputation: 682

This should do the trick

jQuery(document).ready(myFunction);

function myFunction(){
    // logic goes here
}

Upvotes: 2

Related Questions