What is Variable Hoisting in JavaScript?

Consider the following code:

1
2
var sheldon = 'bazinga!';
alert(sheldon); // bazinga!

Okay, of course the alert will display “bazinga!.” That’s obvious; however, stick with me.

Let’s next create an immediate function, which alerts the same value.

1
2
3
4
5
var sheldon = 'bazinga!';
 
(function() {
  alert(sheldon); // bazinga!
})();

All right, all right. Still obvious, I know. Now, let’s throw a wrench into the mix, and create a local variable within this anonymous function of the same name.

1
2
3
4
5
6
  var sheldon = 'bazinga!';
 
(function() {
  alert(sheldon); // undefined
  var sheldon = 'local bazinga!';
})();

Huh? Why is the alert now displaying undefined? Even though we’ve declared a new variable, it’s still below the alert; so it shouldn’t have an effect, right? Wrong.

Variable Declarations are Hoisted

Within its current scope, regardless of where a variable is declared, it will be, behind the scenes, hoisted to the top. However, only the declaration will be hoisted. If the variable is also initialized, the current value, at the top of the scope, will initially be set to undefined.

Okay, let’s decipher the difference between the terms, declaration andinitialization. Assume the following line: var joe = 'plumber';

Declaration
1
var joe; // the declaration
Initialization
1
joe = 'plumber'; // the initialization

Now that we understand the terminology, we can more easily comprehend what’s happening under the hood. Consider the following bogus function.

1
2
3
4
5
6
7
8
(function() {
  var a = 'a';
  // lines of code
  var b = 'b';
  // more lines of code
  var c= 'c'; // antipattern
  // final lines of scripting
})();

Declare all variables at the top.

Note that what’s exemplified above is considered to be bad practice. Nonetheless, behind the scenes, all of those variable declarations — regardless of where they occur in the function scope — will be hoisted to the top, like so:

1
2
3
4
5
6
7
8
9
(function() {
  var a, b, c; // variables declared
  a = 'a';
  // lines of code
  b = 'b'; // initialized
  // more lines of code
  c= 'c'; // initialized
  // final lines of scripting
})();

Aha Moment

If we now return to the original confusing undefined piece of code, from above:

1
2
3
4
5
6
var sheldon = 'bazinga!';
 
(function() {
  alert(sheldon); // undefined
  var sheldon = 'local bazinga!';
})();

It should now make perfect sense why sheldon is alerting undefined. As we learned, as soon as the local variable, sheldon, was declared, it was automatically hoisted to the top of the function scope…above the alert. As a result, the variable had already been declared at the time of the alert; however, because initializations aren’t hoisted as well, the value of the variable is: undefined.

Summary

To put in simple words, function declarations and variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter. This means that code like this:


function foo() {
bar();
var x = 1;
}

is actually interpreted like this:

function foo() {
var x;
bar();
x = 1;
}

Centering an Absolutely Positioned Element Using CSS

Centering an absolutely positioned element is a CSS challenge that I have always struggled with. I always find myself googling for the solution every now and then.

Today I came across this great article for exactly this problem and decided to share it with everybody and document it on my blog for easy referencing later!

Horizontally centering a static element in CSS is normally handled by setting the left and right margins to auto, for example:

#myelement
{
	margin: 0 auto;
}

However, this won’t work on an absolutely positioned element. Its location is determined in relation to the most immediate parent element that has a position of absolute, relative, or fixed.

In the following example, the relative red square has a width set to 40% of the available space. The top-left of the absolutely positioned blue square is positioned 30px across and 10px down:

#outer
{
	position: relative;
	width: 40%;
	height: 120px;
	margin: 20px auto;
	border: 2px solid #c00;
}  

#inner
{
	position: absolute;
	width: 100px;
	height: 100px;
	top: 10px;
	left: 30px;
	background-color: #00c;
}

If we’re unconcerned about the exact dimensions of our blue box, we could omit the width setting and set the same left and right values. This would effectively center our blue box:

#outer
{
	position: relative;
	width: 40%;
	height: 120px;
	margin: 20px auto;
	border: 2px solid #c00;
}  

#inner
{
	position: absolute;
	height: 100px;
	top: 10px;
	left: 30px;
	right: 30px;
	background-color: #00c;
}

So, how can we center our box if it has fixed dimensions? The answer requires a little lateral thinking:

  1. First, we use left: 50%. Unlike background image positions, this will move the left-hand edge of the blue box to the center.
  2. Since our box is too far to the right, we use a negative left margin that’s half its width. In our example, we must set margin-left to -50px to shift the box back to the right place:
#outer
{
	position: relative;
	width: 40%;
	height: 120px;
	margin: 20px auto;
	border: 2px solid #c00;
}  

#inner
{
	position: absolute;
	height: 100px;
        width: 100px;
	top: 10px;
	left: 50%;
	margin-left: -50px;
	background-color: #00c;
}

The blue box will remain centered no matter how the width of the outer element changes!

Via: SitePoint

Preventing Injection Attacks in ASP.NET

Script injection attacks occur when a hacker takes a few lines of malicious programming code and enters it in to a form on our Website and then submits the form. If the Website is data driven then chances of risk is more on the Website. Hackers will often inject scripts in to our forms to try and make the system fooled in to thinking that they are valid users in order to delete data or change data or access data from database.

The basic technique for a script injection attack is for the client to submit content with embedded scripting tags. These scripting tags can include <script>, <object>, <applet>, and . Although the application can specifically check for these tags and use HTML encoding to replace the tags with harmless HTML entities, that basic validation often is not performed.

The following commonly used HTML tags (not an exhaustive list), could allow a malicious user to inject script code:

<applet>
<body>
<embed>
<frame>
<script>
<frameset>
<html>
<iframe>
<img>
<style>
<layer>
<link>
<ilayer>
<meta>
<object> 

>

An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting.

Request Validation

Script injection attacks are a concern for all web developers, whether they are using ASP.NET, ASP, or any other web development technologies. ASP.NET includes a feature designed to automatically combat script injection attacks, known as request validation. Request validation checks the posted form input and raises an error if any potentially malicious tags ( such as <script> ) are found. In fact, request validation disallows any nonnumeric tags, including HTML tags (such as <b> and <img>), and tags that do not correspond to anything (such as <xyz>).

To test the script validation features, we can create a simple web page like the one shown below.

If we try to enter a block of content with a script tag and then click the button, ASP.NET will detect the potentially dangerous value and generate an error.


Disabling Request Validation

There may be such a situation where users have a genuine need to specify HTML tags (for example, an advertisement purpose) or a block of XML data. In these situations we need to specifically disable script validation using the ValidateRequest Page directive, as shown below.

<%@ Page ValidateRequest="false" Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

We can also disable request validation for an entire web application by modifying the web.config file. We need to add or set the validateRequest attribute of the <pages> element, as shown here.

<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
      <pages validateRequest="false"/>
    </system.web>
</configuration>

The following screenshot is showing what will happen when a user clicks on the submit button.

  protected void btnSubmit_Click(object sender, EventArgs e)
  {
      Response.Write(txtInput.Text);
  }

Encode Output

Use the HttpUtility.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases. HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with < and ” is replaced with “. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.

To prevent a script injection attack from happening when request validation is turned off, we need to explicitly encode the content before we display it using the Server object.

protected void btnSubmit_Click(object sender, EventArgs e)
{
  Response.Write("Entered Input is: "+Server.HtmlEncode(txtInput.Text));
}

The following screenshot is showing the output of the above mentioned code.

It is clear that script injection is a big concern to the developers and to protect our pages from the hand of hackers we should not consider only request validation, but also should not forget to use HtmlEncode wherever applicable. It should be noted that we can disable request validation on a page-b, we should use proper numeric validation, range validation and avoiding some characters such as “*”, “%”, “@”, or “!” in order to prevent script injection.

Further reading:

How To: Protect From Injection Attacks in ASP.NET

FancyUpload – AJAX Uploader with Progress Bar

FancyUpload is a file-input replacement which features an unobtrusive, multiple-file selection menu and queued upload with an animated progress bar.

It is easy to setup, is server independent, completely styleable via CSS and XHTML and uses MooTools to work in all modern browsers.

It is fully compatible with all A-Grade Browsers (Internet Explorer 6+, Opera 9, Firefox 1.5+ and Safari 2+)

Features

  • Select and upload multiple files
  • Filter files by type in the select dialog
  • Optional Events to add your own behaviour
  • Show and filter useful file information before the upload starts
  • Limit uploads by file count and/or file size
  • Platform and server independent, just needs Flash 8+ (> 95% penetration)
  • Unobtrusive, since the element is replaced after the swf loaded successfully
  • Cancel running uploads, add files during upload
  • Everything is optional, documented and easy editable

[ Demo ] [ Website ]

ASP.NET Control : Warning the User when Caps Lock is On

Many of the websites (e.g. Online Banking websites) have a secure area which is only accessible to the user after he provides correct Username/Password. Some of them have case-sensitive passwords.

If a user is not aware (while entering the password) whether his CAPS lock key is ON then his login will fail as the password is case-sensitive.

This is one of the features in Windows based applications that was lacking in Web based application. You all might have noticed it while logging in Windows XP/Windows Server 2003, that a “Speak-out” bubble is displayed with a message that “CAPS Lock is On” while entering the password if the CAPS lock is On.

This feature was highly desired in Web Applications until today when i came across a nice article at 4GuysFromRolla about an ASP.NET control which provides the exact functionality.

Scott Mitchell has explained the working of this control in detail in this article.

Here is the link to the article: [ Warning the User when Caps Lock is On ]

Animated GIF bug in Internet Explorer 7

Today I attempted to get a progress indicator to work in IE7. My idea was that I’d have an animated GIF on a page, hidden with style=”display: none;”. Then, in the onclick event I’d toggle it visible again using JavaScript, so that the progress indicator would animate as the page was submitted and the next page was loading.

Surprise, surprise, it didn’t work. IE simply refused to animate the GIF when the form was submitted. I googled and googled with no avail – until I ran into a simple and working solution. I won’t present the non-working ones here, they can be found with any relevant keywords.

The working one is the following in its entirety: Use a div to display the indicator as a background image. In addition to toggling display, also toggle visibilty.

In my HTML, I have two divs, one with an id of Indicator, and in it another one with id image and some text. The JavaScript goes as follows.

1. First, in the function called from the onload event of body I hide the outer div:

document.getElementById(‘Indicator’).style.display = ‘none’;

document.getElementById(‘Indicator’).style.visibility = ‘hidden’;

2. Then, in the function called from the onsubmit event of the button input in the form, I show the outer div and set the background image for the inner one:

document.getElementById(‘Indicator’).style.display = ‘block’;

document.getElementById(‘Indicator’).style.visibility = ‘visible’;

document.getElementById(‘image’).style.backgroundImage = ‘url(indicator.gif)’;

That’s it!

I have tested this in IE7, but it might also work in IE6.