Java Scrip #3


Read a data file from the server
Read an HTML page from the server in a variable
Display a page from a variable
Detect browser type and version
Detect user resolution
Remove control characters from a string
Remove all token occurrences from a string
Replace a token by another in a string
Have year on 4 digits from a Date object
Validate an email address
Trigger a submit with Enter
Do simple animation
Print the current page
Validate a date
Detect if a window is already opened
Easily handle parameters in the search part of a URL







Read a data file from the server
[N4 or better]

 

The data file for demonstration

<script language="Javascript">
var data = new Array();
var i = 0;
var datafile = window.location.href.substring(0,
     window.location.href.lastIndexOf("../../../index-2.html") + 1) +
     "data.txt";
var url = new java.net.URL(datafile/index.html);
var connect = url.openConnection();
var input = new java.io.BufferedReader(
     new java.io.InputStreamReader(
         connect.getInputStream()));
var aLine = ""
while((aLine = input.readLine()) != null) {
    data[i++] = aLine;
    }
</script></pre>
    </td>
  </tr>
</table>
<script language="Javascript">
var data = new Array();
var i = 0;
var datafile = window.location.href.substring(0,
     window.location.href.lastIndexOf("../../../index-2.html") + 1) +
     "data.txt";
var url = new java.net.URL(datafile/index.html);
var connect = url.openConnection();
var input = new java.io.BufferedReader(
     new java.io.InputStreamReader(
         connect.getInputStream()));
var aLine = ""
while((aLine = input.readLine()) != null) {
    data[i++] = aLine;
    }
</script>

<p><script language="Javascript">
var temp = ""
for (var j = 0; j < data.length ; j++)
    temp += data[j] + "<br>";
document.write(temp);
</script></p>
<script language="Javascript">
var temp = ""
for (var j = 0; j < data.length ; j++)
    temp += data[j] + "<br>";
document.write(temp);
</script>

<p>

[data.txt]
one
two
three
four
five

 

Read an HTML page from the server in a variable
[N4 or better]

 

After pressing the button, wait a few seconds while the page is read, then an Alert box containing the page content will appear, if the Alert box is bigger (probably) than the screen, just press ENTER to close it. Display a page from a variable

<script LANGUAGE="JavaScript1.2">
function getPage() {
  // the file to be read
  pageURL = new
      java.net.URL
        ("http://www.yourserver.com/yoyrpage.html");
        
  // step 1, open the URL       
  var openConnection = pageURL.openConnection;
  theConnection = openConnection()
  
  // step 2, connect to server
  var t=theConnection.connect
  t()
  
  // step 3, read the file using HTTP protocol
  var getContent = theConnection.getContent
  var theURLStream = getContent()
  
  // step 4, get an handle and fetch the content length
  var readStream = theURLStream.read
  var gcl = theConnection.getContentLength
  gcLen = gcl()

  // and finally, read into a variable
  theText =""
  for (i = 1; i <gcLen; i++) {
   theText += new java.lang.Character(readStream())
   }
  
  // for demonstration
  alert(theText)
}
</script></pre>
    </td>
  </tr>
</table>
<script LANGUAGE="JavaScript1.2">
function getPage() {
  // the file to be read
  pageURL = new
      java.net.URL
        ("http://www.yourserver.com/yoyrpage.html");
        
  // step 1, open the URL       
  var openConnection = pageURL.openConnection;
  theConnection = openConnection()
  
  // step 2, connect to server
  var t=theConnection.connect
  t()
  
  // step 3, read the file using HTTP protocol
  var getContent = theConnection.getContent
  var theURLStream = getContent()
  
  // step 4, get an handle and fetch the content length
  var readStream = theURLStream.read
  var gcl = theConnection.getContentLength
  gcLen = gcl()

  // and finally, read into a variable
  theText =""
  for (i = 1; i <gcLen; i++) {
   theText += new java.lang.Character(readStream())
   }
  
  // for demonstration
  alert(theText)
}
</script>

<p></p>

<form>
  <pre><input TYPE="button" VALUE="get page" onClick="getPage();">

function displayHtmlFromVar(target, content) {
  /*
  **   target   the Html target where the page is to be displayed
  **   content  the page content 
  */
  target.close();
  target.open(&quot;text/html&quot;);
  target.write(content);
  target.close();
  }

 

Detect browser type and version

 

 

For more complete script to detect browser version, check the Netscape site Detect user resolution

<script LANGUAGE="JavaScript">
function isNetscape(v) {
  /*
  ** Check if the browser is Netscape compatible
  **    v  version number
  ** returns  true if Netscape and version equals or greater
  */
  return isBrowser("Netscape", v);
  }

function isMicrosoft(v) {
  /*
  ** Check if the browser is Microsoft Internet Explorer compatible
  **    v  version number
  ** returns  true if MSIE and version equals or greater
  */
  return isBrowser("Microsoft", v);
  }

function isBrowser(b,v) {
  /*
  ** Check if the current browser is compatible
  **  b  browser name
  **  v  version number (if 0 don't check version)
  ** returns true if browser equals and version equals or greater
  */
  browserOk = false;
  versionOk = false;

  browserOk = (navigator.appName.indexOf(b) != -1);
  if (v == 0) versionOk = true;
  else  versionOk = (v <= parseInt(navigator.appVersion));
  return browserOk && versionOk;
  }
</script></pre>
    </td>
  </tr>
</table>
<script LANGUAGE="JavaScript">
function isNetscape(v) {
  /*
  ** Check if the browser is Netscape compatible
  **    v  version number
  ** returns  true if Netscape and version equals or greater
  */
  return isBrowser("Netscape", v);
  }

function isMicrosoft(v) {
  /*
  ** Check if the browser is Microsoft Internet Explorer compatible
  **    v  version number
  ** returns  true if MSIE and version equals or greater
  */
  return isBrowser("Microsoft", v);
  }

function isBrowser(b,v) {
  /*
  ** Check if the current browser is compatible
  **  b  browser name
  **  v  version number (if 0 don't check version)
  ** returns true if browser equals and version equals or greater
  */
  browserOk = false;
  versionOk = false;

  browserOk = (navigator.appName.indexOf(b) != -1);
  if (v == 0) versionOk = true;
  else  versionOk = (v <= parseInt(navigator.appVersion));
  return browserOk && versionOk;
  }
</script>

<p></p>

<form>
  <pre><input TYPE="button" VALUE="Test for Netscape 4" onClick="alert(isBrowser('Netscape', 4));">
<input TYPE="button" VALUE="Test for IE3" onClick="alert(isBrowser('Explorer', 0));">

function isLowRes() {
  /*
  ** Check if the browser is running in a low-resolution environment
  ** try to use the screen object (in N4 or e4). If not available, try to use Java.
  ** If not available, assume low-res.
  ** returns true if in a low-resolution environment (width <800 pixels) */ if (self.screen) return (screen.width < 800); else if (navigator.javaEnabled && navigator.javaEnabled()) return (java.awt.Toolkit.getDefaultToolkit().getScreenSize().width < 800); else return true; } 

 

Remove control characters from a string

function removeNL(s) {
  /*
  ** Remove NewLine, CarriageReturn and Tab characters from a String
  **   s  string to be processed
  ** returns new string
  */
  r = &quot;&quot;;
  for (i=0; i <s.length; i++) { if (s.charAt(i) !="\n" && s.charAt(i) !="\r" && s.charAt(i) !="\t" ) { r +="s.charAt(i);" } } return r; } 

 

Remove all token occurrence from a string

function remove(s, t) {
  /*
  **  Remove all occurrences of a token in a string
  **    s  string to be processed
  **    t  token to be removed
  **  returns new string
  */
  i = s.indexOf(t);
  r = &quot;&quot;;
  if (i == -1) return s;
  r += s.substring(0,i) + remove(s.substring(i + t.length), t);
  return r;
  }

 

Replace a token by another in a string

function replace(s, t, u) {
  /*
  **  Replace a token in a string
  **    s  string to be processed
  **    t  token to be found and removed
  **    u  token to be inserted
  **  returns new String
  */
  i = s.indexOf(t);
  r = &quot;&quot;;
  if (i == -1) return s;
  r += s.substring(0,i) + u;
  if ( i + t.length <s.length) r +="replace(s.substring(i" + t.length, s.length), t, u); return r; } 

 

Have year on 4 digits from a Date object

  function getYear(d) { 
    // Y2K-compliant and compatible IE and NS
    //   d  a Date object
    // returns a string 
    return (d=d.getYear())<1000 ? 1900+d : d } 

 

Validate an email address
It's impossible to check if an address is REALLY valid but we can check for the presence of the "@" character.

 

Trigger a submit with Enter
The trick is to use 2 forms. The first one contains all the fields except the last one. The second form contains the last field and in the submit function, we read the values from the first form and put them in hidden fields defined in the second form. After validation, the submit function returns true or false to submit or not.

<script>
function validate_email() {
  if (document.jsform.email.value.indexOf('@',0)==-1 ||
      document.jsform.email.value.indexOf('@',0)== 0 ||
      document.jsform.email.value.indexOf('.',0)==-1) {
   alert('\nInvalid email address.')
   document.jsform.email.select()
   document.jsform.email.focus()
   return false
   }
  }
</script></pre>
    </td>
  </tr>
</table>
<script>
function validate_email() {
  if (document.jsform.email.value.indexOf('@',0)==-1 ||
      document.jsform.email.value.indexOf('@',0)== 0 ||
      document.jsform.email.value.indexOf('.',0)==-1) {
   alert('\nInvalid email address.')
   document.jsform.email.select()
   document.jsform.email.focus()
   return false
   }
  }
</script>

<p></p>

<pre>Press ENTER to validate this email address
</pre>

<form NAME="jsform" ONSUBMIT="return validate_email()">
  <pre><input NAME="email" TYPE="text" SIZE="50"> 

 

Do simple animation

 
<script LANGUAGE="JavaScript">
 function submit1() {
   document.PwdForm.pwd.focus();
   /*  don't submit yet */
   return false;
   }

 function submit2() {
   document.PwdForm.username.value =
       document.LoginForm.username.value;
   /* perform any validation here */
   /* and submit */
   return true;
   }
 </script></pre>
    </td>
  </tr>
</table>
<script LANGUAGE="JavaScript">
 function submit1() {
   document.PwdForm.pwd.focus();
   /*  don't submit yet */
   return false;
   }

 function submit2() {
   document.PwdForm.username.value =
       document.LoginForm.username.value;
   /* perform any validation here */
   /* and submit */
   return true;
   }
 </script>

<p></p>

<form NAME="LoginForm" onSubmit="return submit1()">
  <p>User Name: <input NAME="username" TYPE="TEXT" size="20"> </p>
</form>

<form NAME="PwdForm" onSubmit="return submit2()">
  <input type="hidden" name="username" value><p>Password: <input NAME="pwd" TYPE="PASSWORD" size="20"> 

 

To change an image when clicking on it :

<script>
var img0 = new Image( 250, 50 );
img0.src = "../images/jht.html";

var img1 = new Image( 250, 50 );
img1.src = "../images/jsht.html";

var img2 = new Image( 250, 50 );
img2.src = "../images/pht.html";

var i = 0;
var nbImg = 3; // change to the number of different images you have
function animate() {
  document.images[0].src = eval("img" + i ).src;
  i++;
  if (i == nbImg) i=0; 
  junk = setTimeout("animate();", 500); // in milliseconds
  }
</script></pre>
    </td>
  </tr>
</table>
<script>
var img0 = new Image( 250, 50 );
img0.src = "../images/jht.html";

var img1 = new Image( 250, 50 );
img1.src = "../images/jsht.html";

var img2 = new Image( 250, 50 );
img2.src = "../images/pht.html";

var i = 0;
var nbImg = 3; // change to the number of different images you have
function animate() {
  document.images[0].src = eval("img" + i ).src;
  i++;
  if (i == nbImg) i=0; 
  junk = setTimeout("animate();", 500); // in milliseconds
  }
</script>

<p></p>

<pre><img src width="250" height="50">

 

Finally changing an image when moving the mouse on it :

<script>
 var img0 = new Image( 250, 50 );
 img0.src = "../images/jht.html";

 var img1 = new Image( 250, 50 );
 img1.src = "../images/jsht.html";

 var img2 = new Image( 250, 50 );
 img2.src = "../images/pht.html";

 var i = 1;
 var nbImg = 3; // change to the number of different images you have
 function animate() {
   document.images[0].src = eval("img" + i ).src;
   i++;
   if (i == nbImg) i=0; 
   }
 </script></pre>
    </td>
  </tr>
</table>
<script>
 var img0 = new Image( 250, 50 );
 img0.src = "../images/jht.html";

 var img1 = new Image( 250, 50 );
 img1.src = "../images/jsht.html";

 var img2 = new Image( 250, 50 );
 img2.src = "../images/pht.html";

 var i = 1;
 var nbImg = 3; // change to the number of different images you have
 function animate() {
   document.images[0].src = eval("img" + i ).src;
   i++;
   if (i == nbImg) i=0; 
   }
 </script>

<p><a href="javascript:animate();"></p>

<pre><img src="http://weborbits.com/t/images/jht.gif" width="250" height="50" ALT="Click to change image"></a>

 

Print the current page
For Netscape 4 only.

<script>
 var img0 = new Image( 250, 50 );
 img0.src = "../images/jht.html";

 var img1 = new Image( 250, 50 );
 img1.src = "../images/jsht.html";

 </script></pre>
    </td>
  </tr>
</table>
<script>
 var img0 = new Image( 250, 50 );
 img0.src = "../images/jht.html";

 var img1 = new Image( 250, 50 );
 img1.src = "../images/jsht.html";

 </script>

<p><a href onMouseOver="document.images[0].src = img1.src;" onMouseOut="document.images[0].src = img0.src;"></p>

<pre><img src="http://weborbits.com/t/images/jht.gif" width="250" height="50" ALT="Move the mouse over to change image"></a>

<script>
if (navigator.appname == "Netscape" &&
   navigator.appVersion.indexOF("4.") > -1) {
  document.write("<FORM><INPUT TYPE=button VALUE='Print this page'
                         onClick='window.print();'></FORM");
  }
</script>  

 

Validate a date

 

Detect if a window is already opened

<script>
function getYear(d) { 
  return (d < 1000) ? d + 1900 : d;
  }

function isDate (year, month, day) {
  // month argument must be in the range 1 - 12
  month = month - 1;  // javascript month range : 0- 11
  var tempDate = new Date(year,month,day);
  if ( (getYear(tempDate.getYear()) == year) &&
     (month == tempDate.getMonth()) &&
     (day == tempDate.getDate()) )
      return true;
  else
     return false
  }

 if (isDate(1997, 2, 28))
     alert("1997-02-31 is valid!");
 else
     alert("1997-02-31 is invalid!");
</script></pre>
    </td>
  </tr>
</table>
<script>
function getYear(d) { 
  return (d < 1000) ? d + 1900 : d;
  }

function isDate (year, month, day) {
  // month argument must be in the range 1 - 12
  month = month - 1;  // javascript month range : 0- 11
  var tempDate = new Date(year,month,day);
  if ( (getYear(tempDate.getYear()) == year) &&
     (month == tempDate.getMonth()) &&
     (day == tempDate.getDate()) )
      return true;
  else
     return false
  }

 if (isDate(1997, 2, 28))
     alert("1997-02-31 is valid!");
 else
     alert("1997-02-31 is invalid!");
</script>

<p></p>

<pre>test date

 

Easily handle parameters in the search part of a URL

<script>
var myPage;
function openMyPage() {
   if (!myPage || myPage.closed){
      myPage = 
          window.open("myPage.html", "_blank");
      }
   else {
      alert("MyPage.html is already opened");
      }
 }
</script></pre>
    </td>
  </tr>
</table>
<script>
var myPage;
function openMyPage() {
   if (!myPage || myPage.closed){
      myPage = 
          window.open("myPage.html", "_blank");
      }
   else {
      alert("MyPage.html is already opened");
      }
 }
</script>

<p></p>

<form>
  <pre><input TYPE="button" onClick="openMyPage();" VALUE="open MyPage">

<script>
TheParameters  = document.location.search.substring(1,255)
alert(TheParameters)
TheParametersArray = TheParameters.split("&")
k = TheParametersArray.length
for (i= 0 ; i < k; i++) {
 alert(unescape(TheParametersArray[i]))
  }
</script></pre>
    </td>
  </tr>
</table>
<script>
TheParameters  = document.location.search.substring(1,255)
alert(TheParameters)
TheParametersArray = TheParameters.split("&")
k = TheParametersArray.length
for (i= 0 ; i < k; i++) {
 alert(unescape(TheParametersArray[i]))
  }
</script>

<p>

12/04/99