Martin AJ Martin AJ - 3 months ago 12
Javascript Question

How can I make a function which executes on page loading?

I have a JS function that I need to execute it when page loads. Here is the function:

function myfunc(){
alert('something');
}


Noted that I also need to have a name for it. Because I need to call it after page loading again (on click of a element).

So in short, I need to define a function which executes both on page loading and when user click on
$('.myclass')
element. How can I do that?

Answer

Put the call to that function in both the click handler for the .myclass elements, and also directly in a script tag, right before the </body>. Something like this:

<script>
    $(function() {
        $('.myclass').click(myfunc); // on click
    });

    myfunc(); // on load
</script>