Archive for JavaScript

Updated - CMotion Image Gallery

Download Source ~ CMotion.zip

Screen shot

CMotion Image GalleryDescription: CMotion Image Gallery is a versatile gallery script that uses the most intuitive input devise available, the user’s mouse, to control it! The user can direct both the image scrolling direction and speed just by placing the mouse on either spectrums of the image gallery. Clicking on an image can then load a larger version of it, navigate to a page etc. Apart from the gallery’s dimensions, you can also specify its top scrolling speed, with the script then creating a range from 0-top speed and distributing it evenly across the gallery. Cool!This script works in all modern DHTML browsers- IE5+, NS6/ Firefox 1.0+, Opera 7+. FYI we named it “Cmotion” to stand for “Cursor Motion.” :) Yah.. It’s COOL! It’s working fine as long as there is only one image container (Image Rows) in apage. But if we put more than one container in a page then only the first will work and the rest will do nothing.. Anyway, Ihave the requirement that I need to show three image containers in one page. As the static variables (i.e: “motioncontainer” and etc)is used in the external javascript file, it’s not impossible to make it work unless I modify as my requirement.

Then I decided to take a look at js header file “motiongallery.js” ..
Here is the coding that I modified.. (I have tested with IE6,7 and Firefox 1.5.04 and its working fine.. )

Put the following code inside the <head>Tag.

<style>
#motioncontainer a img{  /*image border color*/
border:  1px solid #ccc;
}

#motioncontainer a:hover img{
/*image border hover color*/
border:  1px solid navy;
}

#motioncontainer a:hover{
 /* Dummy definition to overcome IE bug */ 
color: red;
}
</style>

Put the following code inside the <head>Tag.

 <scriptlanguage=javascript>


//function to enlarge image. Change as desired.
  function enlargeimage(path, optWidth, optHeight){
//set 600px to default width
var actualWidth=typeof optWidth!=“undefined” ? optWidth :  “600px”;
//set 500px to default height
var actualHeight=typeof optHeight!=“undefined” ? optHeight :  “500px”;
var  winattributes=“width=”+actualWidth+
“,height=”+actualHeight+“,resizable=yes”;
window.open(path,“”, winattributes);
}


/* inner func(s)*/
 //1) width of the “neutral” area in the center of the gallery in px
var restarea=6; 
//2) top scroll speed in pixels. Script auto creates a range from 0 to top speed.
var maxspeed=7;
/*
Michael Sync : Dont want to show “End of Gallery” Text
var endofgallerymsg=”<span style=’font-size: 11px’>End of Gallery</span>”
3) message to show at end of gallery. Enter “” to disable message.
*/

var iedom=document.all||document.getElementById;
var scrollspeed=0;
var movestate=“”;

var actualwidth=’;
var  cross_scroll, ns_scroll;
var loadedyes=0;

function ietruebody(){
return (document.compatMode && document.compatMode!=“BackCompat”)?   document.documentElement : document.body;
}

function creatediv(){
statusdiv=document.createElement(“div”);
statusdiv.setAttribute(“id”,“statusdiv”);
nbsp; document.body.appendChild(statusdiv);
statusdiv=document.getElementById(“statusdiv”);
statusdiv.innerHTML=endofgallerymsg;
}

function positiondiv(){
menuheight=parseIntcrossmain.offsetHeight);
mainobjoffsetH=getposOffset(crossmain, “top”);
statusdiv.style.left=mainobjoffset+(menuwidth/2)
-(statusdiv.offsetWidth/2)+“px”;
statusdiv.style.top=menuheight+mainobjoffsetH+“px”;
}

/*
function showhidediv(what){
if (endofgallerymsg!=”")
statusdiv.style.visibility=what;
}
*/

function motionengine(e){
var  dsocx=(window.pageXOffset)? pageXOffset:ietruebody().scrollLeft;
var  dsocy=(window.pageYOffset)? pageYOffset :ietruebody().scrollTop;
var curposy=window.event? event.clientX : e.clientX? e.clientX:“”;
curposy-=mainobjoffset-dsocx;
var leftbound=(menuwidth-restarea)/2;
var rightbound=(menuwidth+restarea)/2;
if (curposy>rightbound){
  scrollspeed=(curposy-rightbound)/((menuwidth-restarea)/2) * maxspeed;
if (window.righttime)clearTimeout(righttime);
if (movestate!=”left”)moveleft();
}
else if (curposy<leftbound){
scrollspeed=(leftbound-curposy)/((menuwidth-restarea)/2) * maxspeed;
if (window.lefttime)clearTimeout(lefttime);
if (movestate!=”right”)moveright();
}
else
  scrollspeed=0;
} 

function moveleft(){
if (loadedyes){
movestate=“left”;

 if (iedom&&parseInt(cross_scroll.style.left)>(menuwidth-actualwidth)){
cross_scroll.style.left=parseInt(cross_scroll.style.left)-scrollspeed+”px”;
//showhidediv(”hidden”);
//M.Sync : Dont want to show “End of Gallery” Text
}
//else
//showhidediv(”visible”);
//M.Sync : Dont want to show “End of Gallery” Text
}
lefttime=setTimeout(”moveleft()”,10);
}

function moveright(){
if (loadedyes){
movestate=“right”;

 if (iedom&&parseInt(cross_scroll.style.left)<0){
cross_scroll.style.left=parseInt(cross_scroll.style.left)+scrollspeed+”px”;
//showhidediv(”hidden”);
//M.Sync : Dont want to show “End of Gallery” Text
}
//else //M.Sync : Dont want to show “End of Gallery” Text
//showhidediv(”visible”);
}
righttime=setTimeout(”moveright()”,10);
}

function  getposOffset(what, offsettype){
  var/font> totaloffset=(offsettype==“left”)? what.offsetLeft: what.offsetTop;
  var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype==“left”)? totaloffset+parentEl.offsetLeft :  totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)return true;
return false;
}

function stopmotion(e){
if ((window.event&&!crossmain.contains(event.toElement)) || (e && e.currentTarget && e.currentTarget!= e.relatedTarget && !contains_ns6(e.currentTarget, e.relatedTarget))){
if (window.lefttime) clearTimeout(lefttime)
if (window.righttime) clearTimeout(righttime)
movestate=”"
}
}

//Main Funcs

function  init(obj,divGallery, noBrCtr){
//crossmain=document.getElementById? document.getElementById(obj.id) : document.all[obj.id];
//alert(obj.id);
crossmain = obj;
menuwidth=parseInt(crossmain.style.width)
mainobjoffset=getposOffset(crossmain, “left”)
cross_scroll=document.getElementById? document.getElementById(divGallery) : document.all[divGallery];
actualwidth=document.all? cross_scroll.offsetWidth : document.getElementById(noBrCtr).offsetWidth;

crossmain.onmousemove=function(e){
motionengine(e);
//alert(”move”);
}

crossmain.onmouseout=function(e){
stopmotion(e);
//showhidediv(”hidden”);
//M.Sync : Dont want to show “End of Gallery” Text
}
loadedyes=1;

/* //Michael Sync : Dont want to show “End of Gallery” Text
if (endofgallerymsg!=”"){
creatediv()
positiondiv()
}
*/
}

</script>

Put the following code inside the <body>Tag.

< divid=“Div0 style=“position:relative;width:450px;height:150px;overflow:hidden;”        onmouseover=“init(this,’mgallery’,'tContainer’);”>
<div id=“mgallery” style=“position:absolute;left:0;top:0;white-space:nowrap;”>
<nobr id= “tContainer”><a href= “javascript:enlargeimage(’dynamicbook1.gif’)”>
<img  src=“dynamicbook1.gif”border =1></a> < a href= “javascript:enlargeimage(’dynamicbook1.gif’, 300,300)”><img   src=“dynamicbook1.gif”border=1></a>
<a href=“http://www.dynamicdrive.com”><img src=”dynamicbook1.gif”border=1></a>
<a href=“#”><img src=“dynamicbook1.gif”border=1></a> <a href=“#”><img src=“dynamicbook1.gif”border=1></a> <a href=“#”>
<img src=“dynamicbook1.gif”border=1></a> <a href=”#”>
<img src=“dynamicbook1.gif”border=1></a> <a href=”#”>
<img src=“dynamicbook1.gif”border=1></a> <a href=”#”>
<img src=“dynamicbook1.gif”border=1></a></nobr>
</div>
</div> 

<divid=“Div1″ style=“position:relative;width:450px;height:150px;overflow:hidden;” onmouseover=“init(this,’Div2′,’tContainer2′);”>
<div id=“Div2″style=“position:absolute;left:0;top:0;white-space:nowrap;”>
<nobr id=“tContainer2″><a href=“javascript:enlargeimage(’dynamicbook1.gif’)”>
<img src=“dynamicbook1.gif”border=1></a> <a href=“javascript:enlargeimage(’dynamicbook1.gif’, 300,300)”><img  src=“dynamicbook1.gif”border=1></a>
<a href=“http://www.dynamicdrive.com”><img src=”dynamicbook1.gif”border=1></a>
<a href=“#”><img src=“dynamicbook1.gif”border=1></a> <a href=“#”><img src=“dynamicbook1.gif”border=1></a> <a href=“#”>
<img src=“dynamicbook1.gif”border=1></a> <a href=”#”>
<img src=“dynamicbook1.gif”border=1></a> <a href=”#”>
<img src=“dynamicbook1.gif”border=1></a> <a href=”#”>
<img src=“dynamicbook1.gif”border=1></a></nobr>
</div>
</div>

Fav Links

JavaScript Virtual Keyboard
By Dmitry Khudorozhkov
http://www.codeproject.com/jscript/jvk.asp

Hiding HTML/SCRIPT… I think it IS possible!
http://www.siteexperts.com/tips/hideit/index.asp

Cross-browser BlendTrans Filter JavaScript
http://www.brainerror.net/scripts_js_blendtrans.php

Dynamic Drive
http://www.dynamicdrive.com/

Reflection.js
Reflection.js 1.5 allows you to add reflections to images on your webpages. It uses unobtrusive javascript to keep your code clean.
It works in all the major browsers - Internet Explorer 5.5+, Mozilla Firefox 1.5+, Opera 9+ and Safari. On older browsers, it’ll degrade and your visitors won’t notice a thing. Best of all, it’s under 5KB.

http://cow.neondragon.net/stuff/reflection/
http://cow.neondragon.net/

JScript Tree List Control with Resizable Columns
By Nathan Ridley.
http://www.codeproject.com/jscript/jstreelistcontrol.asp

Adding and Removing Listitem from ListBox

<html>

<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252″>
<meta name=”GENERATOR” content=”Microsoft FrontPage 6.0″>
<meta name=”ProgId” content=”FrontPage.Editor.Document”>
<title>New Page 1</title>
<script language=”javascript”>
window.onload = function(){
//var strCook = document.cookie;

}
function loadStates(){
var oLst1 = document.getElementById(”Select1″);
var oLst2 = document.getElementById(”Select2″);

if(document.cookie != “” && document.cookie != oLst1.selectedIndex){
lbl.style.visibility=”visible”;
txt.style.visibility=”visible”;

}
else{
lbl.style.visibility=”hidden”;
txt.style.visibility=”hidden”;
document.cookie = oLst1.selectedIndex;
}

RemoveAll(oLst2);
switch(oLst1.selectedIndex){
case 0: //Myanmar
AddItem(oLst2, “AAA”, “a”);
AddItem(oLst2, “BBB”, “a”);
break;
case 1: //India
AddItem(oLst2, “UP”, “up”);
AddItem(oLst2, “BB”, “b”);
break;
case 2: //US
AddItem(oLst2, “NK”, “nk”);
AddItem(oLst2, “CA”, “ca”);
break;
case 3: //UK
AddItem(oLst2, “LD”, “ld”);
AddItem(oLst2, “CK”, “ck”);
break;

}
}
function RemoveAll(objListBox){
for(var i=objListBox.children.length-1;i>=0;i–)
objListBox.remove(i);
}
function AddItem(objListBox, strText, strId){
var newOpt;
newOpt = document.createElement(”OPTION”);
newOpt = new Option(strText,strText);
newOpt.id = strId;
objListBox.add(newOpt);
}
</script>
</head>

<body>
<SELECT id=”Select1″ name=”Select1″ size=”3″ runat=”server” style=”width: 168; height: 104″ onclick=”loadStates();”>
<OPTION>Myanmar</OPTION>
<OPTION>India</OPTION>
<OPTION>US</OPTION>
<OPTION>UK</OPTION>
</SELECT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<SELECT id=”Select2″ name=”Select2″ size=”3″ runat=”server” style=”width: 168; height: 106″>
</SELECT>
<p>
<div id=”lbl” style=”visibility:hidden”>ENTER STATE</div>
<input id=”txt” type=text style=”visibility:hidden”></input>
</body>
</html>

Please let me know if this script is not working on ur side.
Thanks.

Adding new row to the existing table - JavaScript

add-row-or-col.jpg

Download Code ~ http://michaelsync.net/demo/HTMLPage1.zip

Note: Preview Code has been removed. Please download the code if you wanna know how to do that.
Ref:

http://www.w3schools.com/js/js_examples_3.asp

Maintain Scroll Position of DIV using JavaScript - ASP.NET 2.0

Some people have some problems in maintaining the position of the DIV. Initially, The most of people are using htc for solving this problem. but there are so many disadvantages of using htc such as it works only in Internet Explorer, it doesn’t work properly with Visual Studio 2005 and so on.

Finally, I got the solution for solving this problem.. Using Javascript for keeping the scroll position is the best way to go.. JavaScript helps us to know the current position of DIV. Plus, we can use HTTP Cookie for storing the value of the previous position of DIV tag.

SouceCode Download : http://michaelsync.net/demo/MaintainScroll.zip


window.onload = function(){
var strCook = document.cookie;
if(strCook.indexOf("!~")!=0){
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS+2,intE);
document.getElementById("grdWithScroll").scrollTop = strPos;
}
}
function SetDivPosition(){
var intY = document.getElementById("grdWithScroll").scrollTop;
document.title = intY;
document.cookie = "yPos=!~" + intY + "~!";
}

I have tested this code with IE6, 7 and Mozilla Firefox. It’s working very fine.
Please let me know if you have any problem with this coding. Thank you.
Special Thanks to Jim Ross and Eric Pascarello.

UPDATED Maintain Scroll Position of DIV using ASP.NET Ajax by Brad Alcock (Thanks for sending this mail, Brad.)

hi. here’s the code with a very brief explanation on what goes on behind the scenes.

a little different to what you did, but sort of on the same track. I’m sure you can find a method of working around it to fit in with your post ^^

right, my div’s id was panel1, I basically created a cookie for the onscroll of the div in the function SetDivPosition(). the read cookie is read using the stringbuilder in the C# Page_load code underneath.


function SetDivPosition(){
var intY = document.getElementById("Panel1").scrollTop;
var date = new Date();
date.setTime(date.getTime()+(1*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = "cookie1"+"="+intY+expires+"; path=/";
document.title = intY;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==’ ‘) c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

here is the string builder in the page Load. the part in the if(!IsPostback) is there so that when the page is loaded for the very first time, it removes any possibility of a cookie being there (incase the page is returned to within an hour. ) that means the scrollbar will not suddenly jump to a position at arb times like first time page is loaded.
don’t forget to use System.Text; otherwise it will throw an error.


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>");
sbScript.Append("document.cookie = cookie1 + \"=\" + \"\" + -1 + \"; path=/\";");

sbScript.Append("</script>");
// Make use ScriptManager to register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript.ToString(), false);

}
StringBuilder sbScript1 = new StringBuilder();
sbScript1.Append("<script language='JavaScript' type='text/javascript'>");
sbScript1.Append("var strCook = readCookie(\"cookie1\"); "+
"document.getElementById(\"Panel1\").scrollTop = strCook;");
sbScript1.Append("</script>");

// Make use ScriptManager to register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript1.ToString(), false);
}

Regards,
Brad

/*References
*
* Maintain Scroll Position in any Page Element
* http://authors.aspalliance.com/jimross/Articles/MaintainScrollPos.aspx
*
* Remember a Div’s Scroll Position
* http://radio.javaranch.com/pascarello/2005/07/18/1121709316718.html
*/

[digg=http://digg.com/programming/Maintain_Scroll_Position_of_DIV_using_JavaScript_ASP_NET_2_0/]

JavaScript - Working with Database

After reading this coding, you will know the following facts.

  1. How to connect the database in JavaScript
  2. How to use the ADODB.Recordset in JavaScript

As I already put the details comments in coding, I hope you will find it useful.

You can download the sourcecode and MSAccess database from this link.

http://michaelsync.net/demo/JavaScriptDatabaseSrc.zip

****

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=
"http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type
="text/javascript">
<!–
var adOpenDynamic = 2;
var adLockOptimistic = 3;

/* Path of database.
If you put the database "Inventory.mdb" in different location,
you need to specify the correct path to this variable.
But When you are running the webpage from Browsers only,
you should use this keyword "window.location.pathname" for getting
the current location. But If you are using FrontPage,
you hav to specity the static path.
*/
var strDbPath = "C:\\JavaScript Database\\Inventory.mdb";

/*
Here is the ConnectionString for Microsoft Access.
If you wanna use SQL or other databases, you hav
to change the connection string..
eg: SQL => var conn_str = "Provider=sqloledb; Data Source=itdev;" +
"Initial Catalog=pubs; User ID=sa;Password=yourpassword";
*/
var conn_str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDbPath;

function getAdoDb(strAdoType){
if (window.ActiveXObject){
return new ActiveXObject(strAdoType);
}
else{
return new ActiveXObject(strAdoType);
}
}

function showReports(){
try{
var strHtml ="";
strHtml += "<table cellpadding=0 cellspacing=0 border=1 width=500px align=center>";
strHtml += "<tr ><td align=center colspan=4><b>Stock List</b></td></tr>";

//Database Connection
var conn = getAdoDb("ADODB.Connection");
conn.open(conn_str, "", "");

//Recordset
var rs =
getAdoDb("ADODB.Recordset");
strQuery = "SELECT StockID,StockName,ReOrderLevel,IsActive FROM Stocks";
rs.open(strQuery, conn, adOpenDynamic, adLockOptimistic);

if(!rs.bof){
rs.MoveFirst();
while(!rs.eof) {
strHtml += "<tr>";
strHtml += " <td width=\"10px\">" + rs.fields(0).value + "</td>";
strHtml += " <td width=\"50px\">" + rs.fields(1).value + "</td>";
strHtml += " <td width=\"10px\">" + rs.fields(2).value + "</td>";
strHtml += " <td width=\"5px\">" + rs.fields(3).value + "</td>";
strHtml += "</tr>";

rs.MoveNext();
}
}
else{
//No Records.
strHtml += "<tr colspan=4><td align=center><font color=red>No Records.</font></td></tr>";
}
conn.close();
strHtml += "</table>";
document.write(strHtml);
}catch(ex){
alert(ex.message);
}
}

//–>
</script>
<title>
Stock List</title>
</head>
<!–<body onload="show_menu()">
<div id="main" />–>
<body>
<script language="JavaScript">
showReports();
</script>
</body>
</html>