Archive for JavaScript

ASP.NET Calendar Control and Yahoo.UI.Calendar

Note: You can also see this article in codeproject.

Using ASP.NET Calendar and Yahoo.UI.Calendar in ASP.NET 1.1

DEMO Project can be downloaded from the link above.

Introduction

The Calendar control becomes an essential control for business application developments since the most of data entry forms used to have one or more field for Date value. Let’s say! we are working on a page called “Candidate Resume Entry” of Recruitment System. There will be some date fields such as “Date of Birth of Candidate”, “Resume Submitted Date” in that page. The calendar control needed to be used in that page. Okay. Let me stop talking about this here as I know you already know how calendar control is important for your project.

There are three sections in this article and each section has two parts called “Running the demo project” and “Lab“. First, you can see how it looks like by running the demo application. Then, if you wanna use this control in your project, you can read the details in “Lab”.

The following topics will be covered in this article.

  • Using ASP.NET Calendar Control in ASP.NET Project
  • Showing ASP.NET Calendar Control in Popup Window
  • Using Yahoo.UI.Calendar Control in ASP.NET Project

Note:

  1. I’d highly recommend you to download the demo project before start reading this article.
  2. Even thought there are three different sections in my article, you can feel free to skip any section and move on to the next section that you wanna read.

Thanks. Hopefully, you may find it useful.

Using ASP.NET Calendar Control in ASP.NET Project

This section is created only for beginners who haven’t used ASP.NET Calendar in Web Project. Feel free to skip this section if you already know about it.

Running the sample

1. Download and extract the zip file.
2. Set SimpleCalendar.aspx as start page.
3. Run the web application.
You will see the result as below if you click “…” button nearly Date Of Birth TextBox.
Simple ASP.NET Calendar
4. If you choose a date from Calendar Control then the selected date will be shown in TextBox and this calendar will be disappeared.

Do you wanna try this code in your owned project?

Lab: Using ASP.NET Control in ASP.NET Project

1. Create one ASP.NET Web Project (C#)
2. Place TextBox and Button in WebForm


<asp:TextBox ID="txtDOB" Runat="server">
</asp:TextBox>
<asp:Button ID="btnDOB" Runat="server" Text="...">
</asp:Button>

3. Add Calendar control to WebForm.
( Thanks to the Author of this article for custom style of calendar control.You can remove the style if you dont wanna customize the appearance.)


&lt;asp:calendar id="cdrCalendar" runat="server"
backcolor="#ffffff" width="250px" height="200px"
font-size="12px" font-names="Arial" borderwidth="2px"
bordercolor="#000000" nextprevformat="shortmonth"
daynameformat="firsttwoletters"
<strong>Visible="False"</strong>>
<TodayDayStyle ForeColor="White"
BackColor="Black"></TodayDayStyle>
<NextPrevStyle Font-Size="12px" Font-Bold="True"
ForeColor="#333333">  </NextPrevStyle>
<DayHeaderStyle Font-Size="12px"
Font-Bold="True">
</DayHeaderStyle>
<TitleStyle Font-Size="14px" Font-Bold="True"
BorderWidth="2px" ForeColor="#000055">
</TitleStyle>
<OtherMonthDayStyle ForeColor="#CCCCCC">
</OtherMonthDayStyle>
</asp:calendar>

4. Add the following codes in Button Click Event


try{
if(txtDOB.Text.Trim() != "")
cdrCalendar.SelectedDate =
Convert.ToDateTime(txtDOB.Text);
}
catch
{}
//showing the calendar.
cdrCalendar.Visible= true;

5. Add the following codes in SelectionChanged Event of Calendar


//displaying the selected date in TextBox
txtDOB.Text = cdrCalendar.SelectedDate.ToString();
//hiding the calendar.
cdrCalendar.Visible= false;

Finally, run your web application. You will see the same result as the picture above. That’s. It is Simple. isn’t it?

Showing ASP.NET Calendar Control in Popup Window

Now, we have some ideas about how to use ASP.NET Calendar. we will try to improve our code more better.
So, How about showing the Calendar in pop-up window? Oki. Let’s see..

Running the sample

1. Set PopupCalendar.aspx as start page.
2. Run the web application. You will see the calendar in pop-up window as following picture.

Popup ASP.NET Calendar

Lab: Adding Pop-Up Calendar Control in your owned project

Here are some facts if you wanna try this code in your owned project.

1. Three things you need to copy from demo project to your project

  • Calendar.aspx under Controls Folder
  • Styles.css under CSS
  • pdate.gif and today.png under Images

2. Two things you might need to check

2.1. Path of the CSS of Calendar


&lt;link href=<strong>"../CSS/Styles.css"</strong>
type="text/css" rel="stylesheet">

2.2. Path of the Calandar Image


&lt;asp:imagebutton id="BtnRefresh"
runat="server" ToolTip="Refresh"
ImageUrl=<strong>"../Images/today.png"</strong>>
</asp:imagebutton>

3. Three things you need to add to the page that you want this calendar to display.

3.1. TextBox and HyperLink


<asp:TextBox ID="txtDOB" Runat="server">
</asp:TextBox><asp:HyperLink id="imgDate"
runat="server" ImageUrl="Images/pdate.gif">
HyperLink
</asp:HyperLink>

3.2. Adding Javascript function to open pop-up window


<script language="javascript"
type="text/javascript">

function calendarPicker(strTxtRef){
window.open('./Controls/Calendar.aspx?field=' + strTxtRef   +
'','calendarPopup','titlebar=no,left=470,top=100,' +
'width=300,height=250,resizable=no');
}
</script>

3.3. Calling JavaScript Function


imgDate.NavigateUrl = "javascript:calendarPicker('document.Form1." +
txtDOB.ClientID.ToString() + "');";

Note: Form1 is the name of web form that you want calendar to display on it. If you are not sure about it, go to HTML view and check it.

eg:


<form id="Form1" method="post" runat="server">
</form>

Finally, you can start running your project and check whether it’s working fine or not.
Good Luck! :-)

Using Yahoo.UI.Calendar Control in ASP.NET Project

Personally, I don’t like that much about showing something in pop-up window. So, I was looking for something better. then I came to know Yahoo UI Library which is amazing javascript library and it is compatible with the most popular browsers. Let’s take a look at the demo.

Running the sample project

1. Set YahooUICalendarSimplePage.aspx as start page.
2. Run the web application. You will see the calendar in pop-up window as following picture.
Using Yahoo.UI.Calendar in ASP.NET

Lab: How to use Yahoo.UI.Calendar in your owned ASP.NET project

You need to add the following stylesheets,javascript files and image in your project.

1. Stylesheets

  1. calendar.css
  2. dpSyntaxHighlighter.css
  3. fonts.css
  4. reset.css

2. Javascript Files

  1. calendar.js
  2. dom.js
  3. event.js
  4. yahoo.js

3. Image

  1. pdate.gif

4. In aspx file,

Add the following code in HEAD Tag~


<script type="text/javascript"
src="./JS/yahoo.js"></script>
<script type="text/javascript"
src="./JS/event.js"></script>
<script type="text/javascript"
src="./JS/dom.js"></script>
<link type="text/css" rel="stylesheet"
href="./CSS/fonts.css">
<link type="text/css" rel="stylesheet"
href="./CSS/reset.css">
<link rel="stylesheet" type="text/css"
href="./CSS/dpSyntaxHighlighter.css">
<script type="text/javascript" src="./JS/calendar.js">
</script>

<link type="text/css" rel="stylesheet"
href="./CSS/calendar.css">
<script language="javascript">
YAHOO.namespace("example.calendar");
function init() {
YAHOO.example.calendar.cal1 = new YAHOO.widget.Calendar(
"YAHOO.example.calendar.cal1",
<strong>"cal1Container"</strong>);
YAHOO.example.calendar.cal1.title = "";
YAHOO.example.calendar.cal1.onSelect = setDate1;
YAHOO.example.calendar.cal1.render();
}

function showCalendar1(txtDateClientID,btnCalendarID) {
this.link1 = document.getElementById(btnCalendarID);
this.oTxtDate = document.getElementById(txtDateClientID);
var pos = YAHOO.util.Dom.getXY(link1);
YAHOO.example.calendar.cal1.oDomContainer.style.display='block';
YAHOO.util.Dom.setXY(YAHOO.example.calendar.cal1.oDomContainer,
[pos[0],pos[1]+link1.offsetHeight+1]);
}

function setDate1() {
var date1 = YAHOO.example.calendar.cal1.getSelectedDates()[0];
YAHOO.example.calendar.cal1.oDomContainer.style.display=’none’;
var formattedDate = date1;
<strong>oTxtDate.value = formattedDate.getDate()+’/'+</strong>
<strong>(formattedDate.getMonth() +1) +’/'+
formattedDate.getFullYear()</strong>;
}

YAHOO.util.Event.addListener(window, "load", init);
</script>

Note:

YAHOO.example.calendar.cal1.getSelectedDates() in setDate1() function will be returned the selected date as long date format. Even thought I have converted that long date format to short date format (DD/MM/YYYY), you can remove the last line if you wanna get long date format. “cal1Container” in init()is the id of DIV where Yahoo.UI.Calendar support to be attached.

  • Put the following code in Body Tag.
    
    <strong>
    <div id="cal1Container"
    style="DISPLAY: none; POSITION: absolute" ></div></strong>
    &lt;asp:TextBox ID=<strong>"txtDOB"</strong>
    Runat="server"></asp:TextBox>
    &lt;a id="chooseday"
    onclick="showCalendar1('<strong><% =txtDOB.ClientID %>'</strong>,
    <strong>'imgCalendar'</strong>)" href="javascript:void(null)">
    &lt;IMG id=<strong>"imgCalendar"</strong>
    border="0" alt="" src=<strong>"Images/pdate.gif"</strong>>
    

    Note:
    If you are using HTML Textbox in your page, you can just pass the id of textbox to showCalendar1() function.
    In case, the calendar is showing behind the other control,
    you can set higher Z-ORDER of callContainer DIV which will be
    attached by Yahoo.UI.Calendar.(Thanks to Julia for asking such a great question.)

    Conclusion

    Hopefully, you may find it useful. (again) and This is the
    way that I used in some of my project and I’m pretty sure that it works very
    well in practical project.
    If you have any question regarding this artilce, you
    can feel free to leave your question as a comment in my blog. (http://michaelsync.net) I will reply you as soon as possible.

    Thanks.

    Related Articles ~

    References

  • JavaScript: Changing Image at runtime.

    This is just very basic example. hum? but this is also very bad UI design that you should NOT use in your web application. Because the code doesn’t work on Web Server. In order to make this script to work, your have to add this page which is using this code as a trust site in Internet Explore 6 or 7. Of course, it won’t work in Mozilla-based browsers.. but the firefox extension called Noscript might help the script to work in Mozilla Firefox. (But I have tested yet.)

    Here is the discussion.

    Feel free to let me know if you have any comment for this script.

    
    <html>
    <head>
    <meta http-equiv="Content-Language" content="en-us">
    <meta name="GENERATOR" content="Microsoft FrontPage 6.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>New Page 1</title>
    <script language=javascript>
    /*
    Changing the image at runtime by using JavaScript.
    @imgId   : ID of Image HTML Control
    @strPath : The path of the image that you just browse.
    */
    function changePic(imgId,strPath){
    var o = document.getElementById(imgId);
    var s = new String(strPath);
    s = s.replace("\\","/");
    alert("file:///" + s);
    o.src="file:///" + s;
    }
    </script>
    </head>
    
    <body>
    
    <p>
    <img id=“img1″ border=”0″ src=”../sm_sunita.jpg” width=”300″ height=”225″>
    </p>
    <p>
    <input type=”file” name=”F1″ size=”20″ onchange=”changePic(‘img1′,this.value)”>
    </p>
    </form>
    </body>
    </html>
    

    Note: Demo Images has been removed.

    OpenLaszlo

    OpenLaszlo

    OpenLaszlo is licensed under the Common Public License (Version 1.0).

    OpenLaszlo is an open source platform for creating zero-install web applications with the user interface capabilities of desktop client software.

    OpenLaszlo programs are written in XML and JavaScript and transparently compiled to Flash and soon DHTML. The OpenLaszlo APIs provide animation, layout, data binding, server communication, and declarative UI. An OpenLaszlo application can be as short as a single source file, or factored into multiple files that define reusable classes and libraries.

    OpenLaszlo is write once run everywhere. An OpenLaszlo application developed on one machine will run on all leading Web browsers on all leading desktop operating systems.

    http://www.openlaszlo.org/
    http://www.laszlosystems.com/developers/

    OpenSouce Kits - xBox

    LightBox

    Lightbox JS is a simple, unobtrusive script used to overlay images on the current page. It’s a snap to setup and works on all modern browsers.

    LightBox - Javascript

    Version 1 ~
    http://www.huddletogether.com/projects/lightbox/
    Version 2 (Source and Demo) ~
    http://www.huddletogether.com/projects/lightbox2/

    iBox

    ibox.PNG

    Source ~
    http://www.ibegin.com/blog/p_ibox.html

    Demo ~
    http://www.ibegin.com/ibox/ibox-test.html

    Thick Box

    One box to rule them all..

    thick-box.PNG

    Source ~
    http://codylindley.com/Javascript/257/thickbox-one-box-to-rule-them-all

    Demo ~
    http://jquery.com/demo/thickbox/

    Greybox

    greybox.PNG

    Source ~
    http://orangoo.com/labs/GreyBox/

    Demo ~
    http://amix.dk/greybox/demo.html

    GreyBox - Redux

    greybox-redux.PNG

    Source and Demo ~
    http://jquery.com/blog/2006/02/10/greybox-redux/

    Yahoo UI Library

    The Container family of components is designed to enable developers to create different kinds of content-containing modules on the web. Module and Overlay are the most basic containers, and they can be used directly or extended to build custom containers. Also part of the Container family are four UI controls that extend Module and Overlay: Tooltip, Panel, Dialog, and SimpleDialog.

    Yahoo UI Library

    Source and Demo ~

    Yahoo! UI Library: Container
    Yahoo! UI Library

    UPDATED:ExtJS

    Cool and very popular Javascript Library.

    extjs.gif

    Download and Demo : http://extjs.com/
    Note: Please let me know if I missed out something. Thanks.

    Ajax Frameworks and Others

    The AJAX Engine
    This implementation has its focus on building an AJAX Engine and Web Controls upon standard WebServices (SOAP, WSDL) on the web server instead of using a new or proprietary protocol. The benefit for that is that there is no special coding necessary for most parts of the networking infrastructure and that many aspects like caching and security of the WebService implementation can be reused.

    http://www.mathertel.de/AJAXEngine/#view=Home
    http://www.mathertel.de/AJAXEngine/#view=Downloads
    http://www.mathertel.de/ajax/Aspects%20of%20AJAX_index.htm

    Atlas
    Atlas is a free framework for building a new generation of richer, more interactive, highly personalized standards based Web applications. This new Web development technology from Microsoft integrates client script libraries with the ASP.NET 2.0 server-based development framework. In addition, Atlas offers you the same type of development platform for client-based Web pages that ASP.NET offers for server-based pages.

    http://atlas.asp.net/default.aspx?tabid=47

    MagicAjax.NET
    MagicAjax.NET is a free open-source framework, designed to make it easier and more intuitive for developers to integrate AJAX technology into their web pages, without replacing the ASP.NET controls and/or writing tons of javascript code. MagicAjax initially appeared as a codeproject article. Now it is hosted on Sourceforge and you can find the latest release at the downloads section.
    http://www.magicajax.net/

    MonoRail
    MonoRail (former Castle on Rails) is a MVC web framework inspired on Action Pack. The Action Pack way of development is extremely productive, very intuitive and easily testable

    http://www.castleproject.org

    AJAXLib
    AJAXLib is a small JavaScript tool that makes working with AJAX applications a little easier.

    http://karaszewski.com/tools/ajaxlib/

    Dojo
    Dojo is the Open Source JavaScript toolkit that helps you build serious applications in less time. It fills in the gaps where JavaScript and browsers don’t go quite far enough, and gives you powerful, portable, lightweight, and tested tools for constructing dynamic interfaces.

    http://dojotoolkit.org/

    MochiKit
    MochiKit.Visual provides visual effects and support functions for visuals.

    http://www.mochikit.com

    Anthem.NET
    Anthem.NET is a free, cross-browser AJAX toolkit for the ASP.NET development environment that works with both ASP.NET 1.1 and 2.0.
    http://sourceforge.net/projects/anthem-dot-net

    Moo.FX *****
    moo.fx is a superlightweight, ultratiny, megasmall javascript effects library, written with prototype.js.
    http://moofx.mad4milk.net/#news

    Cross-Browser.com
    http://www.cross-browser.com/toys/

    AJAX Toolbox - AjaxRequest
    http://ajaxtoolbox.com/request/

    Bajax
    Bajax its a very small and simple javascript library to use Ajax on your pages. independent of programming language. You can put dynamic content using simple commands.
    https://developer.berlios.de/projects/bajax/

    Sardalya
    A small library for making dynamic HTML programming easy and fun.
    http://www.sarmal.com/sardalya/Default.aspx

    Behaviour
    Separate Structure (xhtml) from Behavior (javascript)
    http://bennolan.com/behaviour/

    WZ_DradDrop
    A Cross-browser JavaScript DHTML Library which adds Drag Drop functionality to layers and to any desired image .
    http://www.walterzorn.com/dragdrop/dragdrop_e.htm

    WZ_jsGraphics
    High Performance JavaScript Vector Graphics Library. ( Wow!! This is awesome! )
    http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm

    overLIB
    overLIB is a JavaScript library created to enhance websites with small popup information boxes (like tooltips) to help visitors around your website. It can be used to provide the user with information about what will happen when they click on a link as well as navigational help (see the examples below). Not to mention that it looks cool, is stable, and has an active developer community to boot!
    http://www.bosrup.com/web/overlib/

    Some open ajax librabries
    http://ronchen.blogbus.com/logs/2006/04/2334025.html

    http://www.maxkiesler.com/index.php/weblog/comments/60_more_helpful_ajax_tutorials/
    http://www.maxkiesler.com/index.php/weblog/comments/50_ajax_reference_websites_from_around_the_world/
    http://ajaxaspects.blogspot.com/
    http://www.mathertel.de/
    http://atlas.asp.net/docs/default.aspx
    http://ajaxpatterns.org/wiki/index.php?title=Main_Page

    3D
    http://www.gogofrog.com/start.html
    This 3D Gogofrog Web site is worth taking a look at.
    See it at http://www.gogofrog.com/userdata/SMYSITE

    Nifty Corners
    http://www.html.it/articoli/niftycube/index.html

    http://www.web-graphics.com/

    GreyBox
    http://orangoo.com/labs/GreyBox/
    Demo: http://amix.dk/greybox/demo.html

    Here is another version of GreyBox.
    GreyBox - Redux
    http://jquery.com/blog/2006/02/10/greybox-redux/

    ThickBox - One box to rule them all..
    http://codylindley.com/Javascript/257/thickbox-one-box-to-rule-them-all
    Demo: http://jquery.com/demo/thickbox/

    jQuery
    jQuery is a new type of Javascript library. It is not a huge, bloated, framework promising the best in AJAX - nor is just a set of needlessly complex enhancements - jQuery is designed to change the way that you write Javascript.

    http://jquery.com/

    AXAH (Asynchronous XHTML and HTTP) - Crawl before you AJAX
    http://codylindley.com/Javascript/237/axah-asynchronous-xhtml-and-http-crawl-before-you-ajax

    LightBox (** good for photo gallery)
    Lightbox JS is a simple, unobtrusive script used to overlay images on the current page. It’s a snap to setup and works on all modern browsers

    Version 1:
    http://www.huddletogether.com/projects/lightbox/
    Version 2:
    http://www.huddletogether.com/projects/lightbox2/

    Ajax Linki
    http://www.ajaxlinki.com/

    Using Cookie

    
    using System;
    using System.Data;
    using System.Configuration;using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class   _Default :System.Web.UI.Page{
      protected void Page_Load(object sender, EventArgs e){
       //in case, it’s already there..
    Response.Cookies.Remove(“myCookie”);
    Response.Cookies.Add(new HttpCookie(“myCookie”,“It’s Cookie!”));
      }
    }
    
    
    <%@ Page Language=”C#”AutoEventWireup=”true”
    CodeFile=”Default.aspx.cs”Inherits=”_Default” %>
    
    <!DOCTYPE  html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
    “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
    
    <html xmlns=”http://www.w3.org/1999/xhtml” >
    <head runat=”server”>
        <title>Untitled Page</title><script language=”javascript”type=”text/javascript”>
    <!–
    
    function Button1_onclick() {
      alert(readCookie(“myCookie”));
    }
    
    /*
     * JavaScript - Cookie Library
     * Ref     : http://www.quirksmode.org/js/cookies.html
     * Comment : The following codes can be put in the seperated
     *           js file.  */
    function readCookie(name)
    {
      var nameEQ = name + “=”;
      var ca = document.cookie.split(‘;’);
      for(var i=0;i <ca.length;i++){
        var c = ca[i];
        while (c.charAt(0)==’ ‘) c = c.substring(1,c.length);
         if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length,c.length);
      }
      return null;
    }
    
    function eraseCookie(name)
    {
      createCookie(name,“”,-1);
    }
    
    function createCookie(name,value,days)
    {
     if (days){
        var date =  new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires =  “; expires=” +date.toGMTString();
     }
     else var expires = “”;br> document.cookie = name +  “=” + escape(value) +
                expires +  “;path=/”;
    }
    
    // –>
    </script>
    </head>
    <body>
     <form id=”form1″runat=”server”>
      <div>
       <inputid=”Button1″type=”button”value=”Read Cookie”
         language=”javascript”onclick=”return Button1_onclick()” /></div>
      </form>
    </body></html>
    

    Posted in ASP.NET, JavaScript.