So far during my site development I have been storing all my jQuery functions in an external .js file, below are two examples of the functions inside:
// Loads the login form into the page.
function loadLoginForm() {
$('[name=loadLoginForm]').click(function() {
$("#loadingImage").css({ display:"block" });
$("#mainWrap").load("modules/web/loginForm.php", null, function(data) {
loadRegisterForm(this, data);
validateLoginDetails(this, data);
characterSelect(this, data);
});
});
}
// Loads the register form into the page.
function loadRegisterForm() {
$('[name=loadRegisterForm]').click(function() {
$("#loadingImage").css({ display:"block" });
$("#mainWrap").load("modules/web/registerForm.php", null, function(data) {
loadLoginForm(this, data);
registerUser(this, data);
});
});
}
The way I have been triggering these functions was to echo a link onto the page using PHP such as this;
Click <a href="#" name="loadLoginForm"><i>here</i></a> to login.
The problem I am facing now is how do I let the PHP side of the code trigger an event instead of it giving the user a link to trigger it?
The only answer I came up with was to get the PHP to echo some JavaScript so when the page loads the JavaScript will trigger the function needed, but I don’t know how to code this.
A situation where this will need to be used is for example when the user has successfully logged in, I don’t won the PHP to give the user a link to go to the next part I wont it to go there automatically.
I think it’s best to have a whole bunch of Javascript functions externally like you seem to be doing. No (or little) code should be executed in that common external JS File. Then in your HTML pages themselves you add some dynamic Javascript:
Alternatively you can put the ready() code inside the functions. This way only the minimal and necessary code gets executed on a page.
Trust me, I’ve done it the other way (where all the code gets executed on every page) and the page load times get stupidly high very quickly.
Edit: if you simply want to invoke an event, say you have:
you just need:
(assuming the click handler has been assigned). click() with no arguments triggers a click event.
You can also effectively set “this” in manually called Javascript. Imagine you have:
you can call that elsewhere with:
That is explicitly setting “this”. See JavaScript call and apply.
Does that help?