Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, August 12, 2013

Javascript shift(), unshift(), pop(), push(), concat(), splice() functions

Hi to day i'll digg into shift(), unshift(), pop(), push(), concat(), splice() functions of javascript :


var arr, alphaNumeric;

var alpha = ['A', 'B', 'C'];
var numeric = [10, 20, 30];
arr = alpha;
console.log('ORIGINAL ARRAY: '+ arr);

// SHIFT
var shifted = arr.shift();
console.log('SHIFTED: '+ shifted);
console.log('ARRAY AFTER SHIFT: '+ arr);

// UNSHIFT
var toUnshift = ['D'];
arr.unshift(toUnshift);
console.log('UNSHIFTED: '+ toUnshift);
console.log('ARRAY AFTER UNSHIFT: '+ arr);

// POP
var popped = arr.pop();
console.log('POPPED: '+ popped);
console.log('ARRAY AFTER POP: '+ arr);

// PUSH
var toPush = ['Z'];
arr.push(toPush);
console.log('PUSHED: '+ toPush);
console.log('ARRAY AFTER PUSH: '+ arr);

// CONCATE
alphaNumeric = alpha.concat(numeric);
console.log('ARRAY: '+ arr);
console.log('ALPHA: '+ alpha);
console.log('NUMERIC: '+ numeric);
console.log('ALPHANUMERIC: '+ alphaNumeric);
alphaNumeric = alpha.concat(1, [2, 3]);
console.log('NEW ALPHANUMERIC: '+ alphaNumeric);

// SPLICE
var startingIndex = 2, howManyToRemove = 2;
var elementsToAdd = ['P'];
var removed;
var minVal = Number.MIN_VALUE, maxVal = Number.MAX_VALUE;

//removed = alphaNumeric.splice(); // does nothing
//removed = alphaNumeric.splice(startingIndex); // removes all from the given index
//removed = alphaNumeric.splice(startingIndex, howManyToRemove); // removes 'n' from the given index
removed = alphaNumeric.splice(startingIndex, howManyToRemove, elementsToAdd); // removes 'n' from the given index, and then add new elements
//removed = alphaNumeric.splice(startingIndex, minVal);
//removed = alphaNumeric.splice(startingIndex, maxVal);

//console.log('minVal: '+ minVal);
//console.log('maxVal: '+ maxVal);

console.log('SPLICED: '+ removed);

console.log('ARRAY AFTER SPLICE: '+ alphaNumeric);

Friday, April 19, 2013

Custom setInterval() function javascript or jquery

Hello friends,

At some point of my jquery problem, i wanted to call a particular funtion 'n' times and in 'x' interval(in seconds). I relied on javascript's setInterval() method, but the catch is that it is called forever.

So I've made a jquery function which does the functionality as requiered by user.

var main = {};
// the funtion definition ...
main.TimerFunction = function (opts) {
// interval in seconds ...
var intervalTime = opts.IntervalInSeconds * 1000;
// cutomized setInterval method ...
var intervalId = setInterval(function () {
   // if the functionToExecute is to be called forever ...
   if ((opts.CallForever != undefined) && (opts.CallForever == true)) {
        opts.FunctionToExecute();
   }

   // if functionToExecute is to be called "n" times ...
   else if ((opts.TimesToCall != undefined) && (opts.TimesToCall != 0)) {
       for (var i = 0; i < opts.TimesToCall; i++) {
                opts.TimesToCall = opts.TimesToCall - 1;
                opts.FunctionToExecute();
                clearInterval(intervalId);
                main.TimerFunction(opts);

                break;
       }
   }                    

   // else clear intervalId ...
   else {
       clearInterval(intervalId);
   }
}, intervalTime);
};




Now if i want to execute a funtion just 3 times at the interval of 5 seconds, i'll  call the above function as :
var params = {};
params.FunctionToExecute = function () {
      alert('Hello World !');
};
params.CallForever =
false;     // true, if you want to call it forever ...
params.TimesToCall = 3;         // calling the FunctionToExecute 3 times ...
params.IntervalInSeconds = 5;   // FunctionToExecute will be called every 5 seconds ...
main.TimerFunction(params);     // pass the parameters, and call the function ...



Enjoy,

Friday, October 24, 2008

How To Get Query-String Values From Javascript ?



function GetQueryStringValueFor(key)
{
var valueToReturn="";
var query = window.location.search.substring(1);
var parms = query.split('&');
for(var i=0 to parms.length)
{ var pos = parms[i].indexOf('=');
if (pos > 0)
{
if(key==parms[i].substring(0,pos))
{
valueToReturn = parms[i].substring(pos+1);
}
}
}
return valueToReturn;
}

Thursday, September 25, 2008

Calling Server-Side(ASP.Net) Method from Client-Side(Javascript)

.ASPX Code ...

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test_ClientToServerPostback.aspx.cs"

Inherits="test_ClientToServerPostback" %>

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>Calling Server-Side Method from Client-Side Javascript.title>
<script type="text/javascript">
function LookUp()
{
var lbl = document.getElementById("TextBox1");
CallServerMethod(lbl.value, "");
}

function ReturnedServerData(retValue)
{
document.getElementById("Label1").innerHTML = retValue;
}
script>
head>
<
body>
<form id="form1" runat="server">
<div>
Try Writing : accept/reject <br/> and see the result.<br />
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox><br />
<a href="#" onclick="LookUp();">ClickMea><br />
<br />
<asp:Label ID="Label1" runat="server">asp:Label>
div>
form>
body>
html>

===============================

.CS Code ...

using System;
using System.Web.UI;

public partial class test_ClientToServerPostback : System.Web.UI.Page, ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReturnedServerData", "context");
String callbackScript = "function CallServerMethod(arg, context)" + "{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServerMethod", callbackScript, true);
}
}

public void RaiseCallbackEvent(String eventArgument)
{
if (eventArgument.Trim() == String.Empty)
{
returnValue = "Sorry, please write somthing in textbox.";
}
else
{
if (eventArgument == "accept")
{
returnValue = "Congrats, for accepting!";
}
else if (eventArgument == "reject")
{
returnValue = "You have succesfully rejected !";
}
else
{
returnValue = "You have entered : " + eventArgument + ".";
}
}
}

public String GetCallbackResult()
{
return returnValue;
}
}

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Monday, May 19, 2008

Setting Homepage Using JavaScript

function setasHome()
{
document.body.style.behavior='url(#default#homepage)';
document.body.setHomePage('www.url.com');
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Adding a bookmark in browser using JavaScript

function CreateBookmarkLink() {
title = "TitleForBookmark";
url = "www.url.com'';
if (window.sidebar) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
} else if( window.external ) {
// IE Favorite
window.external.AddFavorite( url, title);
}
else if(window.opera && window.print) {
// Opera Hotlist
return true; }
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Friday, February 22, 2008

Javascript Client Side Page Validation

// In .cs file …

btn_register.Attributes.Add("onclick", "javascript:return ValidateForm()");

=======================================

// In .aspx file in script …

function ValidateForm()

{

//debugger

var p = document.getElementById( "ctl00_ContentPlaceHolder1_txt_phone").value;

var q = document.getElementById ("ctl00_ContentPlaceHolder1_Check_accept");

var fname = document.getElementById ("ctl00_ContentPlaceHolder1_txt_firstname");

var email = document.getElementById ("ctl00_ContentPlaceHolder1_txt_email_id");

var pwd = document.getElementById ("ctl00_ContentPlaceHolder1_txt_password");

if(fname.value=="")

{

alert("Please Enter First Name.")

return false

}

else if(email.value=="")

{

alert("Please Enter Email-ID.")

return false

}

else if(pwd.value=="")

{

alert("Please Enter Password.")

return false

}

else if(!q.checked)

{

alert("You Must Agree Terms \& Conditions To Get Registered.")

return false

}

else if ( document.getElementById (" ctl00_ContentPlaceHolder1_txt_phone" )!="")

{

var num=" ";

chkD = 0

if(p > "")

{

num = p;

}

for (var i = 0; i <>

{

var oneChar = num.charAt(i)

if (oneChar == "." && chkD == 0)

{

chkD = 1

continue

}

if (oneChar < "0" || oneChar > "9")

{

alert("Please Enter Some Valid Phone Numbers.")

return false

}

}

}

}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Friday, February 1, 2008

Opening a Pop-Up Window

//Add this to the Page_Load() ...

Button_ToOpenPopupWindow.Attributes.Add ("onclick", "window.open ('PopUp_WindowToOpen.aspx', null, 'height=600, width=460, status= yes, resizable= no, scrollbars=no, toolbar=no, location=no, menubar=no, minimize=no '); ");


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Tuesday, January 29, 2008

Mouse Events in JavaScript

//WRITE THESE FUNCTIONS IN JAVASCRIPT ...

function sname_focus()

{

if( window.document.all.sendmsg.SenderName.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderName.value = "";

window.document.all.sendmsg.SenderName.style.fontStyle = "normal";

}

}

function sname_blur()

{

if( window.document.all.sendmsg.SenderName.value == "")

{

window.document.all.sendmsg.SenderName.value = "Name of Contact";

window.document.all.sendmsg.SenderName.style.fontStyle = "italic";

}

}

function scompany_focus()

{

if( window.document.all.sendmsg.SenderCompany.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderCompany.value = "";

window.document.all.sendmsg.SenderCompany.style.fontStyle = "normal";

}

}

function scompany_blur()

{

if( window.document.all.sendmsg.SenderCompany.value == "")

{

window.document.all.sendmsg.SenderCompany.value = "Company Name";

window.document.all.sendmsg.SenderCompany.style.fontStyle = "italic";

}

}

function semail_focus()

{

if( window.document.all.sendmsg.SenderEmail.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderEmail.value = "";

window.document.all.sendmsg.SenderEmail.style.fontStyle = "normal";

}

}

function semail_blur()

{

if( window.document.all.sendmsg.SenderEmail.value == "")

{

window.document.all.sendmsg.SenderEmail.value = "Email Address";

window.document.all.sendmsg.SenderEmail.style.fontStyle = "italic";

}

}

function sphone_focus()

{

if( window.document.all.sendmsg.SenderPhone.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderPhone.value = "";

window.document.all.sendmsg.SenderPhone.style.fontStyle = "normal";

}

}

function sphone_blur()

{

if( window.document.all.sendmsg.SenderPhone.value == "")

{

window.document.all.sendmsg.SenderPhone.value = "Phone Number";

window.document.all.sendmsg.SenderPhone.style.fontStyle = "italic";

}

}

function smessage_focus()

{

if( window.document.all.sendmsg.SenderMessage.style.fontStyle == "italic")

{

window.document.all.sendmsg.SenderMessage.value = "";

window.document.all.sendmsg.SenderMessage.style.fontStyle = "normal";

}

}

function smessage_blur()

{

if( window.document.all.sendmsg.SenderMessage.value == "")

{

window.document.all.sendmsg.SenderMessage.value = "Message to Send";

window.document.all.sendmsg.SenderMessage.style.fontStyle = "italic";

}

}

function setboxstyles()

{

window.document.all.sendmsg.SenderName.style.fontStyle = "italic";

window.document.all.sendmsg.SenderCompany.style.fontStyle = "italic";

window.document.all.sendmsg.SenderEmail.style.fontStyle = "italic";

window.document.all.sendmsg.SenderPhone.style.fontStyle = "italic";

window.document.all.sendmsg.SenderMessage.style.fontStyle = "italic";

}


========================================================
//If you want to toggle the textbox values, if the mouse is clickes in it ...

input name="SenderName" type="text" value="Name of Contact" id="SenderName" onFocus="sname_focus()" onBlur="sname_blur()" class=contactsendmsg style="font-style:italic" />

// If you want to make a mouse-over events on buttons, etc ...

td width=90 valign=middle align=center style="cursor:pointer" onclick="window.location=('aboutus.htm')" id=aboutdiv class=mainmenutd onmouseover="changelayer_color('aboutdiv','maincolorover');" onmouseout="changelayer_color('aboutdiv','maincolorout');"><font class=mainmenutext>About Usfont>td>


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Monday, January 28, 2008

Toggle DIV Visibility In .aspx File

<DIV style="CURSOR: hand; COLOR: blue" onclick="ShowHideImageUploader()">

<span style="font-family: Arial; font-weight:bold">Open Insertion span>DIV>


===================================================

function ShowHideImageUploader()

{

if(document.getElementById('tblyes').style.display=='none')

{

document.getElementById('tblyes').style.display='block';

}

else

{

document.getElementById('tblyes').style.display='none';

}

}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Friday, January 25, 2008

Alerting A Multiline Text In ASP.Net 2.0

script type="text/javascript">
function disp_alert()
{
alert("First line" + '\n' + "second line");
}


input onclick="disp_alert()" value="Display alert box" type="button"

=================================================================

Code for ".cs" file ...

string str_msg = "Thank you for your feedback.\\n We will be reverting back to you soon.";

ClientScript.RegisterStartupScript (this.GetType(), "script", "script language = 'javascript'> alert('" + str_msg + "'); ");


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Inserting Values in Parent Page from a Pop-Up Wndow

function parent_location()

{

var firstname ,lastname ;

//store value in variables using getelementbyid

firstname = document.getElementById("txtFname").value;

lastname = document.getElementById("txtLname").value;

//value send in parent form

window.opener.document.getElementById( "ctl00_ContentPlaceHolder1_TextBox_FName").value = firstname;

window.opener.document.getElementById( "ctl00_ContentPlaceHolder1_TextBox_LName").value = lastname;

//closing the PopUp window

window.close();

}


=================================================

Add this Code on Page_Load ...

Button2.Attributes.Add("onclick", "javascript:return parent_location()");


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Opening A New Window

<a style="text-align:right" href="#" onclick="window.open ('../DisplayImage.aspx?Id= <%#DataBinder.Eval(Container.DataItem,"Photo_Id")%> ', null, 'height=700, width=700, status=yes, toolbar=no, menubar=no, location=no, scrollbars=1') ">

-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

Displaying Alert Without Postback

ClientScript.RegisterStartupScript( this.GetType(), "script", "script language="'javascript'"> alert('This is the alert message !'); " );



-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript