Weird Thoughts From Eric's Head

Tags - Categories : All | AJAX | BUSINESS | PERSONAL | PROGRAMMING | BOOK REVIEW

Resetting Forms with JavaScript
Well we all know that the reset button on a form resets the fields of a form back to what their states initially were set to. We can also cause the same effect by performing the following statement:

document.formName.reset();
Now that is fine and dandy if you want the forms to go back to orginal state, but what if you want everything wiped clean? Well you can loop through the form array and detect the type of the element. If it is a text based element, we reset the value. A checkbox/radio button selections get set to false. And a select element's selected Index is set to -1.
<script type="text/javascript">
  function ResetForm(xFormName){
    var arrElems = document.forms[xFormName].elements;
    document.forms[xFormName].reset();
    for(xi=0;xi<arrElems.length;xi++){
      if(arrElems[xi].type.toLowerCase() == "text" ||
         arrElems[xi].type.toLowerCase() == "hidden" ||
         arrElems[xi].type.toLowerCase() == "password" ||
         arrElems[xi].type.toLowerCase() == "textarea")
        arrElems[xi].value="";
      else if(arrElems[xi].type.toLowerCase() == "radio" ||
              arrElems[xi].type.toLowerCase() == "checkbox")
        arrElems[xi].selected = false;
      else if(arrElems[xi].type.toLowerCase().indexOf("select") != -1)
        arrElems[xi].selectedIndex = -1;
    }
  }
</script>
I probably could have used a switch statment to speed up the processing of the loop, but you would only notice the time difference if we were talking 1000's of elements. Sorry that the format is rather ugly, but I did not want to mess up everyone's RSS readers with long strings like normal!

Hope that helps!

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages


How are they defeating Pop Up Blockers?
People have been telling me that it seems like people are getting around pop up blockers. I sat down and tried to break the pop up blocker on google's toolbar on IE6. The first solution I already new, the second one I found in 1 minute.

Piggy Backing
The first solution is what I call piggy backing. Basically you just add an onclick handler on every link.

<a href="http://radio.javaranch.com/pascarello" onclick="window.open
('http://www.javaranch.com')">Your Link</a>


Overloading
The second solution I call is overloading. Basically making a loop that slams a window.open function. Well with google's toolbar, it you do not perform any actions on the page it blocksthem all, but if you start typing, for some reason the pop up blocker fails.
<script type="text/javascript">
  var winPop;
  var i=0;
  function BrakePopUp(){
    winPop = window.open("about:blank");
    document.title = i++;
    if (winPop==null || typeof(winPop)=="undefined")setTimeout("BrakePopUp()",10);
    else {}
  }
  window.onload=BrakePopUp
</script>


How did Mozilla fare?
Of course the piggy backing pop up got through. Not a surprise. The overloading popup did nothing but sit there. I let it run for over 30,000 pop up attempts. That is good.

So I though how about really slamming it, so I built the loop that made a killer loop that would freeze the browser with so many slams.
<script type="text/javascript">
  var winPop;
  var i=0;
  var time;
  function BrakePopUp(){
    winPop = window.open("about:blank");
    document.title = i++;
    if (winPop==null || typeof(winPop)=="undefined")time = setInterval("BrakePopUp()",10);
  }
  window.onload=BrakePopUp
</script>

Well IE cracked and froze, Mozilla just froze!

At some point I want to test this against SP2's pop up blocker.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Finding Errors in an (X)HTML layout painlessly!

One of the tough tasks for people that do not code HTML and CSS often is how to find the errors in their layouts. "Why is this not showing up?" or "Why is this red when it should be blue?" A lot of the time it is missing tags. A person forgets to close a span or paragraph tag. Another reason is nesting two elements together that should not be. Normally you would have to rip the code apart in chunks to find the problems, but there is another way to do this.

Well an easy way to find the errors is to validate your page. You can validate your page by going to W3C Markup Validation Service. Basically you either give the validator the URL to the site or up upload the HTML file. The validator runs through the page's mark-up and either says it found no errors or lists them out.

This validator should help you from banging your head against the wall, but it may cause you to bang your head if you do not understand the error messages! That is where the JavaScript HTML/JavaScript Forum comes in handy!

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Print The DOM Node Tree
A user on one of forums posted this link: http://www.permadi.com/tutorial/domTree/index.html to a tutorial on the DOM Node. The script there is rather interesting to anyone that does not understand the structure of a document.

An example output from the script with IE6 is:

<HTML>
  ¦
  ¦--<HEAD>
  ¦  ¦
  ¦  ¦--<TITLE>
  ¦  ¦   </TITLE>
  ¦   </HEAD>
  ¦
  ¦--<BODY>
  ¦  ¦
  ¦  ¦--<TABLE>
  ¦  ¦  ¦
  ¦  ¦  ¦--<TBODY>
  ¦  ¦  ¦  ¦
  ¦  ¦  ¦  ¦--<TR>
  ¦  ¦  ¦  ¦  ¦
  ¦  ¦  ¦  ¦  ¦--<TD>
  ¦  ¦  ¦  ¦  ¦  ¦
  ¦  ¦  ¦  ¦  ¦  ¦--[unknown tag]
  ¦  ¦  ¦  ¦  ¦  ¦  
  ¦  ¦  ¦  ¦  ¦   </TD>
  ¦  ¦  ¦  ¦   </TR>
  ¦  ¦  ¦  ¦
  ¦  ¦  ¦  ¦--<TR>
  ¦  ¦  ¦  ¦  ¦
  ¦  ¦  ¦  ¦  ¦--<TD>
  ¦  ¦  ¦  ¦  ¦  ¦
  ¦  ¦  ¦  ¦  ¦  ¦--[unknown tag]
  ¦  ¦  ¦  ¦  ¦  ¦  
  ¦  ¦  ¦  ¦  ¦   </TD>
  ¦  ¦  ¦  ¦   </TR>
  ¦  ¦  ¦   </TBODY>
  ¦  ¦   </TABLE>
  ¦   </BODY>
   </HTML>

I guess my geek in me things this is cool.
Hope this helps you out.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

It is Friday, play some games
Well I have not looked at my games that I have programmed in JavaScript for a long time. I thought I would dust off the links and put them out here. So if anyone is bored today or wants to avoid work, click on the links and play:

Hope you do not waste too much time today.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Comparing Colors with JavaScript
If you try to compare two colors in JavaScript, you will find that Firefor chages HEX values to rgb values. Microsoft internet explorer does not do that. So we need to make a function that determines what format the color code is in and then compare them.

<div id="div1" style="background-color:#33AA33">asdf</div>
<div id="div2" style="background-color:#00FF00">asdf</div>

<script>

  window.onload= function(){

    var color1 = document.getElementById("div1").style.backgroundColor;
    var color2 = document.getElementById("div2").style.backgroundColor;
    alert(color1.compareColor(color2) + " ~ False!")

    color2 = "#33AA33";
    alert(color1.compareColor(color2) + " ~ true")

    color2 = "rgb(51, 170, 51)"
    alert(color1.compareColor(color2) + "~ True")

  }


  String.prototype.compareColor = function(){
    if((this.indexOf("#") != -1 && arguments[0].indexOf("#") != -1) || 
      (this.indexOf("rgb") != -1 && arguments[0].indexOf("rgb") != -1)){
      return this.toLowerCase() == arguments[0].toLowerCase()
    }
    else{
      xCol_1 = this;
      xCol_2 = arguments[0];
      if(xCol_1.indexOf("#") != -1)xCol_1 = xCol_1.toRGBcolor();
      if(xCol_2.indexOf("#") != -1)xCol_2 = xCol_2.toRGBcolor();
      return xCol_1.toLowerCase() == xCol_2.toLowerCase()
    }
  }


  String.prototype.toRGBcolor = function(){
    varR = parseInt(this.substring(1,3), 16);
    varG = parseInt(this.substring(3,5), 16);
    varB = parseInt(this.substring(5,7), 16);
    return "rgb(" + varR + ", " + varG + ", " +  varB + ")";
  }
</script>
As you can see I created two prototype functions. The compareColor function is attached to one color string and the second color is send as an argument. The compareColor function returns a Boolean value back.

The second prototype function chnages a hex color value to an rgb color value.

Hope this helps in your color comparisons.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Convert Table Row to Hyperlink
Well I saw a post here on the asp.net forums wanting to take a single column that contains a hyperlink and make the whole row clickable.

Well, I talked about making the whole row clickable here on my blog before, but the user wants to take a hyperlink from one of the columns and do it. A light bulb went off in my head and I coded this in two minutes.

<html>
  <head>
    <style type="text/css">
      table{
        border: 1px solid black;
        border-collapse: collapse;
        width: 50%;
      }
      th, td{
        border: 1px solid black;
        padding: 3px;
        width: 25%;
      }
      th{
        background-color: #A0A0A0;
      }
      tr{
        background-color: white;
      }
      tr.highlight{ 
        background-color: #B8CDDC;
        cursor: pointer;
      }
    </style>
    <script type="text/javascript">
      window.onload = function(){
        ConvertRowsToLinks("table1");
      }
      
      function ConvertRowsToLinks(xTableId){

        var rows = document.getElementById(xTableId).getElementsByTagName("tr");
   
        for(i=0;i<rows.length;i++){
          var link = rows[i].getElementsByTagName("a")
          if(link.length == 1){
            rows[i].onclick = new Function("document.location.href='" + link[0].href + "'");
            rows[i].onmouseover = new Function("this.className='highlight'");
            rows[i].onmouseout = new Function("this.className=''");
          }
        }

      }

    </script>  
  </head>
  <body>
    <table id="table1">
      <tr>
        <th>Website</th>
        <th>Subject</th>
        <th>Content</th>
      </tr>
      <tr>
        <td><a href="http://www.JavaRanch.com">JavaRanch</a></td>
        <td>Java</td>
        <td>Content and Forums</td>
      </tr>
      <tr>
        <td><a href="http://www.asp.net">ASP.NET</a></td>
        <td>.NET</td>
        <td>Content and Forums</td>
      </tr>
      <tr>
        <td><a href="http://radio.javaranch.com/Pascarello">Eric's Blog</a></td>
        <td>JavaScript,.NET,and Stuff</td>
        <td>Programming Discussion</td>
      </tr>
    </table>
  </body>
</html>

Basically we are grabbing the table's rows. We than loop through each of the rows looking for a link. If a link exists, we grab the href and attach an onclick event to the element. To make it fancier, I added some mouse events so the row is highlighted.

Hope this is helps,

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Enable Active Content - IE warning message
I am really tired of the question: "Why can't I run scripts on my local machine without getting a security warning. I do not know why it will not let me do it!"

The problem is not your script but your browser settings on IE. With SP2 installed, it adds more protection and one of them is to block JavaScript from running on the local machine.

It is an easy fix, all you need to do is go into your tools menu and select internet options. Scroll down to you see the Security heading and check the two boxes shown in the graphic below. The one that you most likely need is "Allow active content to run in files on My Computer". The default setting is unchecked. Checking it allows your code to run!

security setting with IE

As you can see, IE blocks code on the client and cd.

Click apply and Ok and your problems should be fixed!

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Disable All Links with JavaScript
Another question that has popped up is how do I disable all of the links on the page? Well you can loop through and set the links to disabled. That in return makes them gray, but it does not disbale them.
To disable the link, you need to add an onclick and return false. If their is an onclick handler on that, you need to grab it and add it to the link. So much fun!

window.onload= function(){
        DisableEnableLinks(true)
}

function DisableEnableLinks(xHow){
  objLinks = document.links;
  for(i=0;i<objLinks.length;i++){
    objLinks[i].disabled = xHow;
    //link with onclick
    if(objLinks[i].onclick && xHow){  
        objLinks[i].onclick = new Function("return false;" + objLinks[i].onclick.toString().getFuncBody());
    }
    //link without onclick
    else if(xHow){  
      objLinks[i].onclick = function(){return false;}
    }
    //remove return false with link without onclick
    else if(!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1){            
      objLinks[i].onclick = null;
    }
    //remove return false link with onclick
    else if(!xHow && objLinks[i].onclick.toString().indexOf("return false;") != -1){  
      strClick = objLinks[i].onclick.toString().getFuncBody().replace("return false;","")
      objLinks[i].onclick = new Function(strClick);
    }
  }
}

String.prototype.getFuncBody = function(){ 
  var str=this.toString(); 
  str=str.replace(/[^{]+{/,"");
  str=str.substring(0,str.length-1);   
  str = str.replace(/\n/gi,"");
  if(!str.match(/\(.*\)/gi))str += ")";
  return str; 
} 
Hope that helps!

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Disable All Form Elements
Another question I have seen a lot lately is how can I disable all of the form elements on the page with JavaScript? Well it is rather simple and only takes a few lines of code. All you need to do is loop through the Form elemnt array and set the disabled property to true to disable the elements and false to enable the elements.

function DisableEnableForm(xForm,xHow){
  objElems = xForm.elements;
  for(i=0;i<objElems.length;i++){
    objElems[i].disabled = xHow;
  }
}
To execute the function, you just need to send the form object reference and a boolean value to the function. The following code is an example how to call the function disable the elements as the page is loading.
window.onload= function(){
  DisableEnableForm(document.Form1,true);
}
Hope this helps!

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Printing a document
Another question I see asked a lot on the forums is I want to print a document without loading it. The problem is you have to load the document. The way to hide it from the user is to use a hidden iframe which you load the document.

<iframe id="iframePDF" src="about:blank" style="display:none"></iframe>
<input type="button" value="Print Word" name="btnPrint1" onclick="PrintFrame('test.doc')"/>
<input type="button" value="Print Excel" name="btnPrint2" onclick="PrintFrame('asdf.CSV')"/>
<input type="button" value="Print PDF" name="btnPrint3" onclick="PrintFrame('test.pdf')"/>
<span id="spanMess" style="display:none;color:red;"><h3>Preparing Document For Print</h3></span>

<script type="text/javascript">
  function PrintFrame(xFile){
    parent.iframePDF.location.href = xFile;
    document.getElementById("spanMess").style.display="block";
    parent.iframePDF.onload = new function(){
      setTimeout("parent.iframePDF.print();
      parent.document.getElementById('spanMess').style.display='none';",5000);
    }
  }
</script>
Now there is one problem with this method. I have to use a timeout to delay the printing. The reason for this is that the onload event fires as soon as the document starts loading, it does not wait until it is completed like a HTML page. Therfore you need to add the timeout. If you document is large, you need to increase the time.

Hope that helps.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages

Was my pop up blocked?
I have seen a lot of questions lately about detecting if your pop up window was blocked by a pop up blocker. It is rather simple as shown below:

var winPop = window.open(...) ;
if (winPop==null || typeof(winPop)=="undefined") alert("window blocked");
Hope that helps

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages