user1234
user1234

Reputation: 3159

How to call a Jquery method on page load or page refresh in jquery

I have created a new JQuery widget for my project and I need to call that method on page load.

Here is the widget sample:

(function($){
   $.widget("mywidget", {
     options: {

     },
    _create: function(){
      var self = this;
      $.ajax({
       url: "/api/1.0/getdata",
       type: "GET",
       contentType: "application/json",

       success: function(arg) {
        //will be inserting the details from the json call into the <div>
        var data = arg;
       },
        error: function(resp){
        }
     });
    }
  });
})(jQuery);

Here is how I am trying to make the call to the widget:

$(document).ready(function(){
   console.log("show my widget");
   $("#div").mywidget();
});

Here is the HTML I am trying to load for my widget:

<div id="div">
  <p>Welcome to the newly created JQuery widget</p>
</div>

But when I do this nothing gets called, neither is the URL called, from which I am trying to access the data to show in my message nor the <div>. Any idea how can i access the widget on page load?

Upvotes: 0

Views: 95

Answers (2)

pohlman
pohlman

Reputation: 331

Syntax errors aside, using the latest stable jQuery UI I had to include a namespace in my widget name. Here is a jsfiddle with your code working. Note that it will correctly output an error attempting to hit /api/1.0/getdata.

If this solution doesn't work in your setup, ensure that the widget initialization code is being run before attempting to use it.

Upvotes: 1

Guy Perry
Guy Perry

Reputation: 306

It seems that your document ready is just missing brackets.. try -

$(document).ready(function(){
   console.log("show my widget");
   $("#div").mywidget();
});

Upvotes: 0

Related Questions