Adding multiple javascript events programmatically

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
LVL 35
YZlatAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rainer JeschorCommented:
Hi,
question: why do you want to add it dynamically and not directly inside the HTML markup?
And as I assume there will be more and more events added, why not using a tested and working library like jQuery which makes such things a lot easier - especially the cross browser handling?

Can you post more or even better the complete code or reproduce your markup with dummy data on a site like jsFiddle, Codepen or Plnkr?

Thanks
Rainer
YZlatAuthor Commented:
I want to separate javascript from html markup. And I cannot use JQuery because of company standards.
YZlatAuthor Commented:
Is there a serious justified improvement that I'd get using JQuery?
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Slick812Commented:
I am not sure why you go the the trouble of trying to do the addEventListener or attachEvent, for a single element onfocus event? ? ?

maybe something like -
document.getElementById("text1").onfocus=function(){ this.value="";};

just my opinion, but using JQUERY for simple javascript is overkill
Slick812Commented:
or you could just write it in the text input declaration -
<input type="text" id="text1" onfocus=" this.value='' " />

iif you still need to use the  add eventlistener, , then I do not think there is a "focus" event, but you might try the onfocus event
YZlatAuthor Commented:
Slick812, I do not want to use inline javascript
Slick812Commented:
OK, but is there a specific reason that you say -
"I do not want to use inline javascript"

if you already have this "inline factor" contained and researched , then just ignore my comments.
Julian HansenCommented:
This works for me
HTML
<input type="text" id="text1" />

Open in new window

jQuery
<script>
var el = document.getElementById('text1');
el.addEventListener('focus', function(evt) {
	evt.target.value = '';
});
</script>

Open in new window

Working sample here
Slick812Commented:
this works in firefox -
<form id="Form1">
  <input type="text" id="t1">
</form>

<script>/* <![CDATA[ */
var x = document.getElementById("t1");
x.addEventListener("focus", doclear);

function doclear() {
document.getElementById("t1").value = "";  
}
/* ]]> */</script>

Open in new window

Slick812Commented:
sorry Julian , did not mean to redo your post, I was writing and did not see yours
YZlatAuthor Commented:
CData is outdated and it is not recommended to keep using it
YZlatAuthor Commented:
Here is how I solved it:

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

}
		
		function ClearText(obj)
		{
			
			obj.value='';
		}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
YZlatAuthor Commented:
I've requested that this question be closed as follows:

Accepted answer: 0 points for YZlat's comment #a41415058

for the following reason:

solved it myself
Julian HansenCommented:
@YSlat - two valid solutions were posted before yours.
Julian HansenCommented:
Two experts provided correct solutions before author posted her own.

This was raised in the thread with no response.
Julian HansenCommented:
@Slick812 - apologies just saw your post re duplicate- did not pick that up but no problems here - you have enough of a rep that it was obviously not intentional
YZlatAuthor Commented:
I posted a question asking for a fix for my solution. I cannot and do not want to change entirely the way I do things. I specifically stated that I do not want inline javascript and cannot use JQuery.
Julian HansenCommented:
Which of the two solutions presented used inline javascript or JQuery?
hieloCommented:
>>Here is how I solved it:
actually that code will give you problems because the "if" clause does not pass any arguments to ClearText while the "else" clause does. The problem in your original code is that for the second argument you are making a function call instead of simply providing a function reference.  The code below should fix your original post (notice that the in the else-if clause I also changed this.id to txt.id):
function attachFocus()
{
	var txt = document.getElementById("text1");
if(txt){
	if (txt.addEventListener){		
		txt.addEventListener('focus', function(){ClearText(txt.id);}, false);
    	}else if (txt.attachEvent){				
		txt.attachEvent('focus', function(){ClearText(txt.id);});
    	}
}
}
		
		function ClearText(id)
		{
			var obj = document.getElementById(id);
			obj.value='';
		}

Open in new window

Slick812Commented:
OHHH, this question just will not die :-c ? ?
I really do not think that in any circumstance, I would even consider the code write using the "addEventListener" because of this line -
     }else if (window.attachEvent){
and the possible muti line extra code work, and difficult naming conventions. . . .

YZlat says -     "I do not want inline javascript and cannot use JQuery"
which seems right to me for this. . . SO, below is some page code that I have used for a HTML form and text inputs, although I changed it from "onclick"  to  "onfocus" and had the value clear, instead of click stuff.
Since the "I do not want inline", this javascript is in another file as   clear_5.js , because of all the talk of JS collisions and NameSpace (LOL), I use the  "_5"  as a suffix to avoid this.

the form code -
<form id="form4">
first -<input type="text" name="first" id="tx1" value="OK1" />
 - Include Sender -<input type="checkbox" value="highG" name="sender" style="vertical-align: middle;" /><br />
last -<input type="text" name="last" id="tx2" value="OK2" /> - 
email -<input type="text" name="email" id="tx3" value="OK3" /><br />
<input type="submit" value=" Send Me ">
</form>

Open in new window


so here is some JS that I consider to be my opinion for a FORM inputs event functioning (in a separate JS file) -
window.onload = function() {
var inAry_5 = document.getElementById("form4").getElementsByTagName("input");
for(var i=0;i<inAry_5.length;++i)
  if(inAry_5[i].type=="text"){
    inAry_5[i].onfocus=function(){
      if(this.clr_5)return;
      this.value="";
      this.clr_5=1;
      }
  inAry_5[i].clr_5=0; inAry_5[i].style.margin="2px 2px 3px 2px";}
}

Open in new window

I can not see how anyone would tolerate always clearing the inputs, so I did it to clear text, only on the initial focus.

I tested this in an old web test puter running IE 6 , and it worked.
YZlatAuthor Commented:
Oh no this question will not just die:) I knew that already and I am Ok with that.
Julian HansenCommented:
attachEvent has been deprecated as of IE11 https://msdn.microsoft.com/en-us/library/ms536343%28v=vs.85%29.aspx

Still trying to figure out what was wrong with this solution ID 41415016
YZlatAuthor Commented:
Dear hielo, actually txt.id was not working out for me. Do not remember why but I had it befor as txt.id and later changed to txt. And exact code I posted was what worked for me so it is my solution. Thank you very much for revisiting an old question but I will stop responding from now on and will let the moderator handle this however they see fit.

I just wanted to post what worked for me in case anyone else has a similar issue and hopefully my solution will help them.

Thank you for your time and have a good day!
YZlatAuthor Commented:
Mr. Wolf, I just attempted to close it again. Thank you for your consideration
YZlatAuthor Commented:
I solved it myself
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.