Kashif Waheed
Kashif Waheed

Reputation: 597

jquery function call on page both onload and onclick?

i am working on jquery calender but i need to call a function both on page load and then on click. when the page load for the first time it should automatically call and execute the function and for 2nd time and onward it should be call through click. is it possible?? if yes please help me.

   <script type="text/javascript">

   $(document).ready(function(){
      $("#fullDate").datepicker({

        showOn: "button",
        buttonImage: "images/calender.jpg",
        buttonImageOnly: true,

        onClose: function(dateText, inst) {
        $('#year').val(dateText.split('/')[2]);
        $('#month').val(dateText.split('/')[0]);
        $('#day').val(dateText.split('/')[1]);
    }


    });


});
</script>

Upvotes: 2

Views: 15894

Answers (3)

hielsnoppe
hielsnoppe

Reputation: 2869

Try writing a named function and call it on both events:

function doSomething() {
    // ...
}
$(document).ready(function() { doSomething() });
$(yourElem).on("click", function() { doSomething() });

Alternatively to writing an anonymous function as a callback, just to call doSomething, you could also pass the function name as an argument, gaining a little performance by not cluttering memory with unnecessary anonymous functions:

$(document).ready(doSomething);
$(yourElem).on("click", doSomething);

Upvotes: 5

ahren
ahren

Reputation: 16961

$(document).ready(function(){
  $("#fullDate").datepicker({
    showOn: "button",
    buttonImage: "images/calender.jpg",
    buttonImageOnly: true,

    onClose: function(dateText, inst) {
        $('#year').val(dateText.split('/')[2]);
        $('#month').val(dateText.split('/')[0]);
        $('#day').val(dateText.split('/')[1]);
    }
  });
  $("#fullDate").datepicker("show"); // this will run once.
});

Upvotes: 1

Joseph
Joseph

Reputation: 119827

During load, you can use

//when window loads
$(window).load(function(){
    functionCallHere();
});

//or when DOM is ready
$(document).ready(function(){
    functionCallHere();
});

Then for the click

$(element).click(function(){
    functionCallHere();  //call the function again
});

Where functionCallHere is the name of the common function called on those events.

Upvotes: 1

Related Questions