Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Javascript delete property vs. nullifying it?

Let's start with a simple object:
var person = {
   firstName: 'John',
   middleName: 'D.',
   lastName: 'Doe'
}

The most common way to get rid of a property value is to nullify it or make it undefined.
Ex.
person.middleName = null;
or
person.middleName = undefined;

var person = {
   firstName: 'John',
   middleName: null,
   lastName: 'Doe'
}


Other way is to just delete it.

The delete operator does a different job by removing the whole property, returning true or false to indicate the success of the operation. In fact the deletion does not do anything related to freeing memory or releasing resources. It is just removing the property so it no longer appears in the object skeleton.
Ex.
delete  person.middleName;

This will result into
var person = {
   firstName: 'John',
   lastName: 'Doe'
}
Obviously deleting a property may help in cases when you need to enumerate the object properties and property must not appear any more. 

Deleting an array element is a different thing. The deleted element gets undefined, but the actual array length is not changing. The actual usage difference between using 'undefined' or delete operator appears to be in object properties. 

What is ECMAScript and ES6, ES7, etc.?

ECMA is an association for standardizing information and communication systems. ECMA standardizes JavaScript under the name of ECMAScript.
In a nutshell ECMAScript is a standard while JavaScript is the implementation of this standard. 

All name like ES1, ES2, ES3, ES4, ES5, ES6, ES7, etc., are abbreviations of the ECMAScript version.
ES6 was issued in 2015 and also called ES2015. As of 2015, all new versions of ES are supposed to be named by the year - ES2016 (ES7), ES2018 (ES8), etc.

ES.next is the abbreviation of all upcoming, not standardized yet versions.

The ECMA standard is supported by browsers. The following table provide extensive information about the browser support, feature by feature:
https://kangax.github.io/compat-table/es6/

In order to provide better browser support, tools like Babel can help you use latest JavaScript features into older browsers. Babel is a JavaScript compiler, more precisely said - a transpiler, that allows developers to program using ES6 feature converted to a Javascript code that current browsers can process. React (ReactJS) is a great example of Babel usage.

How to check if JavaScript function exists?

Checking if function exists differs from the regular object checking. In order to ensure a function exists you can use typeof operator for the verification.

if (typeof myFunctionName === 'function') {
     myFunctionName();
}

Solution on "HTTP Error 414 Request URI too long" error using getJSON

The explanation of 414 error is described here:
http://support.microsoft.com/kb/248061

With regard to JSON queries with jQuery this basically means we are not able to use long GET parameters. But for sure this is necessary for sending bigger objects serialized as JSON.
The solution would be using POST requests, but is jQuery support that?

The answer is yes if we just extend jQuery with post requests as it is described in jQuery forum:
http://forum.jquery.com/topic/getjson-using-post

jQuery.extend({
postJSON: function( url, data, callback) {
return jQuery.post(url, data, callback, "json");
}
});

Then just replace getJSON with postJSON where it is needed.

Strip time from javascript date object

Setting up the hours to zero does the trick:

var myDate = new Date(); //current date and time
myDate.setHours(0,0,0,0);

Stop a postback by javascript with IE7

Somehow the statement javascritpt:return false; doesnt work with IE 7. But there is a workaround by setting the event.returnValue to false.

OnClientClick="javascript:event.returnValue=false; return false;"

Minifying javascript source files.

I just want to recommend you a very simple tool called JSMin, which helps minifying the javascript sources. This code improvement significantly decreases the download time because of the smaller page size. The toll successfully removes whitespaces and comments which are not needed on client side.

The tool is available as a script or a console application.

The usage of jsmin.exe is simple:
jsmin.exe output.js

Javascript Query String

The query string is reachable through window.location.search property. Splitting it by & gives you list of passed GET parameters.


function GetPageParameter(param) {
var query ='';
if (window.location.search.length>3){
//removes '?' from the query string
query = window.location.search.substring(1);
}else{
return '';
}
params = query.split("&");
for (i=0;i1){
if (pair[0] == param) {
return pair[1];
}
}else{
return '';
}
}
return '';
}

var value = GetPageParameter("value");

Escape apostrophe in javascript and dynamic built scripts

The apostrophe in javascript is its string delimiter. To render the apostrophe on the response without errors it must be escaped using backslash \.

alert('John\'s name') will produce message box with text: John's name.

Using asp.net usually the scripts are built dynamically on server side before rendering the page. Remember that the backslash is also escape character in C# and you have to put two backslashes to build the javascript correctly:

Response.Write("alert('John\\'s name');");

Javascript trace log

Simple and useful tool can be found here:

http://v2.easy-designs.net/code/jsTrace/


Using it you can get rid of the alert messages while debug applications.

How to excute string with javascript

Simply use eval().

eval('peformAction()') will execute

Javascript: How to check if the variable is a number?

There are some ways for doing this but I think the following is the most easiest and convenient for use:

if (! isNaN(variable)) {
//code here
}


isNaN comes from is Not A Number and can be used for understanding if the variable is a number.

Javascript string functions

Let's see how to use replace() function for replacing string with another one. The specialty here is the usage of regular expressions to replace the string if it occurs more than once in the source string.

replace('aa','a'); is gonna replace only the first occurrence of the 'aa'.
replace(/aa/g, 'a') will replace all occurrences of the 'aa' string.
replace(/A/i, 'b') will replace the occurrences of 'A' or 'a' with 'b' - case insensitive.

Very common problems are the special character replacement. These characters should be escaped using \.

replace(/\./g, '') will replace all occurrences . with an empty ('') string.

Javascript: How to cancel leaving page without saving

Preparing the javascript:
string jscript = "var needToSave= false;" +
"window.onbeforeunload = confirmExit;" +
"function confirmExit(){" +
"if (needToSave){" +
"return 'Are you sure you want to leave the page without saving?';" +
"}" +
"}";

Registering the script - safe for ajax:

ScriptManager smgr = ScriptManager.GetCurrent(Page);
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "", false);

On every field that changes the data and requires saving put:
control.Attributes.Add("onkeydown","javascript: needToSave=true;")

on the button that make save postback add:
control.Attributes.Add("onclick","javascript: needToSave=false;")

Script Callbacks in ASP.NET

I am sure that every web developers hates page refresh. And everyone chases the way to make its page more interactive without postback. The best way is client side scripting, but it is not enough to generate all page activity. Javascript based technologies like callbacks and AJAX are at the bottom of the effcicient developer's code.
Here are some good posts for callback technology in ASP.NET 2.0.

http://msdn.microsoft.com/msdnmag/issues/04/08/cuttingedge/

http://www.developer.com/net/asp/article.php/3485991

http://www.mredkj.com/vbnet/scriptCallback.html


At the core, ASP.NET script callbacks consist of some client-side JavaScript code needed for asynchronous communication to the server. The first requirement for using the callbacks is that some server-side code awaits client calls. The client-side callback intermediary manages the call while the user continues to see the old page and interact with it.


Checking for existing Javascript variable

Somethemes it is necessary to know if the variable is already defined. For example when postback methods which register client script block are used.

function isSet( v )
{
return( typeof( v ) != 'undefined' );
}

Fire Default button on enter on an Asp.NET page

I found two ways to get this to work. By Default the first button in the form is the default button. When you push Enter an fire event of this button occur. Current solution is enough to get Login control on asp.net form to work. Here is the code:


Dim ctl As Control = Login1.FindControl("LoginLinkButton")
If Not (ctl Is Nothing) Then
Login1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) {__doPostBack('" + ctl.UniqueID + "',''); return false;}")
End If

Fix: return false will break the firing of other buttons. Just to ensure right behaviour.

It works fine for all browsers.
There is one more way to do this but unfortinately it doesn't work with firefox.

Login1.Attributes.Add("onkeypress", String.Format("javascript:return WebForm_FireDefaultButton(event, '{0}')", ctl.ClientID))

How to get window size and scroll by javascript

Here is a nice explanation of the browser incompatibility with getting window size:
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}

It works fine for all browsers.

Postback in ASP.NET

This post is a short explanation of the postback "magic" used in asp.net. Check this out.
If you have to change data in a popup and also this information have to be changed in the parent page you can use window.openere.document.__doPostBack('',''); to do postback on the parent page and refresh the information there. The event target id can be passed by session variable or page parameter to the popup. The actual actions in the popup are these:

window.close();
var theform = window.opener.document.aspnetForm;
theform.__EVENTTARGET.value = id
theform.__EVENTARGUMENT.value = '';
theform.submit();

Using javascript for managing asp:ListBox, Add/Remove ListItem

Here is a wonderful tutorial about using javascript with "select" html control:

http://www.mredkj.com/tutorials/tutorial_mixed2b.html

There are also related javascript tutorials. Here is presented the javascript and html code for managing select control. The asp:ListBox is wrapped select control with additional functionality. There is no problem to use select control in your code instead this one. I personally prefer using asp:ListBox:


<asp:ListBox ID="lstItems" runat="server" DataSourceID="ODSItems" DataTextField="Name" DataValueField="Id" Width="170px"></asp:ListBox>

<asp:Button ID="btnAddItem" runat="server" Text=">" />


<br />

<asp:Button ID="btnRemoveItem" runat="server" Text="<" />
<asp:ListBox ID="SelectedItems" runat="server" Width="170px">
<asp:ListItem Value="all" Text="All"></asp:ListItem>
</asp:ListBox>


In the Page.Load Event you have to add the followed code:

btnAddItem.Attributes.Add("onclick", "javascript:moveOptions('" + lstItems.ClientID + "','" + SelectedItems.ClientID + "');return false;") btnRemoveItem.Attributes.Add("onclick", "javascript:moveOptions('" + SelectedItems.ClientID + "','" + lstItems.ClientID + "');return false;")

I have added additional functionality for one more option field: all items. And also this code is optimized for asp pages - see the client id-s handling. This is the new javascript code:


var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

function addOption(theSel, theText, theValue)
{
var newOpt = new Option(theText, theValue);
var selLength = theSel.length;
theSel.options[selLength] = newOpt;


// Removing the option with all value
var selLength = theSel.length;
var i;
if (selLength>1) {
for(i=selLength-1; i>=0; i--)
{
if (theSel.options[i].value=="all"){
deleteOption(theSel, i);
}
}
}
}

function deleteOption(theSel, theIndex)
{


var selLength = theSel.length;
if(selLength>0)
{
theSel.options[theIndex] = null;
}



//adding all
if (theSel.length==0){
addOption(theSel, "Всички","all");
}

}

function moveOptions(theSelFromId, theSelToId)
{

theSelFrom=document.getElementById(theSelFromId);
theSelTo=document.getElementById(theSelToId);

var selLength = theSelFrom.length;
var selectedText = new Array();
var selectedValues = new Array();
var selectedCount = 0;

var i;

// Find the selected Options in reverse order
// and delete them from the 'from' Select.
for(i=selLength-1; i>=0; i--)
{
if(theSelFrom.options[i].selected)
{
if (theSelFrom.options[i].value=="all"){
return;
}
selectedText[selectedCount] = theSelFrom.options[i].text;
selectedValues[selectedCount] = theSelFrom.options[i].value;
deleteOption(theSelFrom, i);
selectedCount++;
}
}

// Add the selected text/values in reverse order.
// This will add the Options to the 'to' Select
// in the same order as they were in the 'from' Select.
for(i=selectedCount-1; i>=0; i--)
{
addOption(theSelTo, selectedText[i], selectedValues[i]);
}

if(NS4) history.go(0);
}