We help IT Professionals succeed at work.
Get Started

Adding multiple javascript events programmatically

YZlat
YZlat asked
on
175 Views
Last Modified: 2016-01-24
I have successfully added a form submit event code using the following:

if (window.addEventListener){			
        window.addEventListener('load', attachFormSubmit, false);
}else if (window.attachEvent){
	window.attachEvent('onload', attachFormSubmit );
}

Open in new window


Now I have a textbox on the page text1 and I want to clear the value of it when it takes focus.

I tried adding the following:

function attachFocus()
{
	var txt = document.getElementById("text1");
	if (txt.addEventListener){		
		txt.addEventListener('focus', ClearText(txt.id), false);
    	}else if (txt.attachEvent){				
		txt.attachEvent('focus', ClearText(this.id));
    	}
}
		
		function ClearText(id)
		{
			var obj = document.getElementById(id);
			obj.value='';
		}

Open in new window

     

And I added a call to attachFocus to the window load event:

if (window.addEventListener){			
        window.addEventListener('load', attachFormSubmit, false);
	window.addEventListener('load', attachFocus, false);
}else if (window.attachEvent){
	window.attachEvent('onload', attachFormSubmit );
	window.attachEvent('onload', attachFocus );
}

Open in new window


So the code I added for the textbox focus event does not work. Can someone point out to me what am I doing wrong and also recommend a better way to add events via javascript. I do not want to use inline javascript
Comment
Watch Question
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 25 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE