1

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?

Martin AJ
  • 5,689
  • 5
  • 42
  • 92

3 Answers3

3

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>
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
2

Try below code, It calls Click me on load and on button click as well. Hope this helps

$(document).ready(function() {
  console.log('document load')
  clickMe();
});
$('.button').click(function(){
clickMe();
});
function clickMe(){
  console.log('Clicked');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" > click me</button>
VJI
  • 81
  • 3
1

how about <body onload="myfunc()"> and your function in the <head> element:

<script>
function myfunc(){
    alert('something');
}
</script>

and then to call it from button

<button onclick="myfunc()">Click me</button>
hanumanDev
  • 6,378
  • 11
  • 78
  • 144