Showing posts with label java script. Show all posts
Showing posts with label java script. Show all posts

Saturday, January 18, 2014

Observer Design Pattern in Jquery


We can use observer design pattern (publisher - subscriber model) in jquery by triggering and attaching events.
Attach a trigger event for publisher
$('div').on('click', function(e) {
    $(this).trigger('MyEvent',e,parameterValue);
});


Attach subscriber methods
$(document).on('MyEvent', function(e,parameterValue) {
    //Do your stuffs with parameterValues..
});
Read More

Monday, August 22, 2011

HTML Encode/Decode using JQuery

using below code you can encode/decode html tags using jquery

function htmlEncode(value){
  return $('
').text(value).html(); } function htmlDecode(value){ return $('
').html(value).text(); }

Compiled By: Rajesh Rolen

Read More

Thursday, August 11, 2011

show multiple jquery scroller in single page



To show multiple jquery scroller in single page just add an extra div on outer side or every scroller. means place every scroller in seperate div and its done..


Compiled By: Rajesh Rolen

Read More

Monday, April 4, 2011

What is use of === and !== in javascript

=== and !== are strict comparison operators:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Two Boolean operands are strictly equal if both are true or both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===).

References: Comparison Operations

Solution By: Rajesh Rolen

Read More

Tuesday, March 15, 2011

Insert item in listbox at top using javascript

many of times we have requirement to add a item at top of listbox using javascript (add item at index 0).


       var txtl = document.getElementById("<%= txtvalue.ClientID %>");
        var lst = document.getElementById("<%=mylistbox.ClientID %>");
        if(txtl.value != "")
        {
            var opt = document.createElement("Option");
            opt.text =txtl.value;
            opt.value = txtl.value;
            lst.options.add(opt,0);  // here while adding new item to listbox we can pass its index number. 
        }



Solution By: Rajesh Rolen





Read More

Wednesday, February 16, 2011

How to Replace All Occurrences of a String using Javascript Replace Function

As we all use javascript's "replace()" function to replace string but normally it replace only first matched text and leave all other.
for eg.
var string_variable = "this is stringToBeReplaced and now again stringToBeReplaced occurred";
string_variable = string_variable.replace("stringToBeReplaced", "NewString");
now if you will print value of string_variable then it will be like:
"this is NewString and now again stringToBeReplaced occurred"
so as you can see in above string only first concurrence of "stringToBeReplaced" is replaced.

Now, if you wants to replace all occurrence of string then the same "replace()" function can help you out:

eg.
var string_variable = "this is stringToBeReplaced and now again stringToBeReplaced occurred";
string_variable = string_variable.replace(/stringToBeReplaced/g, "NewString");
now if you will print value of string_variable then it will be like:
"this is NewString and now again NewString occurred"
How we can enable global regular expression is as simple as adding the "g" identifier following the regular expression.
Using "g" following the regular expression pattern, builtin javascript replace method will replace all matches and all occurences of the given text variable with the new string.

Solution By: Rajesh Rolen

Read More

Tuesday, January 4, 2011

Get File size in javascript

function A()
 {
 var oas = new ActiveXObject("Scripting.FileSystemObject");
 var d = document.a.b.value;
 var e = oas.getFile(d);
 var f = e.size;
 alert(f + " bytes");
 }
  
 
 <form name="a" >
  <input type="file" name="b" >
  <input type="button" name="c" value="SIZE" onClick="A();" >
  </form >
  </body >

Read More

Friday, December 3, 2010

How to set PopUp Window size of current Page

To change height and width of current window we can use resizeTo function like:
window.resizeTo(iWidth, iHeight) 


Solution By

Rajesh Rolen

Read More

Friday, November 12, 2010

What is Bookmarklet / what is use of Bookmarklet

Each bookmarklet is a tiny program (a JavaScript application) contained in a bookmark (the URL is a "javascript:" URL) which can be saved and used the same way you use normal bookmarks. The idea was suggested in the Netscape JavaScript Guide.

JavaScript has been used by page authors on millions of webpages; Bookmarklets allow anybody to use JavaScript - on whatever page you choose (not just your own page).

so A bookmarklet is an applet, a small computer application, stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. The term is a portmanteau of the terms bookmark and applet. Whether bookmarklet utilities are stored as bookmarks or hyperlinks, they are designed to add one-click functionality to a browser or web page. When clicked, a bookmarklet performs some function, one of a wide variety such as a search query or data extraction. Usually the applet is a JavaScript program.

Web browsers use URIs for the href attribute of the < a > tag and for bookmarks. The URI scheme, such as http:, file:, or ftp:, specifies the protocol and required form for the rest of the string. Browsers also implement a prefix javascript: that to a parser is just like any other URI. Internally, the browser sees that the protocol is javascript, treats the rest of the string as javascript code which is then executed, and uses the resulting string as the new page.

The executing script has access to the current page, which it may inspect and change. If the script returns an undefined type (rather than, say, a string), the browser will not load a new page, with the result that the script simply runs against the current page content. This permits in-place font size and color changes, for example, without a page reload.

An anonymous function can be used to force the script to return an undefined type:

javascript:(function(){
/* Statements returning a non-undefined type, e.g. assignments */
})();


Bookmarklets are saved and used as normal bookmarks. As such, they are simple "one-click" tools which add functionality to the browser. For example, they can:

- Modify the appearance of a web page within the browser (e.g., change font size, background color, etc.).
- Extract data from a web page (e.g., hyperlinks, images, text, etc.).
- Submit the current page to a blogging service such as Posterous, link-shortening service such as su.pr, or bookmarking service such as Delicious.
- Query a search engine, with search term(s) provided by previously selected text, or by a dialog box.
- Submit the current page to a link validation service, or translation service.
- Set commonly chosen configuration options when the page itself provides no way to do this.

Bookmarklets are safer than traditional software for the following reasons:

- They are extremely simple. With only a few lines of code it's hard to make a programming error that isn't detected immediately.

- You don't install software. Traditional software programs can produce conflicts with other programs on your hard drive. Bookmarklets work entirely within your web browser, so they can't independently interfere with the functioning of other programs.

- Even if something goes wrong (say, you try to use a Netscape-only bookmarklet on Internet Explorer) the worst thing that is likely to happen is that you will get a JavaScript error message. Furthermore, this site has been designed (through server-side scripting) to make it impossible for you to get a bookmarklet that doesn't work on your browser.

- Because you don't install software, you don't have the security risks of traditional software (which can install files all over your hard drive). Your hard drive is protected by JavaScript security restrictions.
Read More

Monday, November 1, 2010

Gridview with master-slave data

some times we wants to show gridview with master-child data. so that on click of master the details should be shown in child.
To do so here is a very good article:

http://www.progtalk.com/viewarticle.aspx?articleid=54
Read More

Thursday, October 28, 2010

Extract url from string

To extract URL from a string you can use below javascript functions:


function parseUrl1(data) {
var e=/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/;

if (data.match(e)) {
return {url: RegExp['$&'],
protocol: RegExp.$2,
host:RegExp.$3,
path:RegExp.$4,
file:RegExp.$6,
hash:RegExp.$7};
}
else {
return {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}



function parseUrl2(data) { var e=/((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w-.]+.[^#?\s]+)(#[\w-]+)?/;

if (data.match(e)) {
return {url: RegExp['$&'],
protocol: RegExp.$2,
host:RegExp.$3,
path:RegExp.$4,
file:RegExp.$6,
hash:RegExp.$7};
}
else {
return {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}




References :http://lawrence.ecorp.net/inet/samples/regexp-parse.php
Read More

Monday, October 4, 2010

How to detect browser using javascript

we can use navigator.userAgent to detect the type/name of current browser and perform compatibility operations according to it:

below is javascript code so put it in script tag


function DetectBrowser()
{

var val = navigator.userAgent.toLowerCase();



if(val.indexOf("firefox") > -1)

{

isFF = true;

}

else if(val.indexOf("opera") > -1)

{
isOP = true;

}

else if(val.indexOf("msie") > -1)

{

isIE = true;

}

else if(val.indexOf("safari") > -1)

{

isIE = true;

}
}
Read More

Wednesday, September 29, 2010

call function in javascript before window close

if you want to ask user before closing popup window or you want to perform certain operation before window gets closed, you can use below code for that:


window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}

Solution by:Rajesh Rolen

Read More

Thursday, September 23, 2010

Load XML using javascript [works with all browser]

When ever we wants to load and parse xml using javascript. we face a issue most of time is that the script works with one browser but not works with other.
Below script will work on all browsers including [safari,mizila firefox, crome]:


function loadxml() {
var xmlFeed = "xmldata/wfc20100915.xml";
if (window.ActiveXObject) {
var errorHappendHere = "Check Browser and security settings";
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(xmlFeed);
}
else if (window.XMLHttpRequest) {
var errorHappendHere = "Error handling XMLHttpRequest request";
var d = new XMLHttpRequest();
d.open("GET", xmlFeed, false);
d.send(null);
xmlDoc = d.responseXML;
} else {
var errorHappendHere = "Error.";
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load(xmlFeed);
}


var tmp = readXML();

return tmp;
}
//below code is to read xml
function readXML() {

var labels = xmlDoc.getElementsByTagName('node');
arr = new Array();
var counter = 0;
for (i = 0; i < labels.length/ 10; i++) {
{
if (labels[i].childNodes.length >= 9) {
arr[counter] = new Array(5);
arr[counter][0] = parseFloat(labels[i].childNodes[1].textContent);
arr[counter][1] = parseFloat(labels[i].childNodes[3].textContent);
arr[counter][2] = parseFloat(labels[i].childNodes[5].textContent);
arr[counter][3] = parseFloat(labels[i].childNodes[7].textContent);
arr[counter][4] = parseFloat(labels[i].childNodes[9].textContent);
counter++;
}

}

return arr;

}


Solutions by: Rajesh Rolen

Read More

Sunday, September 19, 2010

Timer in javascript

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

* setTimeout() - executes a code some time in the future
* clearTimeout() - cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.
The setTimeout() Method
Syntax
var t=setTimeout("javascript statement",milliseconds);

The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name.

The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()".

The second parameter indicates how many milliseconds from now you want to execute the first parameter.

lets say I wanted to start download a file after 5 seconds of loading my web page.
for that i created below function which i using javascript timer:


write it in script tag in .aspx file:
function startdown() {
var url = "<%= siteurl %>";
setTimeout("window.location.href='" + url + "';", 5000);
}

in .cs file write below code:
protected void Page_LoadComplete(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "downloadnewwin", "startdown();", true);

}

you can use this timer for calling various javascript function or for any other activity.

Solutions By:Rajesh Rolen

Read More

Friday, August 6, 2010

Adding or Removing values from Array using javascript

We can add or remove values from an array using splice() function.

the splice() function returns the removed element(s).
syntex: arrayName.splice(Startindex,HowManyElements,element1,.....,elementX)

eg.
< script type="text/javascript" >

var employes = ["Rolen", "Pankaj", "JS", "Bhupendra"];
document.write("Removed: " + employes.splice(2,1,"Pankaj") + "< br / >");
document.write(employes);

< /script >

Solution By: Rajesh Rolen
Read More

Wednesday, July 21, 2010

Attach double click event on listbox in asp.net

when we want to attach double click event on asp.net listbox we can make by using javascipt.


protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "myListBox_Dblclk")
{

//your code to perform task or to call desired function

}
myListBox.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(myListBox, "myListBox_Dblclk"));
}
by: Rajesh Rolen
Read More

Monday, June 21, 2010

Trim text using javascript

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}
Read More

Add/delete rows in HTML Table at run time using javascript

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

function addrow()
{
var tbody = document.getElementById("< %= tableName.ClientID % >").getElementsByTagName("TBODY")[0];
var row = document.createElement("TR")
var td1 = document.createElement("TD")
var td2 = document.createElement("TD")
var td3 = document.createElement("TD")

td1.appendChild(document.createTextNode("value"));
td2.appendChild(document.createTextNode("value));

//to add hyper liked cell for delete row
var code = "< a href=\'#\' onClick=\"javascript:deleteCriteria(this.parentNode.parentNode.rowIndex);\" >< img src=\"Images/user_delete.png\" alt=\"Delete\" / >< /a >";

td3.setAttribute("align", "center");
td3.innerHTML = code;

row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);

tbody.appendChild(row);
}

function deleteCriteria(i) {
if (window.confirm('Are you sure you want to delete this record?') == true) {
document.getElementById("< %= tblcriteria.ClientID % >").deleteRow(i);

}
}
< /script >
Read More

Friday, March 12, 2010

How to check in javascript that string contains a substring or not

many of times we need to find out that a particular string contains a particular (charactor or string ) or not.
so below example will help you.
var varA = "hello how r u";
if(varA.indexOf("How") != -1)
{
alert('it contains How');
}
else
{
alert('it not contains how');
}

Article by: Rajesh Rolen
Read More
Powered By Blogger · Designed By Seo Blogger Templates