Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for the ‘Javascript’ Category

Blogs releted to javascript

Detect browser F5 / refresh and X / Close in javascript

Posted by Viral Sarvaiya on May 8, 2012


Below javascript is use to detect wether browser is refereshed or closed.

window.onunload = function (e) {
// Firefox || IE
e = e || window.event;
var y = e.pageY || e.clientY;

if (y < 0) {
alert("close");
}
else {
alert("refresh");
}
}

Thanks.

Posted in ASP.NET, Javascript, Silverlight | Tagged: , , , , , | 1 Comment »

Window Close Event of Browser

Posted by Viral Sarvaiya on April 12, 2011


hi,

recently i get a problem that what if some user accessing my website and close directly browser without logout from the system?

i get good solution with this but this is not 100% secure.

for that we have 2 events in javascript “onbeforeunload” or “onunload”

but onunload event is not working in firefox and some time in IE8 also, so onbeforeunload is suitable for both.

<html>
<head>
<title>Window Close Event of Browser</title>
<script language="javascript" type="text/javascript">
 function CloseBrowser() {
 alert("Browser is closing");
 }
 </script>
</head>

<body onbeforeunload="CloseBrowser();">

</body>
</html>

 

window.onbeforeunload = function() {
    return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
 };

 
As we have already discussed that there is no 100% fool proof way to detect the browser close event in a lot of cases, the above technique can fail. For example if the user kills the browser’s process from task manager, there could be many more cases. Yet in a lot of cases, this technique can be handy.

Best of luck and happy programming.

Thank you.

Posted in ASP.NET, Javascript | Tagged: , , , , , | Leave a Comment »

Redirect to a New Page using JavaScript

Posted by Viral Sarvaiya on October 16, 2010


An easy way to redirect a user to a new Page using JavaScript is to use


window.location = "http://www.devcurry.com";

However the problem with this approach is that it adds an item to your browser history. So in browsers like IE, the user can access the history by hitting the back button, which can be confusing to users, as they will redirected back and forth.

 

If you want to avoid the back button, use ‘window.location.replace’ which loads the new page and replaces the current page in the user’s History, with the new one, as shown below:


<head>
 <title>Redirect to a New Page</title>
 <script type="text/javascript">
 window.location.replace("http://www.devcurry.com");
 </script>
</head>
<body>

Now when you are redirected to the new page, there is no back button.

For More Details Click Here

Posted in ASP.NET, Javascript | Tagged: , , , | Leave a Comment »

How To Get URL Parts in JavaScript

Posted by Viral Sarvaiya on April 27, 2010


This JavaScript tutorial article concentrates on:

  • Obtaining the URL from the window.location object
  • Changing the current location with window.location.href and window.location.reload
  • Splitting and rebuilding URLs with Array and String splitting functions

The first step is understanding the JavaScript Location object.

The Location Object

This is a JavaScript class that is used to store URLs. It comes with properties that represent each part of the URL, and can be updated by changing the href property. The key properties that this article deals with are:

  • location.href : the full URL
  • location.protocol, location.host & location.pathname : the parts of the URL

In addition there are various methods that

  • location.reload
  • location.replace

These shall be discussed with reference to the window.location object.

The window.location Object

The window.location object is the specific object that stores the URL of the currently loaded page. If a JavaScript function changes the window.location.href property, then the page should reload with the new location.

However, this may not always be the case, and so the location.reload and location.replace methods have also been provided in the Location object. These were introduced in JavaScript 1.2, and give a little more control over the way that browsing history and current page location URLs are handled. In some cases it may not be enough to set the window.location.href, and so calling window.location.reload will force the page to be refreshed.

The window.location.replace method is used to overwrite the history entry in the browser, for the current page.

Splitting and Rebuilding URLs

The URL is stored as the following parts:

protocol://host/pathname

Each part can be accessed using the appropriate property of the Location object:

  • location.protocol : for web pages, the value http
  • location.host : for this site http://www.suite101.com
  • location.pathname : the path to a page i.e. mypages/page1.html

It is important to note that:

  • The protocol is store without the : or // that make up the whole URL
  • The host will contain a port, where appropriate
  • the pathname does not contain the leading /

So, to rebuild a URL based on the above information, code such as the following can be used:

newURL = window.location.protocol + "//" +  window.location.host + "/" + window.location.pathname;

This makes it very easy to create inline links that are context sensitive, and that refer pages that should exist on the server. For example, a site might have a tag page that collects all content that has the tag marketing associated with it. If the word marketing were to appear in a block of text, then JavaScript could be used to pre-process that block of text, and add a URL based on the current URL, but containing the reference to the marketing tag page.

One final note is that the pathname will be a / separated string, which can be split into an array of strings using the following code:

pathArray = window.location.pathname.split( '/'  );

Using this approach, it is easy to rebuild URLs, as each component will be contained in one array element. Again, however, it is necessary to put the / back:

newPathname = "";
for ( i = 0; i pathArray.length; i++ ) {
newPathname += "/";
newPathname += pathArray[i];
}
you can also retrieve the full path within code
Uri MyUri = Request.Url;

String Temp = MyUri.Scheme + @"://";
Temp = Temp + MyUri.Host;
Temp = Temp + Request.ApplicationPath;

Posted in ASP.NET, Javascript | Tagged: , , , , | 2 Comments »

Reading XMl file from Javascript in asp.net C#

Posted by Viral Sarvaiya on March 23, 2010


hi here i demonstrate another application which read the XML file from the javascript,

in my previous post, i demostrate the webservice calling from javascript, this post i continue from that,

web service  return the string which is in XML format and javascript read this XML string and give the alert according to the TAG of the XML.

follow the steps as per the my previous post url : http://viralsarvaiya.wordpress.com/2010/03/23/calling-web-service-from-java-script-in-asp-net-c/

we repeat the Steps,

step 1 : file -> new -> web site

step 2 : select ASP.NET Web Service

step 3 : Add new web form name “default.aspx”

Step 4 : following code shows the “service.cs” file which is the web service file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml ;
using System.IO ;

[WebService(Namespace = "http://Localhost...xys/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class MyService : System.Web.Services.WebService
{
public MyService()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld(string strNoOfData)
{
// Create the xml document containe
XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("PHI_Data");
doc.AppendChild(root);

int iNoOfData = 0 ;
if ( int.TryParse( strNoOfData, out iNoOfData ) == false )
iNoOfData = 600 ;

DateTime dtTemp = new DateTime(2009, 1, 1, 12, 0, 0);
Random rndTemp = new Random();

float fValue = ((float)rndTemp.Next(1000, 2000)) / 100;

for (int iCounter = 0; iCounter < iNoOfData; iCounter++)
{
XmlElement Data = doc.CreateElement("PHI_Record");
Data.SetAttribute("Record_Number", iCounter.ToString());

XmlElement dataTimeStamp = doc.CreateElement("TimeStamp");
dataTimeStamp.InnerText = dtTemp.ToString("yyyy-MMM-dd hh:mm:ss");
XmlElement dataValue = doc.CreateElement("Value");
dataValue.InnerText = fValue.ToString();
Data.AppendChild(dataTimeStamp);
Data.AppendChild(dataValue);
root.AppendChild(Data);

fValue = ((float)rndTemp.Next(1000, 2000)) / 100;
dtTemp = dtTemp.AddHours(1);

}
string xmlOutput = doc.OuterXml;

return xmlOutput;
}
}

step 5 : following code shows the “default.aspx” file

</pre>
<head id="Head1" runat="server">
<title>Read XML File From Javascript with Web Serice in asp.net</title>

<script type="text/javascript">

function CallService() {
MyService.HelloWorld(document.getElementById('Textbox1').value, OnComplete, OnError, OnTimeOut);
}

function OnComplete(xmlText) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlText);

var child = xmlDoc.documentElement.firstChild;
while (child) {
alert(child.firstChild.text);
alert(child.lastChild.text);
child = child.nextSibling;
}
}

function OnTimeOut(arg) {
alert("timeOut has occured");
}

function OnError(arg) {
alert("error has occured: " + arg._message);
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>
<asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Call Service" OnClientClick="CallService()" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>

Step 6 : Run The Application Enjoy Coding…

Posted in ASP.NET, Javascript | Tagged: , , , , , , | Leave a Comment »

Calling Web Service from Java script in asp.net c#

Posted by Viral Sarvaiya on March 23, 2010


Here i m demonstrate the simple application that calling webservie from javascript

step 1 : file -> new -> web site

step 2 : select ASP.NET Web Service

step 3 : Add new web form name “default.aspx”

Step 4 : following code shows the “service.cs” file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://Localhost...xys/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

<strong>[System.Web.Script.Services.ScriptService()]</strong>

public class Service : System.Web.Services.WebService
{
public Service () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld(string strNoOfData)
{
return strNoOfData;
}

}

step 5 : following code shows the “default.aspx” file


<%@ 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></title>
<script type="text/javascript" language="javascript">
function CallService() {
Service.HelloWorld(document.getElementById('Textbox1').value, OnComplete, OnError, OnTimeOut);
}

function OnComplete(Text) {
alert(Text);
}

function OnTimeOut(arg) {
alert("timeOut has occured");
}

function OnError(arg) {
alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service.asmx" />
</Services>
</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>
<asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Call Service" OnClientClick="CallService()" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Step 6 : Run The Application

Enjoy Coding…

Posted in ASP.NET, Javascript | Tagged: , , , | 4 Comments »

Add Page as a bookmark

Posted by Viral Sarvaiya on December 28, 2009


just copy and paste the below code for bookmark your page.


<head>
<script>
function bookmark(url,title){
if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
window.external.AddFavorite(url,title);
} else if (navigator.appName == "Netscape") {
window.sidebar.addPanel(title,url,"");
} else {
alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
}
}
</script>

</head>
<body>
<input type="button" value="Bookmark us!"
onclick="bookmark('http://viralsarvaiya.wordpress.com/','JavaScript For Bookmark')">
</body>

Posted in ASP.NET, Javascript | Tagged: , , | Leave a Comment »

How to Get Mouse Coordinates with Javascript

Posted by Viral Sarvaiya on October 29, 2009


This will find X and Y coordinates of the mouse where the mouse moves in browser.


<html>
<head>
<title>Get Mouse Coordinates</title>
<script language="javascript">
var divObj;

document.onmousemove=getMouseCoordinates;

function getMouseCoordinates(event)
{
ev = event || window.event;
divObj.innerHTML = "Mouse X:"+ev.pageX + " Mouse Y:"+ev.pageY;
}

function loadDiv()
{
divObj = document.getElementById("mouseCoord");
}
</script>
</head>

<body onLoad="loadDiv()">
<div id="mouseCoord">Mouse Coordinates position will be displayed here.
</div>
</body>
</html>

Posted in Javascript | Tagged: , , | Leave a Comment »

Get CheckBoxList values using Javascript

Posted by Viral Sarvaiya on October 28, 2009


I have one CheckBoxList control that binds values at runtime from the database, and when I click on a button from the page, I want to get the values (Database Primary Key) from the CheckBoxList, but for the checked checkboxes only.

Here is the code, what I have achieved so far. This code works fine with IE 7, but I am not sure with the FireFox.

ASPX page:


<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnDataBound="CheckBoxList1_DataBound" >
<asp:ListItem Value="First1" Text="First" ></asp:ListItem>
<asp:ListItem Value="second2" Text="Second"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" />

<script language="javascript" type="text/javascript">
function CheckItem()
{
var tbl = document.getElementById('<%= CheckBoxList1.ClientID %>').childNodes[0];
for(var i=0; i<tbl.childNodes.length;i++)
{
for(var k=0; k<tbl.childNodes[i].childNodes.length; k++)
{
if(tbl.childNodes[i].childNodes[k].nodeName == "TD")
{
var currentTD = tbl.childNodes[i].childNodes[k];
for(var j=0; j<currentTD.childNodes.length; j++)
{
if(currentTD.childNodes[j].nodeName == "SPAN")
{
var currentSpan = currentTD.childNodes[j];
for(var l=0; l<currentSpan.childNodes.length; l++)
{
if(currentSpan.childNodes[l].nodeName == "INPUT" && currentSpan.childNodes[l].type == "checkbox")
{
var currentChkBox = currentSpan.childNodes[l];
if(currentChkBox.checked)
{
alert(currentSpan.alt);
}
}
}
}
}
}
}
}
}
</script>

Code Behind:


Button1.Attributes.Add("onclick", "javascript:CheckItem();");
CheckBoxList1.DataSource = <Your Dataset>;
CheckBoxList1.DataTextField = "PersonName";
CheckBoxList1.DataValueField = "PersonID";
CheckBoxList1.DataBind();
protected void CheckBoxList1_DataBound(object sender, EventArgs e)
{
CheckBoxList chkList = (CheckBoxList)(sender);
foreach (ListItem item in chkList.Items)
{
item.Attributes.Add("alt", item.Value);
}
}

other way is as below….

this is run in IE as well as FF


function CheckItem() {

var tbl = document.getElementById('<%= CheckBoxList1.ClientID %>');

var chkspecialCount = tbl.getElementsByTagName("input");

var chkspeciallbls = tbl.getElementsByTagName("label");

for (var i = 0; i < chkspecialCount.length; i++) {

if (chkspecialCount[i].checked == true) {

var str = chkspeciallbls[i].innerHTML;

alert(str);

}

}

}

Enjoy Coding….

Reference

http://hspinfo.wordpress.com/2008/08/14/get-checkboxlist-values-using-javascript/

Posted in ASP.NET, Javascript | Tagged: , , , | 2 Comments »

Show Div tag in middle of the page with javascript

Posted by Viral Sarvaiya on October 27, 2009


take a element of Div


<div id="contentmsg" style="position: absolute; right:25%; width: 100px; height:100px;visibility: hidden;">
<img src="images/loading.gif" width="50px" height="50px" />
</div>

suppose we have a dropdown and according to onchange() event this div is visible or hide,


<asp:DropDownList ID="ddlparavalue" runat="server"></asp:DropDownList>

in the server side bind the dropdownlist dynamically and add the attribultes as below


ddlparavalue.Attributes.Add("onchange", "javascript:void HideOrVisibleDDL();")

in the head of the html section write the following code


<script language="javascript" type="text/javascript">
function HideOrVisibleDDL() {

var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
var windowWidth = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
var IpopTop = ((windowHeight - document.getElementById("contentmsg").offsetHeight) / 2);

document.getElementById("contentmsg").style.top = IpopTop + document.body.scrollTop;
document.getElementById("contentmsg").style.left = (document.body.clientWidth / 2) - 50;

document.getElementById("contentmsg").style.visibility = "visible";

}
</script>

in some case it is not working just becouse of the DOCType tag so please remove the DOCTYPE tag as like below


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

so remove this tag.

enjoy coding….

Posted in ASP.NET, Javascript | Tagged: , , | 3 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 44 other followers

%d bloggers like this: