I’ve got the following code that get’s a URL parameter, selects an option from a select element and then hides the div the select is in.
It’s going to be on a form that supplied by a 3rd party service, I only have access to a js file in the head of the form, there’s lots of other javascript. jQuery can’t be used (it’s not in the head).
What I’m unsure of is how to run the code after the rest of the page has loaded (or at least the elements needed), I can’t use window.onload, and I want to wrap things up as much as possible to avoid any chance of variables with same names elsewhere.
Thanks.
function getURLparameter( variable ){
variable = variable.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+variable+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var typeNum = {
abc: {
redirectURL: 'http://www.1.com',
optionIndex: 1
},
123: {
redirectURL: 'http://www.2.com',
optionIndex: 2
},
//etc etc
};
var formId = getURLparameter('SurveyID');
if (formId === 384) {
var urlType = getURLparameter('type');
var theType = typeNum[urlType];
var selectDiv = ('the_div');
var selectField = ('the_select');
if (urlType in typeNum) {
document.getElementById(selectField).options[theType.optionIndex].selected = true;
document.getElementById(selectDiv).style.visibility = "hidden";
}
}
You need to put it at the bottom of the page below all the elements you are accessing in the script.If you want to wrap it then use self-executing anonymous function:
This way no variables and functions defined inside will be accessible outside.
Update (see comments):
If
window.onloadis used by another script you can still add your own code there:HERE is the code.
EDIT:
A comment by symcbean:
For IE versions < 9
attachEvent()must be used. See this.