Skip to content Skip to sidebar Skip to footer

Function Called At The Start Of Page Loading - Javascript

I have a problem; for some reason, my function is being called at the start of the webapplication while the page is loading. My code is as follows function validateName(element) {

Solution 1:

You need to pass function references to onblur, not the result of immediately calling a function. Change to this:

functioninit() {
    var firstName = initToolTip("firstname", "firstnameTip");
    var lastName = initToolTip("lastname", "lastnameTip");
    var promoCode = initToolTip("promocode", "promocodeTip");
    //opens the TOS window when you click 'terms and conditions' linkdocument.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
    //checks the length of the promo code
    promoCode.onblur = function() {validatePromoCode(promoCode);};
    //checks the validity of a name (is not blank)
    firstName.onblur = function() {validateName(firstName);};
    lastName.onblur = function() {validateName(lastName);{;
    //document.getElementById('submitButton').onmousedown = validateForm();
}

This changes each onblur assignment to take an anonymous function reference that will be executed later when the onblur event happens, not immediately like your current code was doing.

Solution 2:

You're not passing the function to onblur in init; you are passing the result of the function.

See the following example:

varAfuntion=function(){
  console.log("hello from function");
  return22;
}
Element.onblur=Afunction("something");//Element.onblur is now 22 and // "hello from function" is loggedElement.onblur=Afunction; //now onblur has a reference to the functionElement.onblur();//this will log "hello from function" and return 22

Youre not using a library like jQuery to make attaching/adding event listeners easy so it's a bit of a pain to set the event listener using pure JS and read the event in the function. There must be some info on SO how to do this already anyway

In your case you could try this:

promoCode.onblur = function(){ validatePromoCode.call(promoCode,promCode);};

Post a Comment for "Function Called At The Start Of Page Loading - Javascript"