<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3436525727412082104</id><updated>2011-12-28T15:53:38.586-08:00</updated><category term='images'/><category term='effects'/><category term='fade-in'/><category term='magnification'/><category term='popup'/><category term='transparency'/><category term='clock'/><category term='window'/><category term='counter'/><category term='mouse position'/><category term='AJAX'/><category term='map'/><category term='right mouse button'/><category term='digital'/><category term='benchmark'/><category term='simple'/><category term='countdown'/><category term='right click'/><category term='movable'/><category term='context'/><category term='drag and drop'/><category term='chrome'/><title type='text'>Javascript tutorials and lessons</title><subtitle type='html'>Javascript tutorials, lessons and howtos. Free scripts, fully functional and commented. Live demos and source code.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>13</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-9170780654432179077</id><published>2009-04-28T05:16:00.000-07:00</published><updated>2009-04-29T00:37:57.924-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='right click'/><category scheme='http://www.blogger.com/atom/ns#' term='context'/><category scheme='http://www.blogger.com/atom/ns#' term='right mouse button'/><title type='text'>Javascript custom right click (context) menu</title><content type='html'>Today I will cover another aspect of creating web pages without using browsers' standard behavior and capabilities. I will show you how to make your own right mouse button menu and use it instead of this, that the browser draws by default. This allows you to adapt this menus according to you site's needs and can be very useful for some projects. To achieve that I use the oncontextmenu event trigger, which may not be familiar for some of you, cause it is rarely used. It catches the right mouse button clicks, just like the onclick event works for left mouse button.
&lt;br /&gt;&lt;br /&gt;
This script will use &lt;a href='http://javascripthowtos.blogspot.com/2009/02/javascript-mouse-position-capture.html' target='_blank'&gt;my mouse position capture script&lt;/a&gt; to draw the menus at the proper coordinates.
&lt;br /&gt;&lt;br /&gt;
The object constructor will accept three parameters:
&lt;ul&gt;
&lt;li&gt;id - HTML id of the menu)&lt;/li&gt;
&lt;li&gt;menuItems - an array containing all the menu items which will be drawn&lt;/li&gt;
&lt;li&gt;parent - optional parameter which defines the element to which the menu will be applied. If this is not set, document.body will be used.&lt;/li&gt;
&lt;/ul&gt;

The second parameter needs further explanation. The keys of the array menuItems 
will be used as the text, which will be displayed in the menu and the values of
that array will be the functions that will be executed, when the
corresponding menu item is clicked. Values can be either "function() {...}"
code or a predefined function name. Maybe this seems a bit blurry, but read
on and you will see how it's used.
&lt;br /&gt;&lt;br /&gt;
Here is the object constructor:

&lt;pre name="code" class="js"&gt;
function contextMenu(id, menuItems, parent)
{
 //First we need to make sure that we have the obligatory parameters present
 if(typeof id == 'undefined' || typeof menuItems == 'undefined')
  return;
 
 //Remember menu's id cause we will need it in the object's prototypes
 this.id = id;
 
 //If this menu already exists - call a prototype that destroys it, so it can be created again on it's new place.
 //This is executed when we already have the menu drawn on the page and the user has clicked on a new location
 if(document.getElementById(this.id))
  this.destroy();
 
 
 //Create the main menu item - an UL element. I use some styles to make it look pretty much like every browsers' menu, 
 //which will be more familiar to the user
 var menu = document.createElement('ul');
 menu.id = id;
 menu.style.listStyleType = 'none';
 menu.style.margin = 0;
 menu.style.padding = 0;
 menu.style.position = 'absolute';
 menu.style.left = xMousePos;
 menu.style.top = yMousePos;
 menu.style.border = '1px solid #000;';
 menu.style.background = '#eee';
 menu.onmouseover = function() { this.style.cursor = 'pointer'; }
 menu.oncontextmenu = function() { return false; }
 
 //We have the menu created, now we must append it's items.
 for(k in menuItems)
 {
  //Sometimes we need to divide the menus in sections. To do so, I'm using a keyword - 'separator'. 
  //If this keyword is used in any menu item, it will be drawn as a separating line (hr) between 
  //the elements above and beneath it...
  if(menuItems[k] == "separator")
  {
   var delim = document.createElement('hr');
   delim.style.height = '1px';
   delim.style.width = '90%';
   delim.style.margin = 0;
   delim.style.marginLeft = '5%';
   delim.style.padding = 0;
   
   menu.appendChild(delim);
  }
  else //...otherwise we use the text and code from the menuItems array
  {
   //if this is not a valid function - don't create the menu item
   if(typeof menuItems[k] != "function")
    continue;
   
   var menuItem = document.createElement('li');
   menuItem.style.textAlign = 'left';
   menuItem.style.margin = 0;
   menuItem.style.marginLeft = '5px';
   menuItem.style.marginRight = '5px';
   menuItem.style.padding = 0;
   menuItem.innerHTML = k;
   menuItem.onclick = menuItems[k];
   
   menu.appendChild(menuItem);
  }  
 }
 
 
 //Now we have the menu ready we need to append it to it's parent element. 
 //If the third parameter (parent) is omitted - we use the body of the page.
 //Note that the check 'if(typeof parent == "object")' will also fail if we have provided a parent, 
 //but it is not a valid HTML element, thus the document.body will be used instead.  
 if(typeof parent == "object")
  parent.appendChild(menu);
 else
  document.body.appendChild(menu);
 
 //The last thing we need to do is add an event listener to the parent. 
 //We add an onclick event, so when the user clicks outside the menu it will disappear.
 //WARNING! This code overwrites the parent's onclick event listener (if any)! This means 
 //that if you already have a listener defined, it will stop working! Be careful when using 
 //this menu on elements the already have event listeners and always test carefully when implementing!
 menu.parentNode.onclick = methodize(this.destroy, this);
}
&lt;/pre&gt;

This is just a simple menu and the object has just one prototype, which removes the menu from the page:
&lt;pre name="code" class="js"&gt;
//The prototype that removes the menu from the page.
contextMenu.prototype.destroy = function()
{
 document.getElementById(this.id).parentNode.removeChild(document.getElementById(this.id));
}
&lt;/pre&gt;

I will extend this object in the future, allowing customization, submenus and other useful functionality.

To use the code we need to append an event listener to the oncontextmenu event to each element where the menu will be displayed. We can create a custom function that defines our menu items and creates the menu:
&lt;pre name="code" class="js"&gt;
//This is an example function that creates a custom right-click menu
function createContextMenu(id, parent)
{
 var menuItems = new Array();
 
 //You can define a new function using a "function() {...}" code as the value of the array.
 menuItems["Go Back"] = function() { history.go(-1) };
 //You can add a separator by defining a value "separator" for the array element.
 menuItems[0] = "separator";
 menuItems["Reload"] = function() { location.reload(); };
 //You can also use a predefined function - in this case reload(), which is defined in the code that fallows.
 menuItems["My Own Reload"] = reload;
 menuItems[1] = "separator";
 menuItems["Another Function"] = anotherFunction;
 
 new contextMenu(id, menuItems, parent);
 
 return false;
}

//An example custom function that is called when a menu item is clicked
function reload()
{
 location.reload();
}

//An example custom function that is called when a menu item is clicked
function anotherFunction()
{
 alert('Another Function Code...');
}
&lt;/pre&gt;

This function defines an array, which will be used to draw the menu. Some of the functions inside the menu are created with the code "function() {...}" and others are predefined functions, which are also shown in the code above. Note that the keyword 'separator' is a string, so you can still have a function named separator() and use it within the menu. In order for the menu to be working propery, all values of the array must be valid functions. If you misspell a function name, or set a value that is not a function - the menu item will not be displayed.
&lt;br /&gt;&lt;br /&gt;
Finally, a sample HTML that shows you how to use the object:
&lt;pre name="code" class="html"&gt;
&amp;lt;div style='width: 250px; height: 250px; border: 5px solid #333;' oncontextmenu="createContextMenu('myFirstContextMenu', this); return false;"&amp;gt;&amp;amp;nbsp;&amp;lt;/div&amp;gt;
&lt;/pre&gt;

With this code, a menu will appear at the mouse position when you right click on the div. If you click anywhere outside that div, the page will be working normally.

WARNING! When you create a menu with this code it overwrites the parent's onclick event listner (if any)! This means that if you already have a listener defined, it will stop working, which can lead to strange page behavior or brake other scripts' usage! Be careful when using this menu on elements the already have event listeners and always test carefully when implementing!
&lt;br /&gt;&lt;br /&gt;
This is pretty much the simplest menu example. In the future fallow ups to this post I will extend the object to be able to create a menu with sub menus, add the ability to set a custom style for the menu, etc. You can see a demo page &lt;a href='http://enikoloff.info/examples/javascript%20custom%20right%20button%20(context)%20menu/javascript%20custom%20right%20button%20(context)%20menu.html' target='_blank'&gt;here&lt;/a&gt;. You can use the script directly from &lt;a href='http://enikoloff.info/scripts/contextMenu.js' target='_blank'&gt;this url.&lt;/a&gt;
&lt;br /&gt;&lt;br /&gt;
&lt;span style='color: #b11'&gt;P.S. I've received a bug report about this script - it isn't working on Internet Explorer! Unfortunately I had no Windows OS around me when I was creating it and haven't tested on IE. I will fix it soon and advice you to wait for the fix before using the script.&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-9170780654432179077?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/9170780654432179077/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=9170780654432179077' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9170780654432179077'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9170780654432179077'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2009/04/javascript-custom-right-click-context.html' title='Javascript custom right click (context) menu'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-7903040507233548156</id><published>2009-02-28T01:45:00.001-08:00</published><updated>2009-02-28T01:45:47.877-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='popup'/><category scheme='http://www.blogger.com/atom/ns#' term='movable'/><category scheme='http://www.blogger.com/atom/ns#' term='window'/><title type='text'>Javascript movable custom popup(hint) / alert window</title><content type='html'>Often we want to display additional information to the users when they do something particular on our pages. A good example of that is displaying a help/hint window when the user places the mouse over some element on the page. Both javascript and HTML have some innate means of doing this, but they are often inconvenient, i.e. javascript's alert() which takes the control of the page until closed. This is often undesired as we might want the user to see the alert message, but still be able to work with the page. I've made a small object that creates 'windows' that can be used for all the purposes mentioned above. You can create as many windows as you like, and they can also be moved within the page for users' convenience. 
I will start with the main function that creates the object:
&lt;pre name="code" class="js"&gt;
function msgWin(id, title, msg, buttonText, parent, xPos, yPos)
{
 this.id = id; //ID of the html element (div) that will contain our window. This is used within the object, and can also be used for some custom changes outside the object 
 this.title = title; //Title of the window
 this.msg = msg; //Message that will be displayed within the window
 this.parent = parent; //Parent element. This is the id of the HTML element to which we want the window to be attached. If it's left blank, the window will be attached to the body of the page 
 this.left = xPos; //Abscissa (property left) in pixels of the window. If this is not set the window will be positioned in the center of the screen
 this.top = yPos; //Ordinate (property top) in pixels of the window
 
 this.buttonText = buttonText; //text of the button that closes the window
 
 //The fallowing are used within the object to handle moving of the window on the page
 this.moving = 0;
 this.offsetLeft = 0;
 
 this.create(); //Constructor of the object.
}
&lt;/pre&gt;
Now lets see how the window is created:
&lt;pre name="code" class="js"&gt;
msgWin.prototype.create = function()
{
 //Create the main element that will contain the window.
 var w = document.createElement('div');
 w.id = this.id;
 w.style.width = '400px';
 w.style.border = '2px solid #000';
 w.style.position = 'absolute';
 
 if(!this.left) //If we haven't set coordinates for the object, the window will be centered in the middle of the page 
 {
  w.style.left = '50%';
  w.style.top = '50%';
  w.style.marginLeft = '-200px';
  w.style.marginTop = '-50px';
 }
 else //We have set coordinates, we shall position the element according to them
 {
  w.style.left = this.left+'px';
  w.style.top = this.top+'px';
 }
 
 //Create the window title. The essential thing here is that we set an id and some event hanlers that will allow us to update the content and movement of the window
 var t = document.createElement('div');
 t.id = this.id+'_title';
 t.style.borderBottom = '1px dashed #000';
 t.style.textAlign = 'center';
 t.style.fontWeight = 'bold';
 t.style.fontSize = '16px';
 t.innerHTML = this.title;
 t.style.background = '#628db4';
 t.onmouseover = function() {this.style.cursor = 'move';};
 //The fallowing event handlers are set in order to move the element on the page. The properties startMove and stopMoving will be explained later.
 t.onmousedown = methodize(this.startMove, this);
 t.onmouseup = methodize(this.stopMoving, this);
 
 w.appendChild(t); //Append the title to the window.
 
 //Create the window content element. The only interesting thing here is that we set an ID so we can update the content later. 
 var c = document.createElement('div');
 c.id = this.id+'_content';
 c.style.minHeight = '75px';
 c.style.fontSize = '13px';
 c.style.padding = '3px';
 c.innerHTML = this.msg;
 c.style.background = '#dfe3e8'; 
 
 w.appendChild(c);
 
 //Create a dummy div that will allow us to position the close button without interfering with the other layout of the window
 var tmp = document.createElement('div');
 tmp.style.background = '#dfe3e8';
 tmp.style.textAlign = 'center';
 tmp.style.padding = '3px 0 3px 0';
 
 //Now create the close button.
 var b = document.createElement('input');
 b.type = 'button';
 b.value = this.buttonText;
 b.style.width = '100px';
 b.style.border = '1px solid #000';
 b.onmouseover = function() {this.style.cursor = 'pointer';};
 //Add event listener for clicks that will change the display property of the window to 'none', that hides it, so it looks closed  
 b.onclick = function() 
 {
  //The interesting thing here is that we don't need to create another prototype to the msgWin object and use methodize() or any other method to close the window.
  //We have access to the window from the close button itself without depending on an ID or anything else that we used on the other event handlers.
  this.parentNode.parentNode.style.display = 'none';
 };
 
 tmp.appendChild(b); //Append the button to the dummy div..
 
 w.appendChild(tmp); //..and then append them both to the window.
 
 if(this.parent) //If we have set a parent element to contain the window - append the window to it 
  document.getElementById(this.parent).appendChild(w);
 else //otherwise - append it to the body of our page
  document.body.appendChild(w);
 
 return;
}
&lt;/pre&gt;
Now that we have the window created we need to create the prototypes of the object that will handle moving it on the page. We will start with the function that inits the movement:
&lt;pre name="code" class="js"&gt;
msgWin.prototype.startMove = function()
{
 this.moving = 1; //raise a flag that tells us that the window is being moved 
 
 //This is a tricky part. In order to move the window smoothly, without interruption, we need to do it on every mouse move, even outside of the window (its parent element),
 //because if we track mouse movement only within it, when the user moves the mouse quickly, it will not trigger every mousemove event and move the window, but the mouse will
 //go outside of the window and it will stop moving.
 //WARNING!!! The fallowing couple of lines will set two event listeners to the parent element of the window. This will result in overwriting the original ones (if any). 
 //If you have set any other event handlers on that element, their functionality will be lost, which may result in failure or strange behavior of another function on your 
 //page! If you don't understand exactly what this code does be careful when using this object. I advice you to test it very carefully and add this object to your page 
 //only when you are sure it will not brake something else! If you have some issues, you can contact me and I will try to help you with a solution to your particular 
 //problem. 
 document.getElementById(this.id).parentNode.onmousemove = methodize(this.stopMove, this);
 document.getElementById(this.id).parentNode.onmouseup = methodize(this.stopMove, this); //add the same handler on mouse up, just to be sure it will be executed properly 
 
 var el = document.getElementById(this.id);
 
 el.style.zIndex = 2; //Move the window in front of the other elements on the page (including another windows created with this object)
 
 //Calculate the offset of the mouse from the left border of the window. 
 if(el.style.left.indexOf("%") != -1) //If the window has been positioned in the middle of the page, we need to convert the % to pixel value.
  var l = screen.width/2+parseInt(el.style.marginLeft);
 else //otherwise just get the integer value of the position
  var l = parseInt(el.style.left); 
 
 this.offsetLeft = xMousePos - l; //Calculate the offset
 
 return;
}
&lt;/pre&gt;
The next prototype - the one that moves the window on the page: 
&lt;pre name="code" class="js"&gt;
msgWin.prototype.move = function()
{
 if(!this.moving) //if the flag is not raised we know that the window is not being moved, therefor we must stop the function execution
  return;
 
 var el = document.getElementById(this.id);
 
 //Unset any margins set to the element and move it to it's new location, minding the offset of the mouse from it's left border
 el.style.margin = '0';
 el.style.left = (xMousePos - this.offsetLeft)+"px"; //Use the mouse offset that we calculated within startMove, to position the window properly on it's new place
 el.style.top  = (yMousePos - 10)+"px"; //We need to set element's ordinate a bit above the mouse position, cause otherwise the mouse will always be outside the window and it will be impossible to stop window's movent.
 
 return;
}
&lt;/pre&gt;
Finally, we've got to the last prototype that stops the movement of the element: 
&lt;pre name="code" class="js"&gt;
msgWin.prototype.stopMoving = function()
{
 this.moving = 0; //Unset the flag, so the next time move() is called it will not change the position of the window.
 
 document.getElementById(this.id).style.zIndex = 1; //Set the z-index of the window back to a lower value, but still a positive one, cause this way it will be drawed over the other page elements, which is generally the desired position.
 
 return;
}
&lt;/pre&gt;
This is it. The code above gives us a pretty convenient way to alert the user for something or just show him a message, without interrupting whatever he is doing. There are several different ways of using this object, depending on where you want it to pop up. If you want to use it as an alert to the user, use something like this:
&lt;pre name="code" class="js"&gt;
new msgWin('myId', 'Alert', 'Message', 'Close');
&lt;/pre&gt;
This will create a window in the center of the screen, with title "Alert" and content "Message". It is very useful instead of javascrpit's alert(), cause the user can keep the window open (probably move it) and still be able to work with the rest of the page.
&lt;br /&gt;
Another convenient place to pop it up is at the mouse position. This is easily done using my &lt;a target='_blank' href="http://javascripthowtos.blogspot.com/2009/02/javascript-mouse-position-capture.html"&gt;mouse position capturing script&lt;/a&gt;. You should add this script to your page and then create the window as fallows:
&lt;pre name="code" class="js"&gt;
new msgWin('myId', 'Popup', 'Message', 'Close', '', xMousePos, yMousePos);
&lt;/pre&gt;
This will create the window at the mouse position, which is usable for hints and help messages.
&lt;br /&gt;
You can also show it at a fixed location with a code like this:
&lt;pre name="code" class="js"&gt;
new msgWin('myId', 'Popup', 'Message', 'Close', '', 400, 200);
&lt;/pre&gt;
This will draw the window on the 400th pixel from the left of the screen and the 200th from it's top.
&lt;br /&gt;
No matter where you show the window, don't forget that it can be moved by the user and can also be closed. "Closing" a window actually just hides it, so if you want to show it again, you can do it without creating it from scratch. If you have a window, created with the code:
&lt;pre name="code" class="js"&gt;
var myMsgWin = new msgWin(...);
&lt;/pre&gt;
and the user closes it, you can later show it again by calling it's prototype show():
&lt;pre name="code" class="js"&gt;
myMsgWin.show();
&lt;/pre&gt;

Experiment with the object as it's functionality can be used in a lot of different ways and occasions. Remember to use it with caution when appending it to elements that already have event listeners for mouse move and mouse up, cause it overwrites them!
&lt;br /&gt;
&lt;a target='_blank' href="http://enikoloff.info/examples/javascript%20movable%20custom%20message%20window/javascript%20movable%20custom%20message%20window.html"&gt;Here&lt;/a&gt; you can see an example page for creating several windows with the object.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-7903040507233548156?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/7903040507233548156/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=7903040507233548156' title='11 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/7903040507233548156'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/7903040507233548156'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2009/02/javascript-movable-custom-popuphint_28.html' title='Javascript movable custom popup(hint) / alert window'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>11</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-9112387020464947837</id><published>2009-02-27T13:49:00.000-08:00</published><updated>2009-02-27T13:54:41.388-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='AJAX'/><title type='text'>AJAX requests class</title><content type='html'>The script I'm going to demonstrate is an object that creates, sends and handles AJAX requests easily. You will be able to send requests with a simple line of code, and those requests can be used to load virtually unlimited content into your site. You don't need any advanced javascript knowledge to use it, as I've made it as simple as it can be. 
First we create the object constructor:
&lt;pre name="code" class="js"&gt;
//The parameters passed to the function are as fallows:
//url - the url of the script that we wanna request. You can use either full or relative to your server urls.
//elmnts - this is either the id of the element that will contain the response from our request, or can also be a whole array of elements
//loadingMsg - if this parameter is set, after the request has been send, the content of the changed element(s) will be set to whatever this variable is set, i.e. "Loading! Please wait...".
function ajaxObj(url, elmnts, loadingMsg)
{
 this.obj = new Object();
 
 this.url = url;
 
 this.loadInto = elmnts;
 
 if(loadingMsg) //if we have set a loading message here it will be put into the changed elemnt(s)
 {
  if(typeof(this.loadInto) != 'object') //if we wanna change just one element, simply do it using it's id
       document.getElementById(this.loadInto).innerHTML.innerHTML = loadingMsg;
    else //or if the 'elmnts' parameter is an array - change all the elements of the array
      {
       for(i in this.loadInto)
       {
        document.getElementById(this.loadInto[i]).innerHTML = loadingMsg;
       }
      }
 }
 
 //This prototype is used to create our request, send it and handle it
 this.init();
} 
&lt;/pre&gt;
Now, the prototype that creates the XMLHttpRequest that will be used for our script.
&lt;pre name="code" class="js"&gt;
//This function tries if different objects are available, untill it finds one that works, cause all the major browsers use different techniques to send the request
ajaxObj.prototype.create = function()
{
 try
   {
    xmlHttp = new XMLHttpRequest();
   }
   catch(e)
   {
    try
    {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
     try
       {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
     catch(e)
      {
       return false;
       }
  }
   } 
 
 this.obj = xmlHttp;
}
&lt;/pre&gt;
Now that we have the request object, we need to make sure it will be handled properly before sending it:
&lt;pre name="code" class="js"&gt;
ajaxObj.prototype.handle = function()
{
 var o = this.obj;
 var into = this.loadInto;
 
 o.onreadystatechange = function() //Set an event handler that is triggered everytime the readystate of the object has changed
   {
    if(o.readyState == 4) //If the readyState is 4, the request has been completed - we can proceed with using the response
      {
       if(typeof(into) != 'object') //if we want to change just one element - set it's innerHTML equal to the response 
        document.getElementById(into).innerHTML = o.responseText;
       else //otherwise - we have more than one elements to change. We must first split the data that is returned into parts for each one of the elements and then update them
       {
        temp = o.responseText.split("@@");
        
        for(i in into)
        {
         document.getElementById(into[i]).innerHTML = temp[i];
        }
       }
      }
 }
}
&lt;/pre&gt;
The important thing about the above prototype is that if we want to change more than one element, we need to put delimeters in the response. The delimeter I've chosen is "@@", as this symbols are very rarely used in the content of a web page. 
We have a request, we can handle it properly, the only thing left is to send it:
&lt;pre name="code" class="js"&gt;
//This prototype simply sends the request to the desired url
ajaxObj.prototype.send = function()
{
   this.obj.open('GET', this.url, true);
   this.obj.send(null);
}
&lt;/pre&gt;
There's just one more prototype that's left, the one that initializes the object:
&lt;pre name="code" class="js"&gt;
//This prototype calls all the other ones in the proper order. It's not really necessary, cause we can just call 
//this prototypes from within the object constructor, but I use it, cause I'm planning to extend this object in the future. 
ajaxObj.prototype.init = function()
{
 this.obj = null;
 
 this.create();
 
 this.handle();
 
 this.send();
}
&lt;/pre&gt;

To create a new request you just need to create a new ajaxObj object. Here is an example:
&lt;pre name="code" class="js"&gt;
new ajaxObj('myscript.php', 'myTestElement', 'Loading! Please wait...');
&lt;/pre&gt;

This line of code will send a request to "myscript.php" and will put the response into and element on the page with the id "myTestElement". While the request has been processed "myTestElement" will contain the text "Loading! Please wait...". You can have anything in the .php file that is being requested, i.e. something extracted from a database/read from a file and formatted in HTML. There are two important things to remember when using the object - to use the delimeter "@@" when you send a request for changing more than one element and change only elements that have the innerHTML property (i.e. div, span, td), cause the script will not work with, say &amp;lt input&amp;gt elements.  
&lt;br /&gt;
This is pretty much the simplest way of dynamically loading content within a web page, yet it can be very usefull even for big and complicated pages. However, it is far from being good enough to meet everyone's needs. I will extend it in time, while keeping things simple and understandable. 
&lt;br /&gt;
You can see an example page &lt;a target='_blank' href='http://enikoloff.info/examples/ajax%20requests%20class/ajax%20requests%20class.html'&gt;here&lt;/a&gt; and the file that contains the object can be found &lt;a target='_blank' href='http://enikoloff.info/scripts/ajax.js'&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-9112387020464947837?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/9112387020464947837/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=9112387020464947837' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9112387020464947837'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9112387020464947837'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2009/02/ajax-requests-class.html' title='AJAX requests class'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-7252224441682409363</id><published>2009-02-27T08:40:00.001-08:00</published><updated>2009-02-27T13:55:38.827-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='mouse position'/><title type='text'>Javascript mouse position capture</title><content type='html'>Capturing mouse position on the screen is often needed in creating modern web pages, with better functionality. Here's a small script that captures the mouse position on every mouse move and stores it in a couple of global variables that can be used from anywhere within the page.
&lt;pre name="code" class="js"&gt;
//Add an event listener for mouse move, depending on client browser. 
if(document.layers) 
{ 
 document.captureEvents(Event.MOUSEMOVE);
 document.onmousemove = captureMousePosition;
} 
else if(document.all) 
 document.onmousemove = captureMousePosition;
else if(document.getElementById)  
 document.onmousemove = captureMousePosition;

//Declare the variables that will store the coordinates
var xMousePos = 0; //abscissa
var yMousePos = 0; //ordinate

//Capture the position, again depending on client's browser
function captureMousePosition(e) 
{
 if(document.layers) 
 {
  xMousePos = e.pageX;
      yMousePos = e.pageY;
   } 
   else if(document.all) 
   {
  xMousePos = window.event.x+document.body.scrollLeft;
      yMousePos = window.event.y+document.body.scrollTop;
   } 
   else if(document.getElementById) 
   {
  xMousePos = e.pageX;
      yMousePos = e.pageY;
   }
}
&lt;/pre&gt;
This simple script allows us to know where the mouse is and do a lot of stuff according to it, most commonly - move elements around or knowing exactly where the user has clicked. I use this script oftenly and it will mantioned quite often from now on. Actually, I've already used it in some of the old scripts, but decided to separate it and make it available for you on http://enikoloff.info/scripts/mousePos.js
You can see an example page &lt;a target='_blank' href='http://enikoloff.info/examples/javascript mouse position capture/javascript mouse position capture.html'&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-7252224441682409363?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/7252224441682409363/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=7252224441682409363' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/7252224441682409363'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/7252224441682409363'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2009/02/javascript-mouse-position-capture.html' title='Javascript mouse position capture'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-2093925951828138618</id><published>2008-12-19T01:11:00.001-08:00</published><updated>2009-02-27T08:21:37.242-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='images'/><category scheme='http://www.blogger.com/atom/ns#' term='fade-in'/><category scheme='http://www.blogger.com/atom/ns#' term='effects'/><title type='text'>Javascript image effects, fade-in</title><content type='html'>It's been a long while since my last post, but recently I found some time to write some new scripts. These are object oriented, so they are easier to use and have very little (or no) issues with scope collisions and the like. From now on, I will try to write all examples using OOP and 'classes'.
This script is used to apply effects on pictures in a page. The effect shown in it is "Fade-in" - the image starts fully transparent and smoothly appears till it's fully visible. This is just the first effect of the series, and that is all I will show for today, but there will be additional effects added constantly :) Here's what I've made:

&lt;pre name="code" class="js"&gt;
//THE object constructor (class, etc.)
function imageEffects(elmnt, pics, effectId, steps, time)
{
 //If the required parameters are not passed, show an error and stop.
 if(!elmnt || !pics)
 {
  alert('ERROR: imageEffects object not initialized properly!');
  
  return;
 } 
 
 //Assigning default values of the optional parameters
 if(!effectId)
  var effectId = 1;
 
 if(!steps)
  var steps = 50;
 
 if(!time)
  var time = 1000;
 
 
 this.elmnt = document.getElementById(elmnt); //html element (img) that will be manipulated
 this.pics = pics;          //an array with the pictures that will be shown
 this.steps = steps;         //number of steps for changing pictures
 this.effectId = effectId;       //id of the effect that will be applied. this is for future use
 this.effectTime = time;        //time that will be needed to change between pictures
 this.step = this.steps;        //used to control the smooth changing of the pictures
 this.pic = 0;           //current picture that is being shown
}


//Changes the opacity of any given element. cross browser.
imageEffects.prototype.setOpacity = function(opacity) 
{
   this.elmnt.opacity = (opacity / 100);
   this.elmnt.filter = "alpha(opacity="+opacity+")";
   this.elmnt.MozOpacity = (opacity / 100);
 this.elmnt.KhtmlOpacity = (opacity / 100);
}

//This prototype changes the pictures, handles steps, etc.
imageEffects.prototype.changePic = function(reverse)
{
 //If the previous picture hasn't finished showing, we need to wait
 if(this.step &lt; this.steps)
  return;
 
 //If we got here, the previous picture has finished showing and the user now wants to change it. 
 //Set the step to 0 to start the effect again
 this.step = 0;
 
 if(reverse) //Show previous picture (or if this is the first one - show last)
 {
  if(this.pic == 0)
  {
   this.pic = this.pics.length-1;
  }
  else
   this.pic--;
 }
 else //Show next picture (or if this is the last one - show first)
 {
  if(this.pic == this.pics.length-1)
  {
   this.pic = 0;
  }
  else
   this.pic++;
 }
 
 
 //Change the image
 this.elmnt.src = this.pics[this.pic];
 
 //Determine the time interval that will be used based on the overal time and number of steps 
 var interval = this.effectTime/this.steps;
 
 for(i = 1; i &lt; this.steps+1; i++)
 {
  //call the prototype that visualizes the effect
  setTimeout(methodize(this.setOpacity, this), i*interval);
 }
}


//The fade-in effect. Smoothly changes opacity of the picture from 0 to 100
imageEffects.prototype.setOpacity = function()
{
 //if we've reached the last step - stop the effect. Generally, this soudn't happen, cause it's 
 //controlled by the code that calls the effect, but it's an extra insurance. 
 if(this.step == this.steps)
    return;

 //Determine the opacity that the picture will have at this step.. 
 var opacity = this.step*(100/this.steps);

 //..and apply it to the image. 
 var element = this.elmnt.style; 
 
 element.opacity = (opacity / 100);
   element.filter = "alpha(opacity="+opacity+")";
   element.MozOpacity = (opacity / 100);
   element.KhtmlOpacity = (opacity / 100);
   
   //Go to the next step
   this.step++;
}

//This is a very simple, yet very powerful function that basically allows us to call objects from another 
//scope,in fact, any scope we want, which is not possible with a language construct or anything of the like..   
//There are still a lot of limitations in javascript and this is breaking one of them :)
//This is where I heard of it the first time I think - 
//http://www.tapper-ware.net/2006/12/object-oriented-programming-and-event.html. There are some additional 
//features in the example and I recomend you read it, but we just don't need them here. 
function methodize(methodize_func,methodize_scope)
{
    return (function() { methodize_func.call(methodize_scope); });
}
&lt;/pre&gt;

The html we need to use to get this working is just an image element and some kind of event trigger. We can use any of the event triggers that exist, but I think it's most appropriate to use either onclick or onmouseover. I've set an example page that shows three pictures. The first one is changed onclick. The second one is changed by clicking on the two arrows beneath it. The first arrow shows previous picture and the second one shows next. The last picture is changed onmouseover, and it changes in reverse/descending order. I've used a div and some other elements to position the elements on the page, but the code itself doesn't require anything else except an image. Here is the html:

&lt;pre name="code" class="js"&gt;
&amp;lt;div style="width: 1024px; position: absolute; left:50%; margin-left: -512px; text-align: center"&amp;gt;
&amp;lt;img id="img" src="1.jpg" style="width: 512px" onclick="test2.changePic(1);"&amp;gt;
&amp;lt;br /&amp;gt;&amp;lt;hr /&amp;gt;
&amp;lt;img id="img2" src="2.jpg" style="width: 1024px"&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;
&amp;lt;img id="l_arrow" class="arrow" src="lArrow.gif" onclick="test.changePic(1);"&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;img id="r_arrow" class="arrow" src="rArrow.gif" onclick="test.changePic();"&amp;gt;
&amp;lt;br /&amp;gt;&amp;lt;hr /&amp;gt;
&amp;lt;img id="img3" src="3.jpg" style="width: 1024px" onmouseover="test3.changePic();"&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;

Now that we have the html, we need to create the imageEffects objects for every picture we want to manipulate. These are already used in the html and are named test, test2 and test3. 
Lets create the objects now:

&lt;pre name="code" class="js"&gt;
//The first one will change the pictures for two seconds (2000 miliseconds)
//and will do it in 40 steps
var test = new imageEffects('img', new Array('1.jpg', '2.jpg', '3.jpg'), 1, 40,
2000);

//The second will use the default values for steps and time, which are -
//change the pictures for a second, in 50 steps.
//This one uses the same pictures, but in slightly different order.
var test2 = new imageEffects('img2', new Array('2.jpg', '3.jpg', '1.jpg'));

//The third one will change the pictures for 3 seconds in 100 steps
//This one uses the pictures in completely different order.
var test3 = new imageEffects('img3', new Array('3.jpg', '1.jpg', '2.jpg'), 1,
100, 3000);
&lt;/pre&gt;

This is pretty much it. I've put the code on one of my pages, so you can use it on your page using this code:
&lt;pre name="code" class="html"&gt;
&amp;lt;script type="text/javascript" src="http://enikoloff.info/scripts/imageEffects.js"&amp;gt;&amp;lt;/script&amp;gt;
&lt;/pre&gt;
This will create the imageEffects class on your page. Then all you need to do is create some instances of that object (just as I did with test, test1 and test2) and call them with some event trigger. Don't forget to visit my site where you can find other examples on using this class and other free scripts :)

P.S You can see the example from above &lt;a target='_blank' href='http://enikoloff.info/examples/javascript%20image%20effects%2c%20fade-in/javascript%20image%20effects%2c%20fade-in.html'&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-2093925951828138618?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/2093925951828138618/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=2093925951828138618' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/2093925951828138618'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/2093925951828138618'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/12/javascript-image-effects-fade-in.html' title='Javascript image effects, fade-in'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-2488538184860267629</id><published>2008-09-13T03:19:00.000-07:00</published><updated>2009-01-07T02:10:23.985-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='drag and drop'/><category scheme='http://www.blogger.com/atom/ns#' term='mouse position'/><category scheme='http://www.blogger.com/atom/ns#' term='transparency'/><title type='text'>Javascript drag and drop</title><content type='html'>As promised, I got the &lt;a target="_blank" href="http://javascripthowtos.blogspot.com/2008/09/simplies-javascript-drag-and-drop.html"&gt;simple drag and drop script&lt;/a&gt; further. Lots of the stuff is still the same, but now we actually drag the element. Most of the new code handles getting the mouse position and moving the element according to it. I even made the dragged item transparent, cause I tought it would be useful to see the content that is under it. I also found a bug in the old script. Instead of using window.onmouseup we must use document.onmouseup to make sure the function works in all browsers. Anyways, the simple script was just an example, now this bug is fixed and everything works cross-browser. I think this script is really usefull, so feel free to put it on your site ;)

Here is the javascript code:
&lt;pre name="code" class="js"&gt;
//capture the mousemove event and call a function that will get the position of the cursor
if (document.layers) 
{ 
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} 
else if(document.all || document.getElementById) 
{ 
    document.onmousemove = captureMousePosition;
}

//this variables are used to store the mouse position coordinates
xMousePos = 0; 
yMousePos = 0; 

//this function stores the coordinates into the global variables every time the mouse moves over the page
function captureMousePosition(e) 
{
 if(document.layers) 
 {
  xMousePos = e.pageX;
  yMousePos = e.pageY;
 } 
 else if(document.all) 
 {
  xMousePos = window.event.x+document.body.scrollLeft;
  yMousePos = window.event.y+document.body.scrollTop;
 } 
 else if(document.getElementById) 
 {
  xMousePos = e.pageX;
  yMousePos = e.pageY;
 }
 
 //after we have captured the new mouse position move the dragged element (if there is one) to it 
 if(window.dragged_item)
  moveDraggedItem();
}


//this will store the object that is currently being dragged
var dragged_item = false;

//when the user release the mouse anywhere on the page we need to drop the object.
//creating this global onmouseup event always clears the currently dragged element
document.onmouseup = function()
{
 window.dragged_item = false;
}

//get the element that is being dragged
function get(elmnt)
{
 window.dragged_item = elmnt;
 
 //make the dragged object transparent
 setOpacity(elmnt.id, 50);
}

//drop the element in it's new spot.
function drop(elmnt)
{
 //what we do is access the parent node of the dragged element and remove the element from it.
 //this line works for all objects, no matter if they are part of the whole page (window object) or any other element within the page
 window.dragged_item.parentNode.removeChild(window.dragged_item);
 
 //we won't move the element anymore, so - reset it's position styles
 window.dragged_item.style.position = 'relative';
 window.dragged_item.style.left = 0;
 window.dragged_item.style.top = 0;
 
 //then append the dragged item to it's new parent element
 elmnt.appendChild(window.dragged_item);
 
 //we've droped the element - make it fully visible again
 setOpacity(window.dragged_item.id, 100);
}

//this func changes the opacity of the elements. It makes them transparent. Works in all browsers.
//we will use it to make the dragged element transparent until it is droped.
function setOpacity(id, opacity) 
{
    var object = document.getElementById(id).style;
 
    object.opacity = (opacity / 100);
 object.filter = "alpha(opacity="+opacity+")";
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
}

function moveDraggedItem()
{
 //set the position property to absolute, so we can move the element according to the mouse cursor
 window.dragged_item.style.position = 'absolute';

 //now move it to the mouse coordinates. I add 5 pixels to the bottom right, cause otherwise the
 //onmouseup event on the elements that the dragged one is being droped to, will not work..
 window.dragged_item.style.left = xMousePos+5;
 window.dragged_item.style.top = yMousePos+5;
}
&lt;/pre&gt;

The HTML that is used has not changed a lot, except that we now need to put an id to each element. The id is used in setting the opacity of elements. Here's the HTML I used for testing:

&lt;pre name="code" class="html"&gt;
&amp;lt;div onmousedown='get(this);' id='1' style='border: 1px solid #333; width: 50px; height: 50px; background: #f99'&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div onmousedown='get(this);' id='2' style='border: 1px solid #333; width: 50px; height: 50px; background: #9f9'&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div onmousedown='get(this);' id='3' style='border: 1px solid #333; width: 50px; height: 50px; background: #99f'&amp;gt;&amp;lt;/div&amp;gt;

&amp;lt;div onmouseup='drop(this);' id='a' style='border: 1px solid #333; width: 200px; height: 200px;'&amp;gt;&amp;lt;/div&amp;gt;

&amp;lt;div onmouseup='drop(this);' id='b' style='border: 1px solid #333; width: 200px; height: 200px'&amp;gt;&amp;lt;/div&amp;gt;
&lt;/pre&gt;

You can see the new drag and drop script &lt;a target="_blank" href="http://javascripthowtos.freehostia.com/javascript%20drag%20and%20drop/javascript%20drag%20and%20drop.html"&gt;here&lt;/a&gt;. Just "save page as..." to get the code, for some reason freehostia (or is it just me?) is having some issues with the rar files i used to upload and I don't have the time to fix it now..&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-2488538184860267629?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/2488538184860267629/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=2488538184860267629' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/2488538184860267629'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/2488538184860267629'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/09/as-promised-i-got-simple-drag-and-drop.html' title='Javascript drag and drop'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-9065317864377626513</id><published>2008-09-07T02:12:00.000-07:00</published><updated>2009-01-06T06:51:44.220-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='drag and drop'/><category scheme='http://www.blogger.com/atom/ns#' term='simple'/><title type='text'>Simplies javascript drag and drop</title><content type='html'>Drag and drop was something very common for desktop applications and yet rarely found on a web page. Well, a lot of things changed and over the last few years web pages are becoming more and more flexible and functional. Having &lt;a href="http://javascripthowtos.blogspot.com/2008/09/javascript-on-google-chrome.html"&gt;faster browsers&lt;/a&gt; and lots of big, complicated projects (i.e Gmail) is pushing web masters and coders to offer more and more functionality within their pages. In this article I will show you what is the simplies way to implement a drag and drop interface. I call it 'simpliest', cause that's what it is - the very simple, ugly and primitive way to implement drag and drop. Funny thing is, that drag and drop is so commonly mistaken for something so hard to accomplish, that a lot of people are scared to even think about implementing it. Here I'll show you how with as little as 10-15 lines of code you can have drag and drop, working on each and every element on your page. 
&lt;br /&gt;&lt;br /&gt;
First, we need to get the dragged element and store it somewhere. This will be triggered by a onmousedown event:
&lt;pre name="code" class="js"&gt;
//this will store the object that is currently being dragged
var dragged_item = false;


//get the element that is being dragged
function get(elmnt)
{
        //simply save the element (not it id or something - the whole HTML element) into our global var
 window.dragged_item = elmnt;
}
&lt;/pre&gt;
Now we can simply add a &lt;span style="font-style:italic;"&gt;onmousedown='get(this);'&lt;/span&gt; to any object that we want to be able to drag and drop. Having the element in window.draged_item we can 'drop' it somewhere else: 
&lt;pre name="code" class="js"&gt;
//drop the element in it's new spot.
function drop(elmnt)
{
 //what we do is access the parent node of the dragged element and remove the element from it.
 //this line works for all objects, no matter if they are part of the whole page (window object) or any other element within the page
 window.dragged_item.parentNode.removeChild(window.dragged_item);
 
 //then append the dragged item to it's new parent element
 elmnt.appendChild(window.dragged_item);
}
&lt;/pre&gt;
Now all we need to do is add a &lt;span style="font-style:italic;"&gt;onmouseup='drop(this);'&lt;/span&gt; event trigger to every object on the page where we want to be able to drop stuff into. Voila, actually this simple two functions are enough for a drag and drop functionality. However, I will add something else to make things a bit better: 
&lt;pre name="code" class="js"&gt;
//when the user release the mouse anywhere on the page we need to drop the object.
//creating this global onmouseup event always clears the currently dragged element
window.onmouseup = function()
{
 window.draged_item = false;
}
&lt;/pre&gt;
Not having this global onmouseup trigger will cause the elements to be dragged forever. The user can actually click the mouse somewhere on a blank space within the page, but he will still be able to drop the element once he clicks on another element, which has a &lt;span style="font-style:italic;"&gt;onmouseup='drop(this);'&lt;/span&gt; trigger.. Creating the global function handles that and makes sure that when the user has released the mouse button the element will be droped, either onto it's new location, or into it's old. &lt;br /&gt;
That's it for now, I'll surely write more about the subject. Soon I will show you how to actually drag the element on the page, not just imagine that it is being dragged :) You can see two demos of the above code. In the first one I use some div elements. It can be seen &lt;a href="http://javascripthowtos.freehostia.com/simpliest%20javascript%20drag%20and%20drop/simpliest%20javascript%20drag%20and%20drop.html"&gt;here&lt;/a&gt;.
&lt;br /&gt;In the &lt;a href="http://javascripthowtos.freehostia.com/simpliest%20javascript%20drag%20and%20drop/simpliest%20javascript%20drag%20and%20drop2.html"&gt;second demo&lt;/a&gt; I use some unordered lists. In this demo you can see what I mean by ugly drag and drop - you can drag the list elements from one list to another, but while doing it you select some of the text, some of it is still selected when you drop the element, etc, etc. Next time I will show you how to fix this issues.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-9065317864377626513?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/9065317864377626513/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=9065317864377626513' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9065317864377626513'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9065317864377626513'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/09/simplies-javascript-drag-and-drop.html' title='Simplies javascript drag and drop'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-53959357802997277</id><published>2008-09-05T05:29:00.001-07:00</published><updated>2008-09-05T05:33:09.563-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='chrome'/><category scheme='http://www.blogger.com/atom/ns#' term='benchmark'/><title type='text'>Javascript on Google Chrome</title><content type='html'>This morning I found something very interesting. The last few days, after Google's new open source browser &lt;a href="http://www.google.com/chrome"&gt;Chrome&lt;/a&gt;'s beta version has been released, there have been a lot of discussions on how good or bad it is. One of the things that amased me is the fallowing test: &lt;br /&gt;&lt;br /&gt;
&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.sfu.ca/~cyrille/news/CFM.gif"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px;" src="http://www.sfu.ca/~cyrille/news/CFM.gif" border="0" alt="" /&gt;&lt;/a&gt;&lt;br /&gt;
It's clear too see that Chrome is much faster than other browsers in terms of javascript execution. Google were right to tell that this browser will be much more 'usable' for rich web applications, as having fast javascript means that you can build stuff on the web that runs almost as smoothly as desktop applications. This is great news to me, and a lot of other developers, I believe. So, congrats guys, let's now hope that Chrome's issues will soon be fixed and there will not be lots of differences on how it handles the same code, compared to other browsers... :)
&lt;br /&gt;&lt;br /&gt;
P.S You can run the tests from the picture &lt;a href="http://wd-testnet.world-direct.at/mozilla/dhtml/funo/jsTimeTest.htm"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-53959357802997277?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/53959357802997277/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=53959357802997277' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/53959357802997277'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/53959357802997277'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/09/javascript-on-google-chrome.html' title='Javascript on Google Chrome'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-1446138808346584909</id><published>2008-09-01T13:11:00.001-07:00</published><updated>2009-01-06T06:52:40.324-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='counter'/><category scheme='http://www.blogger.com/atom/ns#' term='clock'/><category scheme='http://www.blogger.com/atom/ns#' term='countdown'/><category scheme='http://www.blogger.com/atom/ns#' term='digital'/><title type='text'>Javascript digital countdown clock</title><content type='html'>This is the conclusion of the digital clocks scripts. A countdown clock that is made in pretty much the same way as the others, but it countdowns a given time to zero. This has a lot of "real life" applications. IMHO, maybe the most appropriate usage is to tell the user how much session time he has left. How much time he has to spend waiting for that damn download to begin, etc., etc.

Lots of the code is about the same as in the &lt;a href="http://javascripthowtos.blogspot.com/2008/08/do-you-wanna-have-clock-on-your-pages-i.html"&gt;clock&lt;/a&gt; and the &lt;a href="http://javascripthowtos.blogspot.com/2008/08/javascript-digital-counter.html"&gt;counter&lt;/a&gt;. Here it is: 

&lt;pre name="code" class="js"&gt;
window.onload = function()
{
 //create the clock just after the page has loaded
 draw_clock('countdown', '00:00:04');
}

function draw_clock(id, starting_time)
{
 //create the div that will hold the clock
 var clock = document.createElement('div');
 
 clock.id = id;
 
 //you can change the style of the clock ie to position it at a specific place on the page
 //i'll put this one approximately in the center of the page, but you can adjust that to fit your needs
 clock.style.position = 'absolute';
 clock.style.left = '50%';
 clock.style.top = '50%';
 clock.style.marginLeft = '-50px';
 clock.style.marginTop = '-20px';
 
 //keep the current time in an unexisting property (for the div element) - 'time'. Instead of declaring a global variable
 //you can use the current objects you have. This makes it a lot easier to remember what is what. If you are familiar 
 //with OOP, you can go even furher by declaring new javascript objects. Well, I will digg further into that OOP stuff later,
 //in another script :)
 clock.time = starting_time; 
 
 //get the current time and set it as div's innerHTML, using a function that formats it to look good on the page
 clock.innerHTML = get_clock_innerHTML(clock.time);

 //add the element to the page
 document.body.appendChild(clock);
 
 //set the timer which will update the clock. The interval can also be set to more or less than a second. 
 //If you need to update the time in another interval of time, say 15 seconds, you can use 15000 as the second argument to setInterval()
 window.countdown_interval = setInterval("clock_timer('"+id+"')", 1000);
}

function get_clock_innerHTML(time)
{
 //an array that stores the symbols which draw the good old-fashioned digital clock :) 
 //IMPORTANT: don't change the alignment or anything else on this array, cause this will cause the clock to look uglier, or even not work
 var digits = " _     _  _     _  _ _   _  _    "+
     "| | |  _| _||_||_ |_  | |_||_| . "+
     "|_| | |_  _|  | _||_| | |_| _| . "+
     "                                 ";

 //put the symbols inside a &amp;lt;pre&amp;gt; tag to make sure they will be displayed just like they are written in the array.
 //you can also change the style settings i've set
 var data = "&amp;lt;pre&amp;gt;&amp;lt;span style='color: #181; background: #111; font-size: 10px;'&amp;gt;";

 //loop trough the four 'rows' of the array and display the appropriate symbols
 for(r = 0; r &lt; 100; r += 33)
 {
  for(i = 0; i &lt; time.length; i++)
  {
   for(c = (time[i])*3 + r , b = 0; b &lt; 3; b++, c++)
   {
    if(isNaN(c))
     c = 10*3+r;

    data += digits[c];
   }
  }

  data += "&amp;lt;br /&amp;gt;";
 }
 
 data += "&amp;lt;/span&amp;gt;&amp;lt;/pre&amp;gt;";

 return data;
}

function clock_timer(id)
{
 var clock = document.getElementById(id);

 //get the current time and split it into hours minutes and seconds
 var tmp = clock.time.split(":");
 
 var hours   = tmp[0];
 var minutes = tmp[1];
 var seconds = tmp[2];
 
 //check what to decrement. If the seconds have reached zero we need to change either the minutes or both - minutes and hours
 if(seconds == 0)
 {
  //if the minutes have reached zero, decrement the hours and reset minutes and seconds.
  if(minutes == 0)
  {
   hours--;
   minutes = 59;
    seconds = 59;
  }
  else //just decrement the minutes and reset seconds
  {
   minutes--;
   seconds = 59;
  }
 }
 else //nothing interesting happend this last second - just decrement seconds and go on :)
  seconds--;
 
 //if the time has elapsed - call the function to destroy the counter and do someting else if you need to
 if(hours == 0 &amp;&amp; minutes == 0 &amp;&amp; seconds == 0)
  countdown_finished(id);
 
 //Save the new time in the appropriate form of HH:MM:SS
 clock.time = ((hours &lt; 10) ? "0"+parseInt(hours) : hours)+
 ":"+ ((minutes &lt; 10) ? "0"+parseInt(minutes) : minutes) +
 ":"+ ((seconds &lt; 10) ? "0"+parseInt(seconds) : seconds);
 
 //update the clock with the new time
 clock.innerHTML = get_clock_innerHTML(clock.time);
}
&lt;/pre&gt;

That was easy, everything looks just like the counter, except we're counting down this time. Here is a little something that makes a lot of difference - the countdown_finished() function. It is called when the time has elapsed. This is the place where you can stop the countdown, alert() the appropriate message to the user, etc., etc. Do what you have to do when the time has elapsed. Here are some examples of what you might want to do:

&lt;ul&gt;
&lt;li&gt;The simpliest one - stop the countdown and tell the user the time has elapsed:
&lt;pre name="code" class="js"&gt;
function countdown_finished(id)
{
 //clear the interval, cause the time has elapsed
 clearInterval(window.countdown_interval);
 
 alert('The time has elapsed!');
}
&lt;/pre&gt;
You can &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock.html"&gt;see a demo here&lt;/a&gt; and &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock.zip"&gt;download the code from here&lt;/a&gt;.
&lt;/li&gt;
&lt;br /&gt;
&lt;li&gt;Again, tell the user the countdown has finished, but this time remove the clock from the page:
&lt;pre name="code" class="js"&gt;
function countdown_finished(id)
{
 //clear the interval, cause the time has elapsed
 clearInterval(window.countdown_interval);
 
 alert('The time has elapsed! It\' time to dissapear..');
 
 //get rid of the clock, we don't need it anymore ]:-&gt;
 document.body.removeChild(document.getElementById(id));
}
&lt;/pre&gt;
You can &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock2.html"&gt;see a demo here&lt;/a&gt; and &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock2.zip"&gt;download the code from here&lt;/a&gt;.
&lt;/li&gt;
&lt;br /&gt;
&lt;li&gt;Tell the user the time has elapsed and send him somewhere else:
&lt;pre name="code" class="js"&gt;
function countdown_finished(id)
{
 //clear the interval, cause the time has elapsed
 clearInterval(window.countdown_interval);
 
 //tell the user he has had his time on that page..
 alert('Go away! You\'re not welcome anymore!');
 
 //and send him somewhere else
 window.location = "http://javascripthowtos.blogspot.com/";
}
&lt;/pre&gt;
You can &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock3.html"&gt;see a demo here&lt;/a&gt; and &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock3.zip"&gt;download the code from here&lt;/a&gt;.
&lt;/li&gt;
&lt;br /&gt;
&lt;li&gt;Redirect the user to the download he has waited for:
&lt;pre name="code" class="js"&gt;
function countdown_finished(id)
{
 //clear the interval, cause the time has elapsed
 clearInterval(window.countdown_interval);
 
 //time has elapsed - redirect the user to the long waited download..
 alert('Ok, now you know how I look and what I can do. Now, download me!');
 
 //set the new location - the file to download
 window.location = "javascript digital countdown clock4.zip";
}
&lt;/pre&gt;
You can &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock4.html"&gt;see a demo here&lt;/a&gt; and &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock4.zip"&gt;download the code from here&lt;/a&gt;.
&lt;/li&gt;
&lt;br /&gt;
&lt;li&gt;After telling the user the time has elapsed - start the countdown again. This is also very usable if you wan't to do stuff over a period of time, and want to user to know how much time is left till 'stuff' happens.. :)
&lt;pre name="code" class="js"&gt;
function countdown_finished(id)
{
 //clear the interval, cause the time has elapsed
 clearInterval(window.countdown_interval);
 
 alert('OK, one down! There goes another one!');
 
 //The countdown is dead. Long live the countdown! :)
 //create a new timeout for another countdown
 var new_timeout = Math.ceil(Math.random()*10);
 
 //add a leading zero if the number is just one digit
 if(new_timeout &lt; 10)
  new_timeout = "0"+new_timeout;
 
 //create the new countdown clock, even use the same id as before, but use the new timeout
 draw_clock('countdown', "00:00:"+new_timeout); 
}
&lt;/pre&gt;
You can &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock5.html"&gt;see a demo here&lt;/a&gt; and &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20countdown%20clock/javascript%20digital%20countdown%20clock5.zip"&gt;download the code from here&lt;/a&gt;.
&lt;/li&gt;
&lt;/ul&gt;

The possibilities are endless - do whatever you need to do when the time has elapsed :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-1446138808346584909?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/1446138808346584909/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=1446138808346584909' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/1446138808346584909'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/1446138808346584909'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/09/javascript-digital-countdown-clock.html' title='Javascript digital countdown clock'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-4988894351687982316</id><published>2008-08-28T11:25:00.000-07:00</published><updated>2009-01-06T06:52:59.019-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='counter'/><category scheme='http://www.blogger.com/atom/ns#' term='clock'/><category scheme='http://www.blogger.com/atom/ns#' term='digital'/><title type='text'>Javascript digital counter</title><content type='html'>I tought of something else I can also do with the &lt;a href="http://javascripthowtos.blogspot.com/2008/08/do-you-wanna-have-clock-on-your-pages-i.html"&gt;digital clock script&lt;/a&gt;. Using quite the same code as before, I made a counter, which is a very convinient way to tell the users how much they have been on your site. It starts as the page loads, from "00:00:00" and goes up each second. Of course, you can change the starting value if you need to, just edit it in the code.
&lt;br /&gt;
Here is the code:
&lt;pre name="code" class="js"&gt;
window.onload = function()
{
 //draw the clock when the page loads
 draw_clock('counter');
}

function draw_clock(id)
{
 //create the div that will hold the clock
 var clock = document.createElement('div');

 clock.id = id;
 
 //you can change the style of the clock ie to position it at a specific place on the page
 //i'll put this one approximately in the center of the page, but you can adjust that to fit your needs
 clock.style.position = 'absolute';
 clock.style.left = '50%';
 clock.style.top = '50%';
 clock.style.marginLeft = '-50px';
 clock.style.marginTop = '-20px';

 //set a starting time for the counter. 
 clock.time = '00:00:00';

 //display the time as div's innerHTML, using a function that formats it to look good on the page
 clock.innerHTML = get_clock_innerHTML(clock.time);

 //append the clock to the page
 document.body.appendChild(clock);

 //start a timer that will update the counter every second. You cam use other intervals if you need to
 setInterval("clock_counter('"+id+"')", 1000);
}

function get_clock_innerHTML(time)
{
 //an array that stores the symbols which draw the good old-fashioned digital clock :) 
 //IMPORTANT: don't change the alignment or anything else on this array, cause this will cause the clock to look uglier, or even not work
 var digits = " _     _  _     _  _ _   _  _    "+
     "| | |  _| _||_||_ |_  | |_||_| . "+
     "|_| | |_  _|  | _||_| | |_| _| . "+
     "                                 ";

 //put the symbols inside a &amp;lt;pre&amp;gt; tag to make sure they will be displayed just like they are written in the array.
 //you can also change the style settings i've set
 var data = "&amp;lt;pre&amp;gt;&amp;lt;span style='color: #000; background: #ccc; font-size: 10px;'&amp;gt;";

 //loop trough the four 'rows' of the array and display the appropriate symbols
 for(r = 0; r &lt; 100; r += 33)
 {
  for(i = 0; i &lt; time.length; i++)
  {
   for(c = (time[i])*3 + r , b = 0; b &lt; 3; b++, c++)
   {
    if(isNaN(c))
     c = 10*3+r;

    data += digits[c];
   }
  }

  data += "&amp;lt;br /&amp;gt;";
 }
 
 data += "&amp;lt;/span&amp;gt;&amp;lt;/pre&amp;gt;";

 return data;
}

function clock_counter(id)
{
 var clock = document.getElementById(id);

 //split the time into hours, minutes and seconds
 var tmp = clock.time.split(":");

 var hours = tmp[0];
 var minutes = tmp[1];
 var seconds = tmp[2];

 //if the seconds and/or minutes are about to pass 59 - increase the minutes/hours and set seconds/minutes back to zero.
 if(seconds == 59)
 {
  if(minutes == 59)
  {
   hours++;
   minutes = '00';
   seconds = '00';
  }
  else
 {
   minutes++;
   seconds = '00';
  }
 }
 else //otherwise just increase the seconds untill they reach 60
  seconds++;
 
 //update the var that holds the time
 clock.time = ((hours &lt; 10) ? "0"+parseInt(hours) : hours)+
 ":"+ ((minutes &lt; 10) ? "0"+parseInt(minutes) : minutes) +
 ":"+ ((seconds &lt; 10) ? "0"+parseInt(seconds) : seconds);

 //and update the innerHTML of clock's div
 clock.innerHTML = get_clock_innerHTML(clock.time);
}
&lt;/pre&gt;

Make sure your users know how long they've been on the page, they have to eat from time to time, you know ;) You can see a demo &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20counter/javascript%20digital%20counter.html"&gt;here&lt;/a&gt; and get the code from &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20counter/javascript%20digital%20counter.zip"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-4988894351687982316?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/4988894351687982316/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=4988894351687982316' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/4988894351687982316'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/4988894351687982316'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/08/javascript-digital-counter.html' title='Javascript digital counter'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-5121506596687334342</id><published>2008-08-28T10:52:00.000-07:00</published><updated>2009-01-06T06:53:15.533-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='clock'/><category scheme='http://www.blogger.com/atom/ns#' term='digital'/><title type='text'>Javascript digital clock</title><content type='html'>Do you wanna have a clock on your pages? I bet you do. Well, there are tons of clock scripts out there, but I tried something different here. Instead of using images to represent the clock, I used symbols, just like they do in the old digital clocks. It's a bit nasty algorithm, but it sure works :) &lt;br /&gt;
Here is what I did:
&lt;pre name="code" class="js"&gt;
window.onload = function()
{
 //draw the clock when the page loads
 draw_clock('current_time', 1);
}

function get_current_time()
{
 //create a new date object and get current hours, minutes and seconds
 var d = new Date();
 var h = d.getHours();
 var m = d.getMinutes();
 var s = d.getSeconds();

 //add a leading 0 (zero) to those which are one digit
 if(h &lt; 10)
  h = "0" + h;

 if(m &lt; 10)
  m = "0" + m;

 if(s &lt; 10)
  s = "0" + s;

 return h+":"+m+":"+s;
}

function draw_clock(id)
{
 //create the div that will hold the clock
 var clock = document.createElement('div');
 
 clock.id = id;
 
 //you can change the style of the clock ie to position it at a specific place on the page
 //i'll put this one approximately in the center of the page, but you can adjust that to fit your needs
 clock.style.position = 'absolute';
 clock.style.left = '50%';
 clock.style.top = '50%';
 clock.style.marginLeft = '-50px';
 clock.style.marginTop = '-20px';
 
 //get the current time and set it as div's innerHTML, using a function that formats it to look good on the page
 clock.innerHTML = get_clock_innerHTML(get_current_time());

 //add the element to the page
 document.body.appendChild(clock);

 //set the timer which will update the clock. The interval can also be set to more that a second. 
 //If you need to update the time in another interval of time, say 15 seconds, you can use 15000 as the second argument to setInterval()
 setInterval("clock_current_time('"+id+"')", 1000);
}

function get_clock_innerHTML(time)
{
 //an array that stores the symbols which draw the good old-fashioned digital clock :) 
 //IMPORTANT: don't change the alignment or anything else on this array, cause this will cause the clock to look uglier, or even not work
 var digits = " _     _  _     _  _ _   _  _    "+
       "| | |  _| _||_||_ |_  | |_||_| . "+
       "|_| | |_  _|  | _||_| | |_| _| . "+
       "                                 ";

 //put the symbols inside a &amp;lt;pre&amp;gt; tag to make sure they will be displayed just like they are written in the array.
 //you can also change the style settings i've set
 var data = "&amp;lt;pre&amp;gt;&amp;lt;span style='color: #000; background: #ccc; font-size: 10px;'&amp;gt;";

 //loop trough the four 'rows' of the array and display the appropriate symbols
 for(r = 0; r &lt; 100; r += 33)
 {
  for(i = 0; i &lt; time.length; i++)
  {
   for(c = (time[i])*3 + r , b = 0; b &lt; 3; b++, c++)
   {
    if(isNaN(c))
     c = 10*3+r;

    data += digits[c];
   }
  }

  data += "&amp;lt;br /&amp;gt;";
 }
 
 data += "&amp;lt;/span&amp;gt;&amp;lt;/pre&amp;gt;";

 return data;
}

function clock_current_time(id)
{
 //get the new time and change the innerHTML of the clock
 document.getElementById(id).innerHTML = get_clock_innerHTML(get_current_time());
}
&lt;/pre&gt;

Now you know what time it is* :) You can see a preview &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20clock/javascript%20digital%20clock.html"&gt;here&lt;/a&gt; and download the code from &lt;a href="http://javascripthowtos.freehostia.com/javascript%20digital%20clock/javascript%20digital%20clock.zip"&gt;here&lt;/a&gt;.
&lt;br /&gt;&lt;br /&gt;
*Does anyone know what "it" means in the sentence "What time is it?" :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-5121506596687334342?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/5121506596687334342/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=5121506596687334342' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/5121506596687334342'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/5121506596687334342'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/08/do-you-wanna-have-clock-on-your-pages-i.html' title='Javascript digital clock'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-8196278690779437378</id><published>2008-08-14T03:37:00.001-07:00</published><updated>2009-01-07T02:11:57.799-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='images'/><category scheme='http://www.blogger.com/atom/ns#' term='magnification'/><title type='text'>Javascript image magnifier</title><content type='html'>&lt;p&gt;A friend of mine has asked me if she can put a script on her image gallery that magnifies the pictures the way that desktop software does when you zoom in. The main reason for this was that some of the people, browsing the gallery, have found it difficult to read some funny stuff like a road sign in the background of the picture. She needed something to work on the page itself, so the users won't need to save the picture on their pc and then zoom in to read this funny road sign. So, here it is, a javascript image magnifier:&lt;/p&gt;

&lt;p&gt;I've made some settings for the the script to be more easily adjustable to what you need. The code starts with the declaration of the &lt;span style="font-style:italic;"&gt;magnifier_settings&lt;/span&gt; array:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;
var magnifier_settings = new Array();
magnifier_settings['widht'] = 100;
magnifier_settings['height'] = 100;
magnifier_settings['zoom_level'] = 2;&lt;/pre&gt;

&lt;p&gt;The width and height indexes of the array are used to manage how big the magnifier should be. The zoom_level is, well, a zoom level :) The value in this var will be used to determine how much times the magnified image will be biger than the original one.&lt;/p&gt;

&lt;p&gt;What fallows is a function that I've &lt;a href="http://javascripthowtos.blogspot.com/2008/08/javascript-image-map.html"&gt;already posted about&lt;/a&gt;, which gets the offset coordinates of the cursor, according to the image on which it is called. This offsets  will be used to determine where should the magnifier be displayed.&lt;/p&gt;

&lt;pre name="code" class="js"&gt;
function get_image_offset(e, id)
{
 offset_x = e.offsetX ? e.offsetX : e.pageX-document.getElementById(id).offsetLeft;
 offset_y = e.offsetY ? e.offsetY : e.pageY-document.getElementById(id).offsetTop;
 
 magnify(document.getElementById(id));
}&lt;/pre&gt;

&lt;p&gt;The new addition to the code in this function is the call to magnify(), which is the function that does the magnification.&lt;/p&gt;

&lt;pre name="code" class="js"&gt;
function magnify(elmnt)
{
 //check if the element exists; if it does not - create it
 if(!document.getElementById('magnifier'))
 {
  //create the div that will hold the magnifier
  var magnifier = document.createElement('div');
  magnifier.id = 'magnifier';
  magnifier.style.width = magnifier_settings['widht'];
  magnifier.style.height = magnifier_settings['height'];
  magnifier.style.overflow = 'hidden';
  magnifier.style.border = '2px solid #000';
  magnifier.style.position = 'relative';
  
  //magnified image. The original image is used to create the new one, which means that this function 
  //will work on any number of images on the same page, without the need to declare them or anything else..
  var magnifier_img = document.createElement('img');
  magnifier_img.id = 'magnifier_img';
  magnifier_img.src = elmnt.src;
  magnifier_img.width = parseInt(elmnt.width)*magnifier_settings['zoom_level'];
  magnifier_img.height = parseInt(elmnt.height)*magnifier_settings['zoom_level'];
 }
 else 
 {
  //if the element already existst we don't need to recreate it. Just declare the same variables, as used when creating the elements. 
  //This saves a lot of work for the browser and makes the script run smoother even on older PCs
  var magnifier = document.getElementById('magnifier');
  var magnifier_img = document.getElementById('magnifier_img');
 }
 
 //Adjust the magnifier position. Basically, it is set to the offset of the cursor plus a random value(i use 25) 
 //that will move the magnifier a little bit to the right  bottom of the page. This is used with two purposes: 
 //1. the magnifier will not pop over the cursor, so the user will actually see what will be magnified :)
 //2. this resolves an issue with the onmouseover trigger of the original image. If the value is not altered by 25, 
 //the instant when the magnifier is displayed, a onmouseout event is triggered on the original image, cause 
 //the mouse is now over the magnifier and not the original image. This causes the magnifier to be destoyed 
 //and in general is quite the oposite of what we want, cause this adds a big load to the client machine.
 //The top value is altered by the elements height, cause if the image is not at the top of the page,  
 //the magnifier will be misplaced somewhere above the image
 magnifier.style.left = offset_x+25;
 magnifier.style.top = offset_y+25-elmnt.height; 
 
 //Put negative margins to the magnified image, so the will show at the right place in the magnifier div
 magnifier_img.style.marginLeft = '-'+offset_x*magnifier_settings['zoom_level']+'px';
 magnifier_img.style.marginTop = '-'+offset_y*magnifier_settings['zoom_level']+'px';
 
 
 //Check again, if the magnifier is not created, cause if it's not we need to append it to the page elements
 if(!document.getElementById('magnifier'))
 {
  magnifier.appendChild(magnifier_img);
  
  //The only way I figured this magnification thing would work is using an image 'holder', which is a div 
  //with the same id as the &lt;img&gt; element plus the part '_holder'.
  var id = elmnt.id+'_holder';
  
  document.getElementById(id).appendChild(magnifier);
 }
}

//Removes the magnifier from tha page. This can be changed to just alter the magnifier's display property to 'none'
//or visibility to 'hidden', but i figured removing it is the most appropriate way
function hide_magnifier(id)
{
 id += '_holder';
 
 if(document.getElementById('magnifier'))
  document.getElementById(id).removeChild(document.getElementById('magnifier'));

}&lt;/pre&gt;

&lt;p&gt;And now, the HTML code that will display the images on the page:&lt;/p&gt;

&lt;pre name="code" class="html"&gt;
&amp;lt;div id='test_holder'&amp;gt;
&amp;lt;img id='test' src='test.jpg' onmousemove='get_image_offset(event, this.id);' onmouseout='hide_magnifier(this.id)'&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div id='test2_holder'&amp;gt;
&amp;lt;img id='test2' src='test2.jpg' onmousemove='get_image_offset(event, this.id);' onmouseout='hide_magnifier(this.id)'&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div id='test3_holder'&amp;gt;
&amp;lt;img id='test3' src='test.jpg' onmousemove='get_image_offset(event, this.id);' onmouseout='hide_magnifier(this.id)'&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;You can put as many images as you wish, they will be handled by the same function automatically. I've used 3 images to show how the script works on more that one image. You can put the code on you entire gallery or just a single image, it's your call :)&lt;/p&gt;

&lt;p&gt;The two things required for this script to work are as fallows: 
&lt;ul&gt;
&lt;li&gt;You need to have an id on each image. This is very important, cause otherwise the script won't work and a handful of javascript errors will occur when the user mouseover's an image that doesn't have an 'id' property. You can use whatever id you want, just use one :) &lt;/li&gt;
&lt;li&gt;The second thing is a div that holds the images. This is also very important, cause the script again won't work, and again there will be many many javascript errors when you mouseover the images. The requirement here is that the id for the div is the same as the id of the image it holds, plus the text '_holder'. You can use whatever styles you want on that div. If you want to, you can also put some other stuff in it, not just the image. Again - just put the images in divs and use the same ids with the text '_holder' added to them. &lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;

&lt;p&gt;I made two demos for this script with different settings. The first one is &lt;a href="http://javascripthowtos.freehostia.com/javascript%20image%20magnifier/javascript%20image%20magnifier.html"&gt;here&lt;/a&gt; and it uses a 100x100 pixels magnifier, with a zoom level of 2. You can download the code from &lt;a href="http://javascripthowtos.freehostia.com/javascript%20image%20magnifier/javascript%20image%20magnifier.zip"&gt;here&lt;/a&gt;. The second one can be seen &lt;a href="http://javascripthowtos.freehostia.com/javascript%20image%20magnifier/javascript%20image%20magnifier2.html"&gt;here&lt;/a&gt; and it uses 200x200 pixels magnifier with the zoom level of 4. You can download this code from &lt;a href="http://javascripthowtos.freehostia.com/javascript%20image%20magnifier/javascript%20image%20magnifier2.zip"&gt;here&lt;/a&gt;. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-8196278690779437378?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/8196278690779437378/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=8196278690779437378' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/8196278690779437378'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/8196278690779437378'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/08/javascript-image-magnifier.html' title='Javascript image magnifier'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3436525727412082104.post-9126171508999985776</id><published>2008-08-14T00:04:00.000-07:00</published><updated>2009-01-07T02:08:33.525-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='map'/><category scheme='http://www.blogger.com/atom/ns#' term='images'/><title type='text'>Javascript image map</title><content type='html'>&lt;p&gt;Have you ever needed to know exactly where the user has pointed or clicked on an image?  Well, this is easily done with HTML image maps, they are quite 
useful. But they do have some disadvantages. Using an HTML/XHTML image map requires form submission or page redirection to be used. What if you need to 
display appropriate content somewhere on the page, depending on where the user has pointed? Here is a way to get the offset coordinates of the pointer, 
inside an image.&lt;/p&gt;

&lt;pre name="code" class="js"&gt;
function get_image_offset(e, id)
{
offset_x = e.offsetX ? e.offsetX : e.pageX-document.getElementById(id).offsetLeft;
offset_y = e.offsetY ? e.offsetY : e.pageY-document.getElementById(id).offsetTop;
 
document.getElementById('x').innerHTML = offset_x;
document.getElementById('y').innerHTML = offset_y;
}
&lt;/pre&gt;

&lt;p&gt;This function takes two parameters - the event (mouseover, click, mousemove), and the id of the element (image) that we wan't to use. It saves the offset in 
&lt;span style="font-style: italic;"&gt;offset_x&lt;/span&gt; and &lt;span style="font-style: italic;"&gt;offset_y&lt;/span&gt;. If client's browser is IE, the &lt;span style="font-style:italic;"&gt;offsetX&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;offsetY&lt;/span&gt; 
values will be used, but since this is not supported by the other browsers, we can use the &lt;span style="font-style:italic;"&gt;pageX&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;pageY&lt;/span&gt; values and the elements &lt;span style="font-style:italic;"&gt;offsetLeft&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;offsetTop&lt;/span&gt; 
values to determine the cursor offset.&lt;/p&gt;

&lt;p&gt;After the two lines of code have been executed we have the offset in the variables offset_x and offset_y and we can use them for any purpose. I have added two span elements to the HTML, which show the offset as the user moves the mouse over the image. Here is the rest of the code you need to get this working:&lt;/p&gt;

&lt;pre name="code" class="html"&gt;
&amp;lt;img id='my_image_map' src='test.jpg' onmousemove='get_image_offset(event, this.id)'&amp;gt;
&amp;lt;br /&amp;gt;
X: &amp;lt;span id='x'&amp;gt;0&amp;lt;/span&amp;gt;; Y: &amp;lt;span id='y'&amp;gt;0&amp;lt;/span&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Now, presuming you have a 'test.jpg' file inside the folder of your page, you will see that when you move the mouse over it, the values of the two spans change width the coordinates of the cursor offset. You can change the code that alters the &lt;span style="font-style:italic;"&gt;innerHTML&lt;/span&gt; of the two spans and do whatever you need to do with this offset coordinates. You can also change the event that triggers the function. I use onmousemove to update the coordinates every time the cursor moves over the image, but you can use other triggers like onclick, ondblclick, etc.&lt;/p&gt;


&lt;p&gt;P.S. You can see a demo of this code &lt;a href="http://javascripthowtos.freehostia.com/javascript%20image%20map/javascript%20image%20map.html"&gt;here&lt;/a&gt;  and you can get the example code from &lt;a href="http://javascripthowtos.freehostia.com/javascript%20image%20map/javascript%20image%20map.zip"&gt;here&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3436525727412082104-9126171508999985776?l=javascripthowtos.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javascripthowtos.blogspot.com/feeds/9126171508999985776/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3436525727412082104&amp;postID=9126171508999985776' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9126171508999985776'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3436525727412082104/posts/default/9126171508999985776'/><link rel='alternate' type='text/html' href='http://javascripthowtos.blogspot.com/2008/08/javascript-image-map.html' title='Javascript image map'/><author><name>Nikoloff</name><uri>http://www.blogger.com/profile/04979646043847574965</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
