// Trigger mark action on button click
$("button[name='mark']").on("click", mark);
});
mark(); //will execute on page load
So the first part is creating a binding against the found element what will execute when any of them are clicked. Your question asked to also perform this on page load.
mark();
will immediately invoke it when it is encountered, which if you have it outside of any function, or in a function that is invoked on page load, it will execute on page load.
Others have suggested using .trigger('click')
on the end of the binding to reach the same result, which is correct as well. However, this incurs more overhead. When you use trigger(event)
you are making jQuery create a new Event object which will then be processed by the element(s) triggered.
Unless you have a reason to do this, this is usually unnecessary for the case you brought up. You simply want the function to execute on page load. There is no reason to force this logic through the DOM.
There are cases were this is desirable though, for instance if the element you are working with may also do other things, have other bindings, that should also process. In this case a trigger(event) can be used to invoke all the unknown methods that may be bound to the element.
It was also mentioned in the comments that one use of doing the trigger() is also that jQuery will auto bind the this
variable to the element processing the event. If you are using this
in the method then simply calling the method would not work as the this
would not be defined in that case.
However, even in this case you don't have to force your logic through the DOM and incur jQuery overhead. You could also simply use the call() method. For instance...
function workHorse() {
console.log(this.name);
}
$('button').on('click', workHorse);
console.log('without context');
workHorse();
console.log('with context');
workHorse.call($('button').get(0));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button name="tester">Click Me</button>
Using call()
you can tell it which element to use as the this
if you need to. So in either case, making jQuery create a new Event just to invoke a method is usually not necessary.
Though at the end of the day, it could be argued that it's also programmer flavor, so to each his own.