Adding multiple javascript events programmatically

YZlat
YZlat used Ask the Experts™
on
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

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2013
Awarded 2012

Commented:
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

Author

Commented:
I want to separate javascript from html markup. And I cannot use JQuery because of company standards.

Author

Commented:
Is there a serious justified improvement that I'd get using JQuery?
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

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
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

Author

Commented:
Slick812, I do not want to use inline javascript
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.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
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
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

sorry Julian , did not mean to redo your post, I was writing and did not see yours

Author

Commented:
CData is outdated and it is not recommended to keep using it
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

Author

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
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
@YSlat - two valid solutions were posted before yours.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Two experts provided correct solutions before author posted her own.

This was raised in the thread with no response.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
@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

Author

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.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Which of the two solutions presented used inline javascript or JQuery?
Expert of the Year 2008
Top Expert 2008

Commented:
>>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

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.

Author

Commented:
Oh no this question will not just die:) I knew that already and I am Ok with that.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
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

Author

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!

Author

Commented:
Mr. Wolf, I just attempted to close it again. Thank you for your consideration

Author

Commented:
I solved it myself

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial