Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, October 5, 2012

JavaScript code to Get/Set the Caret position from/at TextArea


<html>
<head>
<title>Get/Set Caret in Textarea Example</title>
<script>
function doGetCaretPosition (ctrl) {

var CaretPos = 0;
// IE Support
if (document.selection) {

ctrl.focus ();
var Sel = document.selection.createRange ();

Sel.moveStart ('character', -ctrl.value.length);

CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;

return (CaretPos);

}


function setCaretPosition(ctrl, pos)
{

if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}

function process()
{
var no = document.getElementById('no').value;
setCaretPosition(document.getElementById('get'),no);
}

</script>
</head>
<body>
<textarea id="get" name="get" rows="5" cols="31">Please write some integer in the textbox given below and press "Set Position" button. Press "Get Position" button to get the position of cursor.</textarea>
<br>
Enter Caret Position: <input type="text" id="no" size="1" /><input type="button" onclick="process();" value="Set Position">
<BR>
<input type="button" onclick="alert(doGetCaretPosition(document.getElementById('get')));"
value="Get Position">
</body>
</html>

Requirement for updation of window.showModalDialog functionality in JSP

Requirement:  I need to create a JavaScript "modal child window" functionality with JSP, along with the same JSP webpage update functionality.  Here, parent window should aware of child window's number of update requests.

Issue: I can create a "modal child window" with JSP using window.showModalDialog JavaScript function.  But, it is not supporting JSP webpage update functionality.  There is one more JavaScript function window.open.  It is supporting JSP webpage update functionality.  But, it creates "modeless child window".  

Issue Resolution:  I had chosen window.open JavaScript function, as it is supporting major JSP webpage update functionality.  Later, using the additional JavaScript features (i.e., JavaScript global variables, HTML hidden variables and JavaScript parent-child/child-parent window communication), I made the child window behaves like a "modeless child window".

Here, using JavaScript global variables, parent window can know the state of the child window, i.e., whether child window is opened/closed.  Using JavaScript HTML hidden variables, parent window would aware of child window's number of update requests.  Using JavaScript parent-child/child-parent communication, I successfully made the "modeless child window", even though by using JavaScript window.open function.

Wednesday, September 19, 2012

Sample JavaScript Code to Display/Hide the Table


<!--          Sample JavaScript program to Display/Hide Table         -->

<html>
<head>
<title>TableDisplayOnOff</title>
<script>
function load()
{
        var t = document.getElementById("tab");
        t.style.visibility="visible";
}

function load2()
{
        var t = document.getElementById("tab");
        t.style.visibility="hidden";
}
</script>
</head>
<body bgcolor=white>
<br><br><br><br><br><h3 align="center" style="font-family:arial;font-weight:BOLD;font-size:16px"> <u>Table</u></h3>
<form name ="frm">
<table id="tab" style="visibility:hidden">
<tr>
<th>RAGHUPATI</th><th></th><th>RAGHAVA</th><th></th><th>RAJA</th><th></th><th>RAM</th>
</tr>
</table>
<input type="button" name="hai" value="Display" onclick="load()">
<input type="button" name="hai" value="Hide" onclick="load2()">
</form>
</body>
</html>


---------------------------------------------------------------------------------------------------


<!--   Example:    Table Display/Hidden         -->
<html>
<head>
<title>Sample Program</title>
<script>
function load()
{
        var t = document.getElementById("tab");
        t.style.visibility="visible";
}
</script>
</head>
<body bgcolor=white>
<br><br><br><br><br><h3 align="center" style="font-family:arial;font-weight:BOLD;font-size:16px"> <u>TaskList</u></h3>
<form name ="frm">
<table id="tab" style="visibility:hidden">
<tr>
<th>name</th><th>address</th>
</tr>
</table>
<input type="button" name="hai" value="hai" onclick="load()">
</form>
</body>
</html>


Saturday, August 4, 2012

Play Audio files at background from HTML page using JavaScript

JavaScript Methods

var audioFileName = "NenuSaitam";
var audioFileExtn = ".wav";


function playSound(audioFileName) // Audio : Start Sound
{


// alert (audioFileName);
audioFileName = audioFileName + audioFileExtn;

try
{

if(document.all)
{

document.all["BGSOUND_ID"].src = audioFileName;
}
else
{

self.iplayer.location.replace("jsplayer.htm?" + audioFileName);
}
}
catch(err)
{

dispErrorMessage(err);
}
finally
{ }

} // playSound


function stopSound() // Audio : Stop Sound
{

try
{

if(document.all)
{

document.all["BGSOUND_ID"].src = "jsilence.mid";
}
else
{

self.iplayer.location.replace("jsplayer.htm?stop");
}
}
catch(err)
{

dispErrorMessage(err);
}
finally
{ }

} // stopSound


HTML Code



<BGSOUND id="BGSOUND_ID" name="BGSOUND_ID" LOOP=1 SRC="jsilence.mid"/>

<iframe id="iplayer" name="iplayer" src="jsplayer.htm" style="vertical-align:top; width:200px; height:22px; scrolling:no; border:0; frameborder:0">
Your browser does not support iFrame.
</iframe>



JavaScript File (jsplayer.htm)


<html>
<body style=margin:3px; bgcolor=#dddddd>

<noscript>
<div class="noscript" style="margin:24px;">
<img src="noscript.gif" alt="In order to access this site you need to enable JavaScript !" />
</div>
</noscript>

<script type="text/javascript" language="JavaScript">
<!--

var sUsrAgt = navigator.userAgent;
var sSearch = self.location.search;
var sNameLC = sSearch.toLowerCase().substring(1);
var nameLen = sNameLC.length;
var sType   = 'unknown';

if (sNameLC.lastIndexOf('.au') >nameLen-6) sType="audio/basic";
if (sNameLC.lastIndexOf('.ra') >nameLen-6) sType="audio/x-pn-realaudio";
if (sNameLC.lastIndexOf('.rm') >nameLen-6) sType="audio/x-pn-realaudio";
if (sNameLC.lastIndexOf('.mid')>nameLen-6) sType="audio/midi";
if (sNameLC.lastIndexOf('.mp3')>nameLen-6) sType="audio/mpeg";
if (sNameLC.lastIndexOf('.wav')>nameLen-6) sType="audio/wav";

if (sSearch.length<3) document.bgColor="white";
else if (sNameLC=='stop' ) document.writeln('<center><small>Audio stopped.</small></center>');
else if (sType=='unknown') document.writeln('<center><small>Unknown audio file type.</small></center>');
else
{ // WRITE HTML TAGS FOR AUDIO PLAYBACK

  if (sUsrAgt.indexOf('Opera')!=-1||sUsrAgt.indexOf('MSIE')!=-1)
document.writeln('<bgsound volume=-1000 LOOP=1 src="'+encodeURI(sSearch.substring(1,99))+'">');
  else document.writeln('<object width=194 height=16 data="'+encodeURI(sSearch.substring(1,99))+'" type="'+sType+'"></object>');
}

-->
</script>
</body>
</html>

Tuesday, May 1, 2012

JavaScript function to TRIM the string

function trim(stringToTrim)                //     Trim the String
{

return stringToTrim.replace(/^\s+|\s+$/g,"");

}

Sunday, April 29, 2012

JavaScript code to send text from HTML page to MS Word


<HTML>
 <HEAD>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <SCRIPT type="text/javascript">


function trim(stringToTrim) 
{


return stringToTrim.replace(/^\s+|\s+$/g,"");
}


function SelectionToWord(theField)
{


var tempVal = eval("document." + theField);
tempVal.focus();
tempVal.select();


if(tempVal.createTextRange)
{


theRange = tempVal.createTextRange();

if(trim(theRange.text).length > 0) // If selection is not empty:
{


if(theRange.execCommand)
{


theRange.execCommand("Copy");


// window.status="Contents highlighted and copied to clipboard!";

var word = new ActiveXObject("Word.Application");   // Start MS Word instance:
word.Documents.Add(); // Create new document:
word.Selection.Paste(); // Paste clipboard contents into the document:
word.Visible = true; // Show MS Word:
}


}
else
{


alert("Please type the text and click the button.........");
}


}
else
{


alert("This feature is not available for this Browser.");
}


}
  </SCRIPT>
 </HEAD>


 <BODY>


 <form action="#" name="test2">


 <P>Please type the text and click the button.</P>


<textarea cols='60' rows='2' name='textWord2' id='textWord2' style='font-size:20; font-weight:bold' > </textarea>


<br><br><br>


 <INPUT type="button" onclick="SelectionToWord('test2.textWord2')" value="Send To MS Word"></INPUT>


 </form>


 </BODY>
</HTML>

Wednesday, November 23, 2011

JavaScript Source code : Disable right mouse click on Browser


<script language=JavaScript>
<!--

//Disable right mouse click Script
var message = "Function Disabled!";

function clickIE4()
{

if (event.button==2)
{

// alert(message);
return false;
}
}

function clickNS4(e)
{

if (document.layers||document.getElementById&&!document.all)
{

if (e.which==2||e.which==3)
{

// alert(message);
return false;
}
}
}

if (document.layers)
{

document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById)
{

document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("/*alert(message);*/return false;");

//-->
</script> 

Sunday, October 30, 2011

JavaScript Event KeyCode Test Page

Source Code:


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JavaScript Event KeyCode Test Page</title>
<SCRIPT type="text/javascript">
focusInput = function()
{
document.getElementById("input").focus();
};

clear = function()
{
var eventTypes = ["onkeydown", "onkeypress", "onkeyup"];
var codeTypes = ["keycode", "charcode", "which"];
for(var event = 0; event < eventTypes.length; event++)
{
for(var code = 0; code < codeTypes.length; code++)
{
var element = document.getElementById(eventTypes[event] + "_" + codeTypes[code]);
while (element.firstChild != null)
{
element.removeChild(element.firstChild);
}
}
}
};

processKeyEvent = function(eventType, event)
{
// MSIE hack
if (window.event)
{
event = window.event;
}

var element = document.getElementById(eventType + "_keycode");
var text = document.createTextNode("'" + event.keyCode + "'");
element.appendChild(text);

element = document.getElementById(eventType + "_charcode");
text = document.createTextNode("'" + event.charCode + "'");
element.appendChild(text);

element = document.getElementById(eventType + "_which");
text = document.createTextNode("'" + event.which + "'");
element.appendChild(text);
};

processKeyDown = function(event)
{
clear();
processKeyEvent("onkeydown", event);
};

processKeyPress = function(event)
{
processKeyEvent("onkeypress", event);
};

processKeyUp = function(event)
{
processKeyEvent("onkeyup", event);
};
</SCRIPT>
</head>
<body>
<h1>JavaScript Event KeyCode Test Page</h1>
<P>Input: <INPUT id="input" type="text" value=""/></P>
<TABLE border="1">
<THEAD>
<TR>
<TH></TH>
<TH>onKeyDown</TH>
<TH>onKeyPress</TH>
<TH>onKeyUp</TH>
</TR>
</THEAD>
<TR>
<TH>event.keyCode</TH>
<TD id="onkeydown_keycode"></TD>
<TD id="onkeypress_keycode"></TD>
<TD id="onkeyup_keycode"></TD>
</TR>
<TR>
<TH>event.charCode</TH>
<TD id="onkeydown_charcode"></TD>
<TD id="onkeypress_charcode"></TD>
<TD id="onkeyup_charcode"></TD>
</TR>
<TR>
<TH>event.which</TH>
<TD id="onkeydown_which"></TD>
<TD id="onkeypress_which"></TD>
<TD id="onkeyup_which"></TD>
</TR>
</TABLE>
<H4>Notable Gotchas</H4>
<UL>
<LI>Firefox and onKeyDown vs. onKeyPressed</LI>
<LI>Firefox and keyCode vs. charCode</LI>
<LI>Enter key and onKeyPress on Firefox vs. IE</LI>
</UL>
<SCRIPT>
window.onload=focusInput;
document.getElementById("input").onkeydown=processKeyDown;
document.getElementById("input").onkeypress=processKeyPress;
document.getElementById("input").onkeyup=processKeyUp;
</SCRIPT>
</body>
</html>

Saturday, October 29, 2011

JavaScript code issues with special characters in URL


Problem Statement:
Browser is showing “Page cannot be found” error for only one document.

Ok, what is the bug here?
Browser is not able to trace the document using the specified URL.

How the problem was identified?
I have verified the database whether the specified document is available or not.  Later, I have taken the document name from database and replaced the document name from the part of the URL in the browser. Then, I can see the document in the browser. Finally, I came to know that the problem is with special characters which are the part of the document name.

Solution provided:

Quick solution provided:
I have updated the database by removing the special character.

Suggested solution:
I have updated the javascript code as below to handle special characters in URL.
Previous Code: -
location.href = “<%=url%>”;
Updated Code: -
location.href = escape(“<%=url%>”);

Thursday, October 27, 2011

IE & Firefox Browser Compatibility


Introduction

The purpose of this white paper is to compare the compatibility between Internet Explorer 6.0 and Mozilla Firefox 1.5 with reference to programming consideration so as the web application will be compatible with both the browser.

Overview

In Firefox, JavaScript DOM is not properly implemented and has its flaws. 

Case 1:  Square brackets are preferable while using arrays.

Internet Explorer

Ø       alert(arr(2));
    
Compatible with Internet Explorer and Firefox

Ø       alert(arr[2]);

Case 2: getElementById for IE works for name as well as id attributes. For FF, it works only for id attribute.

Internet Explorer

Ø       timeData.innerHTML = "<select name=rt"></select>";

Compatible with Internet Explorer and Firefox

Ø       timeData.innerHTML = "<select name=rt id=rt"></select>";


Case 3:  While creating HTML elements using DOM, we should not use its HTML code to create it.

Internet Explorer

Ø       var opt = document.createElement(“<option value=\"Firefox Browser\">”);

Compatible with Internet Explorer and Firefox

Ø       var opt = document.createElement(“option”);

Ø       opt.value=”Firefox Browser”;

Case 4:  While creating HTML elements using DOM, we should not use its HTML code to create it.

Internet Explorer

Ø       var docLink = document.createElement("<a>");

Compatible with Internet Explorer and Firefox

Ø       var docLink = document.createElement("a");

Case 5:  While creating HTML elements using DOM, we should not use its HTML code to create it.

Internet Explorer

Ø       var grpTab = document.createElement("<table cellspacing=0 cellpadding=3 width=98% bordercolor=gray align=center>");

Ø       grpTab.className = "tab";

Ø       <style>
.tab
{
border-left: thin solid;
border-right: thin solid;
border-top: thin solid;
border-bottom: thin solid;
}       
</style>

Compatible with Internet Explorer and Firefox

Ø       var grpTab = document.createElement(“table”);

Ø       grpTab.style.width="98%";

Ø       grpTab.setAttribute("align", "center");

Ø       grpTab.className = "tab";

Ø       <style>
.tab
{
border-left: thin solid;
border-right: thin solid;
border-top: thin solid;
border-bottom: thin solid;

border: 1px solid gray; 
border-collapse: collapse;             <!-- cellspacing -->
padding: 3px;
}       
               </style>

Case 6:  While creating HTML elements using DOM, we should not use its HTML code to create it.

Internet Explorer

Ø       var msgRow = document.createElement("<tr style=\"height:18px;font-family:verdana;font-size:12px;color:blue\">");

Compatible with Internet Explorer and Firefox

Ø       var msgRow = document.createElement("tr”);

Ø       msgRow.className = "tabrowStyle";

<style>
.tab rowStyle
{
height: 18px;
font-family: verdana;
font-size: 12px;
color: blue;
}
    </style>

Case 7:  While creating HTML elements using DOM, we should not use its HTML code to create it.

Internet Explorer

Ø       remChoice.innerHTML = "<input type=checkbox name=\"orgrem\" value=\"1\">";

Ø       remChoice.setAttribute("disabled","true");

Compatible with Internet Explorer and Firefox

Ø       var chk = document.createElement("input");

Ø       chk.setAttribute("type", "checkbox");

Ø       chk.setAttribute("name", " orgrem");

Ø       chk.setAttribute("value", "1");

Ø       remChoice.appendChild(chk);

Ø       chk.setAttribute("disabled", "true");

Case 8:  .innerText attribute is not working in Firefox

Internet Explorer
Ø       .innerText

Compatible with Internet Explorer and Firefox

Ø       .innerHTML.replace(/\&lt;/g,"<").replace(/\&gt;/g,">")

Case 9:  window.event is not working in Firefox.

Internet Explorer

Ø       <input type="text" name="txt1" onKeyPress="SearchName(this, selList)" value="<Type To Search>" onClick="javascript:this.value='';">
    
Ø       function SearchName(txtObj, selObj)
{
keyPressed = window.event.keyCode;
}

Compatible with Internet Explorer and Firefox

Ø       <input type="text" name="txt1" onKeyPress="SearchName(this, selList, event)" value="<Type To Search>" onClick="javascript:this.value='';">

Ø       function SearchName(txtObj, selObj, e)
{
                         if(window.event)
                   keyPressed = window.event.keyCode;      //  IE
     else
                   keyPressed = e.which;                           //  Firefox
}

Case 10:  removeNode( ) is not working in Firefox

Internet Explorer

Ø       frm.comp.removeNode(true);
    
Compatible with Internet Explorer and Firefox

Ø       var temps = frm.comp;

Ø       temps.parentNode.removeChild(temps);


Case 11:  insertBefore( ) is not working in Firefox.

Internet Explorer

Ø       document.frm.insertBefore(tab);
    
Compatible with Internet Explorer and Firefox

Ø       document.frm.appendChild(tab);


  Case 12:  window.showModalDialog( ) is not working in Firefox 1.5.

Internet Explorer

Ø             retval = window.showModalDialog("attach.html",txtData);
    
Compatible with Internet Explorer and Firefox

Ø       if(window.showModalDialog)                         //   IE
{
        retval = window.showModalDialog("attach.html",txtData);
}
else                                              //  Firefox
{
        retval = window.open("attach.html", txtData,
                           "left=100,top=100,width=550,height=300,dependent,modal");
       
        window.onfocus=function()
        {
              if(retval && !retval.closed)

                     retval.focus();
        }
        return false;
}

Ø       The problem with this code is that window.open is asynchronous -- it does not block the JavaScript execution until the window has finished loading. Therefore, you may execute the line after the window.open line before the new window has finished.  You can deal with this by having an onload handler in the new window and then call back into the opener window (using window.opener).