Reputation: 6707
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?
Upvotes: 1
Views: 100
Reputation: 6614
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>
Upvotes: 1
Reputation: 81
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>
Upvotes: 2
Reputation: 337713
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>
Upvotes: 4