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

JQuery conflict when using different javascript libraries

Today, I came to a scenario where I need to use JQuery and Prototype libraries in my application. Both are operating with $() to access the objects and do the client side logic. But, the $() is getting conflicted between JQuery and Prototype libraries and things got messed up. So, it should be a good practice to distinguish them because who knows what requirements come in future and how many client side javascript technologies we are going to use. The code which we have shouldn't effect anything, right?.

The same thing happen in my SharePoint sites too. When I tried to migrate from SharePoint 2007 to SharePoint 2010, the client side script [JQuery] custom developed is not working. The only reason behind is the conflicts in the javascript. The file SP.js in the SharePoint 2010 causing the problem.

So, make sure, if you have used JQuery in your applications, always the best practice is declare the Jquery global instance variable and then start using that instead of directly use the $(). For example,
var $j = jQuery.noConflict();

// Use jQuery via $j(...)
$j(document).ready(function(){
$j(".someclass").hide();
});

So, in the above code, we actually referring the $j() instead of directly $(), so it won't give any problems in future. No matter what how many different client side javascript technologies used, that should work. For more information check it here.

Hope you like this post and love to hear comments. Read More...

Disable button in onclick and process the button click event

This is what I need to implement for one of my project. I am using Ajax and if user tries to hit the submit the button more than once, only the very first request should submit to server and all other requests shouldn't make any request. So, for this I need to disable the button when first  time click on button and enable it after processed. But, I faced a problem that when I try to disable the button in javascript of client side click event then the postback event not raising at all. There are couple of ways we can implement this. First, I tried from server side code.

Solution 1:

btnSubmit.Attributes.Add("onclick","javascript:" + btnSubmit.ClientID + ".disabled=true;" + this.GetPostBackEventReference(btnSubmit));
But, this solution won't work in all scenarios and especially if there are validations.

Solution 2:

OnClientClick='javascript:this.disabled=Page_ClientValidate("");' UseSubmitBehavior="false"
For ASP Button the two properties onclientclick and usesubmitbehavior will do magic for us. In onclientclick event I am disabling the button if and only if the validation passed. Go back to my previous post. It describes how to validate the controls in client side and give the result true or false. And because of using the UseSubmitBehavior property it will automatically re-enable the button once the request processed.

Hope this gives you the enough idea. Like to know what you think. 

Read More...

How to detect clicked on outside of a particular div?

This is the part of my work on java script. I need to detect in my code, whether I clicked on a particular div or out of a div. So, what is the best way? Get he user clicked position and compare them with div coordinates? No that's not a good solution. Then how we need to do? Below is the best way of implementing it.

document.onclick = clickEvent;
function clickEvent(e) {
var targ;
if (!e) var e = window.event;

if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;

//if (targ.nodeType == 3) // defeat Safari bug

if (targ.nodeName != "HTML") {
while (targ.nodeName != "BODY") {
if (targ.id && targ.id == 'divGrid') {
return false;
} else {
targ = targ.parentNode;
}
}
} //This is the place where you need to write code when you click outside of the div.
}

Hope this helps in solving some problems. Look for more.

Read More...

How to detect tab key is pressed in javascript?

Recently I was working for a client and they needs plenty of functionality to be implemented in the javascript. And on the way of writing the code, I need to check whether user pressed on the tab key. When user on a particular div and hit the tab key then I need to do some logic. So, is there any event like tab clicked in javascript? NO… So,how to detect it. Below is the code I used for it.

document.onkeydown = keydown;

function keydown(event) {
var code;
var e;
if (document.all) {
if (!event) {
var e = window.event;
code = e.keyCode;
}
}
else if (event.which) {
code = event.which;
e = event;
}
if (code == 9) {//Write some logic
}
}

Note: keycode 9 is for tab key.

Hope this helps you.

Read More...

Set Focus to ASP.NET control

This is the question I received from developers on how to set the focus to an ASP.NET control from server side. Because once page is posted back to server or when request sent to server, from the response we need to set the focus to some x control on the page from server side.

There are requirements like this. For example, we have multiple panels on the page and when you saved the data successfully of a panel then you need to show the user the panel they submitted with some successful message instead of showing them the top section of  page always. :) Otherwise, user always needs to scroll down to the panel where he edited the changes and see whether the data saved successfully or not. An user experience problem.

Usually, the way the developers will do is, catch the control in client side either using javascript or jquery, then they will write logic to set the focus to it. But it's not needed. We can simply use the existing functions available in ASP.Net and C# and implement the behavior without any pain. See below example on how to do that.

C# language by default providing some options to set the focus to an ASP.NET control on the page. There are two ways to do that.

  • You can directly use Focus() method to set focus to a control. 
    tbName.Focus();
  • You can use the Page object function named "SetFocus" to set the focus to a control as shown below. 
    Page.SetFocus(tbName);
Note: Assuming "tbName" is the textbox control id on the page.

So, by using any of the above ways we can set the focus to a control from server side code itself. I hope this will help you. Please provide your comments on it.

NOTE: Don't try to set the focus to the control when it is in disable mode or invisible. This will give some problems in the client side.

Read More...

Client side validation of ASPX validation controls

This is the nice post under validating the ASPX validations in client side like java script. The concept behind is,

  • Some times we need to validate the .NET controls in client side whether they have correct values or not. We can do them in client side logic by using some existing functions available in javascript which are handled by ASP.NET framework.
  • And another requirement is on the page some controls are .NET controls and some are HTML controls. And all .NET controls are using the server side validation controls and html controls are using client side validation. So, when click on submit button, you need to detect whether form is valid or not on client side. So, you need to write some custom logic to detect all HTML controls are valid or not and then you need to detect all ASP.NET controls are having valid values or not. How will you detect that? You should validate both of them in javascript. So, this logic will help you to find the form is valid or not. 
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}

The above function is taking an argument named validationGroup. This is the validation group of the server side validation control. And the output or return value returning is the boolean value. If it is returning true then it passes the server side validation and false then it fails the server side validation. So, along with it's value you can write your own logic to validate the html controls and test whether form is valid or not.

Hope this helps and you can solve so many problems with this logic. Always welcome your valuable feedback and comments. Do you know any other ways to implement it?

Read More...

Check/Uncheck all checkboxes in Jquery

This is simple, but want to show you how to get it working in simple and efficient way. Usually we have a parent check box and then some child checkboxes. Depends on the parent check box selection, all the child checkboxes should behave exactly same. So, below is the Jquery function which will do that magic for you.
function CheckUncheckAllCheckBoxes(objID, checkedValue) {
if (objID == null || objID == undefined )
return;

$(objID + " input[type=checkbox]").each(function() {
this.checked = checkedValue;
});
}
If you observe, I am using two parameters for the function named objID and checkedValue. objID is the parameter for knowing which checkbox group or list we need to check or uncheck? Like, on a page we may have many checkboxes and groups or lists. So, we need a way to find out which group or list we need to check or uncheck? For this reason I added a parameter for the function to check only the checkboxes under that ID or Class. Possible values for the objID are
  1. #parent Control ID of the element which has the check boxes declared. Example: #ageList
  2. .parent control class of the element under which all the check boxes defined. Example: .edit
And second parameter, it is for passing the parent selected check box value. If it is ON, then logic will loop through and set the each checkbox to checked otherwise unchecked.

Usage - How to call this method:
Code for check/Uncheck all in ASP.NET
$("#<%=cbAllStates.ClientID %>").click(function() {
   CheckUncheckAllCheckBoxes("#<%=cblState.ClientID %>", this.checked);
});
Note: cblAllStates is the parent ASP.NET check box which is controlling child. cblState is the asp.net checkboxlist and in our terms child check boxes.

Code for Check/Uncheck all in HTML:
$("#cbAllStates").click(function() {
   CheckUncheckAllCheckBoxes("#divChilds", this.checked);
});
Note: cbAllStates is the parent check box control and divChilds is the division <DIV< tag which has all the child check boxes present in it.

**UPDATED** 06/22/2010
This is the small update for the check/uncheck the all check box depends on the child check box selection. If any of the child check box is unchecked or the all child check boxes are selected then the all check box will toggle depends on it. Below is the work around.

Example:
Code for  Toggling the all check box depends on the child check boxes:
function ToggleSelectAllCheckBox(allCheckBox, checkedValue, obj) {
    if (allCheckBox == null || allCheckBox == undefined)
        return;
    if (!checkedValue)
        $(allCheckBox).attr("checked", false);
    else {
        var areAllChecked = true;
        $(obj + " input[type=checkbox]").each(function() {
            if (!this.checked) {
                areAllChecked = false;               
            }
        });
        $(allCheckBox).attr("checked", areAllChecked);
    }
}
In the above function param1 is the all child check boxes, param2 is the current child check box selection and param3 is the all check box selector.

How to use:
ASP.NET Checkbox list:
$("#<%=cblAge.ClientID %> input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox("#<%=cbAllAges.ClientID %>", this.checked, "#<%=cblAge.ClientID %>");
 });
Note: cblAges is the check box list id and the cblAge is the all check box for the age group. So, the click event is for the all check boxes inside the check box list.

HTML Check boxes:
$(".ageGroup  input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox(".ageGroup", this.checked, "#allAgeCheckbox");
 });
Note: ".ageGroup" is the div or some parent element which holds all the checkboxes in HTML. "#allAgeCheckbox" is the id of the all checkbox for that age group.

**End of Update**

Hope this will help you to understand how to write code in efficient way and which helps for us in multiple scenarios. Always welcome your valuable comments. Read More...

ASP.NET Checkboxlist get values in client side [JQuery]

See my other post, which explains "how to set the value attribute for a single check box through c# code" before proceed to this post.

I know, this is the question most of the ASP.NET developers will ask or look for an answer on why there is no value attribute set for check box when it generates from the ASP.NET checkbox list? Where as the Radio button list, Drop down list and other controls has this value attribute set when you set the data source for them. But why there is no value attribute set for check box list control. Below is the nice explanation and will help you to understand the concept well.

If we assign some data source to the check box list control, then the HTML output is with two controls for each check box as input control with type checkbox and another is label with the text. So, This is the problem. How to get the value of the checkbox in client side using some javascript library? Here we need to think a way of how to set a attribute which holds the value for each checkbox and how to get it.

Below is the solution I found. In your C# code, after you bind the data source for the checkbox list, then need to add extra piece of code below to get our problem solved.

C# code:

foreach (ListItem li in checkBoxList.Items)
li.Attributes.Add("someValue", li.Value);

So, What happening here is, I am just adding extra attribute "someValue" for each check box in a check box list[checkBoxList] and looping through them and assign the actual value to that custom attribute. So that HTML for each checkbox on the page will render like this.

HTML rendered output:


If you observe, there is an extra parent control for each check box control named <SPAN> with the attribute we have set in c# code for each checkbox. Now you have some value set with each checkbox and you can get it on client side easily. [There is no change in C# code accessing values.]

How to access the values on client side?

I am using JQuery, so I will give an example of how to get the values using the JQuery.

To get all checkboxes which are checked under a checkbox list are accessed as follows.

JQuery code:

$("#<%=checkBoxList.ClientID %> input[type=checkbox]:checked").each(function() {
var currentValue= $(this).parent().attr('someValue');
if(currentValue != '')
values += currentValue + ",";
});

So, values is the string which holds all the selected checkbox values in a check box list which are selected with comma separated. I think, now you got an idea of how to access the values in client-side. Hope it will help you to understand what I am trying to say. Please add your valuable comments on it.

Read More...

Access IFrame content using Jquery

This is really helpful post for so many people who are using frames in their pages and want to access content inside it from main[parent] page. I really faced so many problems to read the data inside a frame and use it on the current page. So, it's simple and nice to know this tip for JQuery lovers.

HTML:

In Parent file, for example iFrame is declared as below.

<iframe id="uploadIFrame" scrolling="no" frameborder="0" hidefocus="true" style="text-align: center;vertical-align: top; border-style: none; margin: 0px; width: 100%; height: 60px;" src="IFrameExample.htm"></iframe>

In IFrameExample.htm, assume there is a hidden control as shown below.

<input type="hidden" id="hiddenExample" name="hiddenExample" />

So, now I will tell you how to set the "hiddenExample" hidden control value from the parent file. Because, we can’t directly access it through java script/HTML. We need to use below logic to get it working.

var $currentIFrame = $('#uploadIFrame');
$currentIFrame.contents().find("body #hiddenExample").val("Value from parent file.");

That's it!!! You are done with assigning some value to hidden variable inside IFrame. And in that iFrame you can access this hidden control on server side[C# or VB etc..] too. For it, you need to follow my other post. Very simple, but hard to find. Below is the nice explanation of above code. [How it will work.]

So, we are using Jquery, you know how to define JQuery object and use it in DOM. I created a variable[Object] currentIFrame which holds the whole IFrame reference. And in the second line, I am using the contents() method, which actually returns me all the HTML code of the frame. So, as we already know, find is the method we need to use to find out any element in a given scope/context. So, it tries to find out the occurrence of given criteria in current frame. I think you understood well how it works. If you are having multiple IFrames then you can define class for <iframe> instead of id and you can catch it in Jquery by using "." operator instead of "#". Is it a new and good find? Please let me know, if this helps you or any questions if you have.

Read More...

Get difference between Dates in Java script

It is very simple and easy to implement the difference between two dates. I received some queries on how to do it. So, this is the post for them.

function parseDate(str) {
    var date = str.split('/');
    return new Date(date[2], date[0] - 1, date[1]);
}

function GetDaysBetweenDates(date1, date2) {
    return (date2 - date1) / (1000 * 60 * 60 * 24)
}

"parseDate" is the function which is for converting a string to Date object. And the method "GetDaysBetweenDates" is expecting two date parameters which calculate the difference between the dates and return the result in number of days. You can change the formula as you want to return in time, months, weeks etc…

Enjoy!!!

Read More...

Steps to add a Web service 2.0 in SharePoint 2007

Today at my work, I need to implement JQuery in SharePoint on a module. I need to make AJAX calls to get the data from the database depending on the value in a text box. So, I choose JQuery, because I know it well and it will take very less time to implement. But for JQuery I need to create page web methods. But SharePoint doesn’t support Page web methods because SharePoint is completely built upon ASP.NET 2.0.

So, what is the solution, how can I make a call to the server and get the data from DB? After thought some time about it, finally I got a brilliant and better idea of using web services. Please follow the steps below to implement Web services in SharePoint.

  • We are using client side technologies like JQuery etc to call Web service to get the data from server. By default, it is not supported. For that, we need the supporting DLL's[System.Web.Script.Services] for the Web service script on the SharePoint server. These DLL's are needed to process the web service request and send the response[JSON]. For those DLL, you need to install the Ajax extensions 1.0.
  • Create a web service using Visual studio. It will generate two files webservice.asmx and webservice.cs. Write all the web methods required inside the webservice.cs file. I will explain you with an example more detail later in this post.
  • Now, we need a location to keep our *.cs [webservice.cs] file. So, for that, create App_Code folder in the SharePoint site file system virtual directory root [c:\inetpub\…\wss\virtualdirectories\portnumber]. You can find the advantages of using App_code folder, in SharePoint web application in this post.
  • By default SharePoint won't allow the script handlers and http modules. For this reasons, we need to make the web.config changes as explained in this post.
  • Change the settings in central admin to remove asmx extension from blocked file types. See it here.

After you are ready with all the above steps, then please follow the steps below.

  • Check the related dll’s are added in the system, after installed Ajax extensions. Below are the namespaces you required in the webservice.cs file.
  • using System.Web.Services;
    using System.Web.Script.Services;

  • Copy the webservice.asmx file to the SharePoint website virtual directory file system path [c:\inetpub\…\wss\virtualdirectories\portnumber\].
  • Copy the file webservice.cs file, and paste it in the app_code folder of the SharePoint web site.
  • Please follow the post web.config changes as explained.
  • Central administration changes as explained above.

There we are done with the process. This is really working great and we can solve really very difficult problems like all scenarios where we need to communicate with DB without doing post back etc. This is very smooth and fast way of retrieving results. I like to hear feedback. This is the one of the best solutions I found. Please post any problems if you face while implementing this process.

Isn't this a valuable find?

Read More...

Knowing browser width and height [for all browsers]

Today, at my work I need to implement java script for a SharePoint web page. First I developed the javascript in simple HTML page and after it is successful running I moved the code to SharePoint page.

In html page, it was working very fine and on the SharePoint page it was not. After some research I found the problem in the line document.documentElement.clientWidth and document.documentElement.clientHeight. I don’t know what the problem with this. I was browsing both HTML page and SharePoint page in the same browser. This behavior is weird.

Solution:

I researched on the javascript functions and read all the properties available for the document object and below is the code I came up with.

function GetWindowProps() {
var browserWidth = 0, browserHeight = 0;
//For checking non-IE browsers Mozilla, Safari, Opera, Chrome.
if (typeof (window.innerWidth) == 'number') {
browserWidth = window.innerWidth;
browserHeight = window.innerHeight;
}
//All IE except version 4
else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
}
//IE 4
else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
browserWidth = document.body.clientWidth;
browserHeight = document.body.clientHeight;
}
}

This will give you the correct values and it will work for any browser. How is it?

Read More...

JQuery integration in SharePoint

As we are well experienced with the JQuery in ASP.NET applications, JQuery is a client side script for executing really impressive logics, calling server-side methods, animations, smooth rendering etc.

SharePoint is a platform and which is built upon ASP.NET, so we can do all the stuff in SharePoint which we implemented in ASP.NET applications. Here is a small walk through of how to integrate the JQuery in SharePoint applications. We usually write lot of logics by using JQuery to get data from server using Ajax implementation by calling Page Web methods and render the data by using JTemplates etc… But We can’t implement the same in SharePoint because we can’t wriite page web methods. Reason behind is SharePoint don’t support page web methods because it is build with ASP.NET 2.0 version. Other than that you can implement all the logics in SharePoint as well.

Follow the steps below to integrate JQuery into SharePoint.

  • Open your SharePoint site in SharePoint designer.
  • It’s always better to organize your data and files in good structure. So create a folder for placing all scripts named “Scripts” if it does not exist.
  • Now copy the Jquery script file to this folder. I am using the file jquery-1.3.1.js.
  • Create an ASPX page in your pages folder of the site if it is a published web site template otherwise create a page in the root of site. [However, any place it works.]
  • This page is not a web part page, we are just creating a simple ASPX page for JQuery integration.
  • Here, add a reference to the JQuery java script file to the head tag of the page.
  • Add the below code to test the Jquery functionality to body of the page.
  • <script type="text/javascript">
        $(document).ready(function() {
            $("#cb").live('click', function() {
            $("#lblMessage").text("you clicked on CheckBox, selected = " + $("#cb").attr('checked'));
            });
        });
    </script>

    <input type="checkbox" id="cb" />
    <label id="lblMessage"></label>

  • We just wrote a very small piece of code snippet for testing the JQuery functionality. This post main goal is to integrate the JQuery plug-in for SharePoint. The same way you can add reference to the master page of the site to get the advantage of JQuery in all pages of the web site.

  • We can apply the master page to the current ASPX page by following this post. This will give you the same look and feel as other pages.

  • We have plenty of ways to do this. For example, for simple integration purpose i explained you to place the JQuery file in scripts folder of the root of the web site. But good way of doing is, placing the file in Layouts folder of 12 hive in SharePoint system. This way you can access the file in any site and on any page through out the SharePoint. Because Layouts is the common sub site exist for all the sites.

  • Adding script reference to all the pages in a site:

  1. Add the script reference to the <HEAD> tag of the master page of the site. So that all pages have the reference to the JQuery script and you can use it any where.
  2. Syntax: <script type=”text/javascript” src=”/_layouts/scripts/jquery-1.3.1.js”></script>
  • Add script reference to specific pages:
  1. For this we have a good and nice web part to add html/script/css. That is nothing  but Content Editor Web part. We can add a content editor web part on the page [most probably on the top of page] and we will add the script reference code to it. Now the JQuery is available only for the pages where you added the code.
Read More...

Use of XML HTTP Request object to make server calls through javascript

We have a requirement that we need to show light box when you click on search results in search results page. When i was new to ASP.NET and know some what about ASP.NET AJAX i thought of using it, but it didn't work out well. Because search results returns large amount of data and if i put everything in UpdatePanel then it can't process the request because Ajax is meant for processing small amounts of data to and from server.

The main requirement is on search results page, we are showing a title, small description and read more link, when anyone clicks on the read more link, it will make a server call and get's the corresponding search results related data and show it up on the page in light box. It needs an ajax call. So, here ASP.NET Ajax won't work. After thought about 2 days i got a new idea and implemented that and working great. Everything was implemented with 15 lines of javascript code by using the XMLHttpRequest object.

How it works:
I have created an ASPX page, where it will return the HTML i need to show in the light box. From the XMLHttpRequest object, i will call that page, gets the response from it and show it in the light box. Very simple!!!
You can use handlers as well to do this. We can write some logic like depends on the querystring params, inside HTTPHandlers build HTML and return that html to browser. But for better styling and html formatting i used ASPX page instead of handlers. Finally, we will catch the response and bind it to the page.

ASPX CODE:








Explanation:
  1. I have taken a data list on my page, where it binds all the search results which matches the given keywords.
  2. I am using data bound event to bind the data on the server side, you can check that in the ASPX.CS section.
  3. I am using a ASP panel, to bind the response from the server and to show the light box. (This is tha panel we are using to bind the response from the server and show the light box.)
ASPX.CS:
protected void dlData_DataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header || e.Item.ItemType == ListItemType.Footer) return;

Literal litTitle = e.Item.FindControl("litTitle") as Literal;
string anchorText = "<a href="javascript:void();" onclick="\"javascript:loadurl('{0}','{2}');return false;\">{1}</a>";
litTitle.Text = String.Format(anchorText, "Path of the page", "Title", panelLightBox.ClientID);
}
Note: "Path of page" is the actual page we need to call, and "Title" is the anchor text.


Explanation:
In this event, you can get the server object and bind the data to the controls declared in the item template of the data list. Example purpose, i am binding data to only litTitle control.

Here, if you observe i am creating a html anchor tag and binding that to the literal control, it's not a good way, rather you can create a html anchor control with runat="server" in Item template and bind the data to it, any thing works. I am using onclick event to make a call to the server, in the onclick event of the HTML anchor control i am calling a javascript function called, "loadurl", which will make a server request through XMLHttpRequest obejct.
So, the process is,
  1. From our code, when you click on the title, it will call the loadurl javascript function.
  2. In loadurl function, we will create a xml http request object and sends the request to server.
  3. We will get response from the server and we will catch the responseText from it, and bind it to the light box control.
You can check the loadurl function below.

JAVASCRIPT:
var xmlhttp;
function loadurl(dest, parentID) {
try {
xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
xmlhttp.onreadystatechange = function(){triggered( parentID)};
//xmlhttp.setContentType("text/xml");
xmlhttp.open("GET", dest);
xmlhttp.send('');
}
var mainLightBoxDiv = null;
function triggered( parentID) {mainLightBoxDiv = parentID;
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
{
var div = document.getElementById(parentID);
div.innerHTML = xmlhttp.responseText.toString();

if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
var centerY = (yScroll + 170);
div.style.top = centerY+'px';
div.style.display="block";
}
}

function CloseDiv()
{
document.getElementById(mainLightBoxDiv).style.display = 'none';
}
Explanation:
  1. We are using two variables. One for the destination url, and one for the parentID which holds the id of the control for light box.
  2. We are creating an XMLHttpRequest object.
  3. When ready state changed, we are trigerring one event to process our request.
  4. Making the GET request to get the data from server.
  5. Binding the reponseText from the response to the parentID innerHTML.
  6. And some sort of logic to detect the y axis unit where we need to show light box, for this we are detecting the scrollbar position and setting the position of the division. i am doing some operation by adding/subtracting 170 - which is the minimum height of the light box in my scenario.
  7. We are using another function to close the light box.
These days, there are lot of technologies are coming and the best way of implement the above case is using JQuery. We cn use JTemplates to bind the search results data and make an ajax call to the page web method to get what we want. This is very simple and best.

For seeing it live or to test, you can see the page i developed for one of our client.

Very simple!!! Happy coding. Read More...

replace querystring with some value in javascript

In my project, i have a requirement that we need to get url from the browser and depends on user selection, or some criteria we need to change some querystring values and reload the page with new url. Here is a small function which will do that in javascript.
function replaceQueryString(url, param, value) {
var preURL = "";
var postURL = "";
var newURL = "";

var start = url.indexOf(param+"=");
if(start > -1)
{
var end = url.indexOf("=", start);
preURL=url.substring(0,end) +"="+value;

var startRest = url.indexOf("&",start);
postURL="";
if(startRest > -1)
{
postURL=url.substring(startRest);
}
}
else
{
var delimeter = "";
preURL=url;
if (url.indexOf("?") > 0)
delimeter = '&';
else
delimeter = '?';

postURL=delimeter+param+"="+value;
}
newURL = preURL+postURL;
var index = newURL.indexOf('id=',0);
if(index > -1)
{
var Nurl = newURL.substring(0,index);
var EUrl = newURL.substr(index,newURL.length - index);
var eIndex = EUrl.indexOf('&',0);
if(eIndex > -1)
EUrl = EUrl.substr(eIndex, EUrl.length - eIndex);
//newURL = newURL.substring();
newURL = Nurl + EUrl;
}
return newURL;
}
the newUrl which builds the new url with updated querystring values. Read More...
Related Posts with Thumbnails
GiF Pictures, Images and Photos