Jump to content

Can I make this shorter?


FrOzeN

Recommended Posts

<html>
<head>
  <title>Example</title>
  <style type="text/css">
    input {background-color: #82CAFA;}
  </style>
  <script type="text/javascript">
    <!--
      function txt_focus(textbox) {
          document.getElementById(textbox).style.backgroundColor = "#AFDCEC";
      }

      function txt_blur(textbox) {
          document.getElementById(textbox).style.backgroundColor = "#82CAFA";
      }
    //-->
  </script>
</head>
<body>

<input id="t1" type="text" onfocus="javascript:txt_focus('t1');" onblur="javascript:txt_blur('t1');" /><br />
<input id="t2" type="text" onfocus="javascript:txt_focus('t2');" onblur="javascript:txt_blur('t2');" /><br />
<input id="t3" type="text" onfocus="javascript:txt_focus('t3');" onblur="javascript:txt_blur('t3');" /><br />
<input id="t4" type="text" onfocus="javascript:txt_focus('t4');" onblur="javascript:txt_blur('t4');" /><br />
<input id="t5" type="text" onfocus="javascript:txt_focus('t5');" onblur="javascript:txt_blur('t5');" /><br />
<input id="t6" type="text" onfocus="javascript:txt_focus('t6');" onblur="javascript:txt_blur('t6');" /><br />
<input id="t7" type="text" onfocus="javascript:txt_focus('t7');" onblur="javascript:txt_blur('t7');" /><br />
<input id="t8" type="text" onfocus="javascript:txt_focus('t8');" onblur="javascript:txt_blur('t8');" />

</body>
</html>

 

Is there a shorter way I can do this? Like a global event when a textbox has focus, and another one for when a textbox doesn't have focus? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/78195-can-i-make-this-shorter/
Share on other sites

Yeah this isnt too bad. The first thing that you want to do is group the elements that you are working with.

 

<div id="group_eles">
<input type="text" id="t1" /><br />
<input type="text" id="t2" /><br />
<input type="text" id="t3" /><br />
<input type="text" id="t4" /><br />
<input type="text" id="t5" /><br />
<input type="text" id="t6" /><br />
</div>

 

Now I just used a very simple object to collect the elements and apply actions, it is kinda unnecessary, but it gives the functionality a namespace

 

<script type="text/javascript">
var blur = {
	ini: function(){
		var eles =  document.getElementById('group_eles').getElementsByTagName('input');
		for(e in eles){
			eles[e].onblur = function(){
				this.style.background = '#82CAFA';
			};
			eles[e].onfocus = function(){
				this.style.background = '#AFDCEC';
			};
		}
	}
};

onload = function(){
	blur.ini();
}

</script>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.