Tag Archives: javascript

The Benefits to Learning JavaScript

Whether you’re seasoned or new to programming, JavaScript is an essential language to have under your belt. Its “write once and run anywhere” mechanics allow users with different programming systems to easily run this language, creating an interface that’s easy for many to use.

Most commonly seen on e-commerce based system or universities who require a programming language that can span different spoken language and be run on any computer system, JavaScript is quickly becoming the necessity to learn for any office or business that seeks to thrive.

But what other benefits exist for you? What can it give you?

1. Networking capabilities

Considered to be network-centric to many, JavaScript makes it easy to work with others across networks and or create platform that easily fit into the perimeters given

2. Performance

JavaScript runs in byte codes, as opposed to native-machine-language commands…this means that Java can work faster to translate its codes rather than working to translate an exclusive language

3. Organized

JavaScript runs its system based on coordinated object-oriented units, known as: classes. These classes are stored away into appropriate files and only called out by the system when they are needed…which improves the speed and efficiency of running time

4. International Use

Unlike other programming languages that run on 8-bit characters that only work with Western spoken languages, Java uses a 16-bit character system that can translate to languages used all across the world.

Don’t hesitate to teach yourself something that could extend the reach of your business, or increase the current efficiency of your product’s running systems. Take the time to learn this language now, and save tons of time, and translation troubles from finding you later.

Thumbnail for 637

 

 

JavaScript 1.8 tutorial video: Objects — Working with Windows

Expert Instructor: Don Kiely

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

What are the Most In-Demand Programming Languages?

url3If you’re a programmer, sometimes it’s a good idea to occasionally read up on job reports that illustrate the most popular languages on the job market. Doing so accomplishes two things. One, it allows you to keep place with your fellow programmer peers; and two, it may make you consider a change in your area of as proficiency. C#, for example, is in demand, and as a result, you may consider a C# video tutorial to help get you up to speed.

That said, don’t take these reports as the entire gospel truth. For example, look at where the data is collected. Some studies, for example, look at programming job openings on Twitter. This is all well and good, but as this article notes, Twitter is disproportionately used by start-ups. In other words, blue chip companies post their programming jobs elsewhere, which can skew the results.

This reality underscores the importance of knowing where you want to be. If you’re aiming for a start-up, then you probably won’t be surprised if like-minded surveys tout JavaScript. But if you’re angling for a blue chip company, languages like .NET are likely in greater demand.

Thumbnail for 637

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

Soften Your Look with jQuery

As mentioned in a previous blog post, Microsoft made two commitments when it decided to embrace jQuery as its one and only client-side JavaScript library. First, they were going to replace their Ajax Library with jQuery in every appropriate ASP.NET Web technology, including both Web Forms and MVC applications. Second, they would contribute plugins and other extensions to the jQuery Library, primarily by adapting their work on enhancements for the Ajax Library to the jQuery Library. These contributions might end up in the core jQuery Library, as official jQuery extensions, or, as a last resort, freely distributed, open source extensions.

In this article, we’ll discuss one such extension.

Creating Rounded Corners

rounded corners in AJAX

Putting rounded corners on elements is a desirable feature to soften the look of a Web page. But it is surprisingly hard to do well across all browsers, both because there are so many ways to accomplish the effect and so many variations among browsers. Web designers have long resorted to using images, even though CSS and other Web technologies support rounded corners. ACT has a nice RoundedCorners extender that applies the effect to HTML elements, letting you vary the appearance by changing the radius of the corner, which corners are rounded, and other options, giving a lot of flexibility for creating a nice page appearance. The Figure below shows the RoundedCorners extender demo from the ACT sample pages, with options set to round the upper right and lower left corners of the image.

Rounded corners seems to have been an area of particular creativity for jQuery plugin developers, probably because of the cross-browser issues and the lack of a single right way to achieve the effect. The result is a lot of plugins that let you get as creative as you want. We chose one of the simpler plugins to use on the Toolkit page, shown in the Figure below. The first box is a plain, square div element and the second has rounded bottom left and upper right corners using the Cornerz plugin for “bullet proof corners.” The plugin has a few options such as to set the border and background color, set the radius, and select which corners to round. But overall it is a pretty simple plugin that does its job quite well.

rounding the corners of a div element

The page uses the following HTML code for the Rounded Corners section. It is very simple markup, using a couple of div elements that each contain a p and cite elements.

The page uses a twain class to style the div elements, setting padding and the background color. Padding is important for most rounded corner plugins, providing room around the text to round the corner. You could have a border of a different color—as is commented out in the style below—and the border would be rounded as well.

Then the page includes a single JavaScript statement to round the corners, shown in the following code. It calls the cornerz method, passing two optional arguments. fixIE attempts to overcome a problem with some inline elements in Internet Explorer due to a wrong reporting of width, and the second specifies that only the top right (tr) and bottom left (bl) corners should be rounded.


ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

jQuery Plugins, Easy as 1,2,3

114-jquery-plugin

Despite the usefulness and comprehensiveness of jQuery, it doesn’t do everything it could to make your JavaScript coding life simpler. Frankly, you wouldn’t want it to do everything! It doesn’t even pretend to be comprehensive, if only because that would make the size of the core library enormous. The bigger the library is, the less likely that it will see wide use because it would have such a big impact on Web page performance and bandwidth, even if the browser effectively caches the library after its first use.

That’s why jQuery includes rich support for extensibility. You can create your own plugins, utility methods, and other features that closely integrate with jQuery itself. If jQuery doesn’t do something you need, or doesn’t do it exactly as you need, always start by doing a search for jQuery extensions online to see if anyone else has already solved the problem. If not, you can write your own extension and use it in your Web pages, and share it with the world if you’re so inclined. It is not very hard to write jQuery plugins.

Plugin Conventions

The jQuery community has created an enormous number of jQuery plugins, and over the last few years a few general guidelines for plugin development have emerged. You should always strive to follow these guidelines, because by doing so your plugins will integrate into jQuery effectively and will have the look and feel of jQuery, making your plugins easier to use.

  • Always name your plugin file using the format jquery.myPluginName[-version].js. The major and minor version numbers are optional, but by using this format for your plugins you follow the general convention, make it easy to find your plugin in a set of script files, and reduce the chance that you have name collisions.
  • Choose the name for your plugin carefully. If it becomes popular, you’ll not want to share a name with other plugins. Some authors include a subprefix after “jquery” in the name. So, if AppDev were to begin producing and sharing jQuery plugins, we might name our files jquery.appdev.myPluginName[-version].js. That would reduce the chance of filename collisions. And name the plugin method carefully to avoid collisions with other jQuery methods and plugins others may use in their Web pages.
  • Plugins can either return a scalar value or the matched set so that you can chain jQuery methods together. If it makes sense for the plugin, you should always return this to support chaining.
  • Always write your plugin so that it is usable with both the full jQuery method name and its $ alias.
  • Avoid a long list of arguments for your plugin. It’s fine to allow lots of options, almost mandatory, but limit yourself to a small number of arguments and make one of them options, through which the user can pass multiple values. This will mimic how most jQuery Library methods work.

It would be well worth your time exploring various popular jQuery plugins available and learn the best practices and conventions that other developers are using. Even if you don’t share your plugins with the world, you can and should take advantage of the things that other people have found that work.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

jQuery: Sticking to Commitments

Microsoft made two commitments when it decided to embrace jQuery as its one and only client-side JavaScript library. First, they were going to replace their Ajax Library with jQuery in every appropriate ASP.NET Web technology, including both Web Forms and MVC applications. Second, they would contribute plugins and other extensions to the jQuery Library, primarily by adapting their work on enhancements for the Ajax Library to the jQuery Library. These contributions might end up in the core jQuery Library, as official jQuery extensions, or, as a last resort, freely distributed, open source extensions. We discuss one such extension, watermarking, below.

Watermarking

Watermarking is a cool, useful, and interactive way to prompt a user for the information that should go into a text box on a form. When the input element is empty, the watermark text appears, usually grayed out. When the user enters the field, the watermark text disappears and whatever the user types appears in the field. You can determine the styling of the watermarked element both when the watermark text appears and when the user text appears.

The Ajax Control Toolkit has a nice TextBoxWatermark extender that you can attach to a server-side ASP.NET TextBox control. Figure 1 shows the TextBoxWatermark demo from the ACT sample pages.

url

Figure 1. The ACT TextBoxWatermark demo.

There are many watermark jQuery plugins, but one of the simplest and easiest to use is the TinyWatermark jQuery plugin. You can use it with any input or text area element by specifying the watermark CSS class and the text you want to display when the input element is empty. You have the option of supplying the watermark text either as the value of the title attribute of the element or as the second argument to the watermark method. When the user submits the form, the plugin removes the watermark text. The jquery.tinywatermark- 3.1.0.js plugin file is a mere 623 bytes, and that’s not even minified or compressed.

Figure 2 shows watermarking in the sample page. The user has moved to the first text box and entered text, so the watermark text is removed and the text box has its default appearance. The other two text boxes show the watermark text and styling.

Screen Shot 2012-10-19 at 9.28.36 AM

Figure 2. Watermarking in action in the sample page.

The following HTML creates the three text boxes on this part of the page. Notice that the first two text boxes have a title attribute with the watermark text, while the third will have the text set programmatically. The first two are assigned the watermarked class as the means to identify them to the plugin that they are to have watermarked text inserted. The last one is assigned to the watermarkedAlt class to let the code treat it differently, as you’ll see in a moment.

 

The plugin uses the following CSS style to change the appearance of the elements that are watermarked. It merely sets the background color to #FFFF99, which is officially Pale Canary Yellow, and changes the font color to a medium gray.

 

The crux of the watermarking code is the following two statements, contained within the jQuery ready method so they’ll fire only after the page’s DOM is loaded in memory. The first statement watermarks the name and email text boxes on the page, using the title attribute’s value as the watermark text. The second statement watermarks the third text box, providing the watermark text as the second argument to the method. Both statements tell the watermark method to use the watermark CSS style to display the input element and watermark text.

We usually find that the first form of the watermark statement, using the title attribute for the watermark text, to be more useful and practical when there are more than a couple of elements on the page you want to watermark. That way the watermark text is with the element rather than separated in the page’s script code. But you’re free to use whatever form works best for you.

You can use whatever class name you want to identify the input elements to be watermarked, as well as the name of the CSS style used to format the elements with watermark text. The plugin is surprisingly functional for such a small size!

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.

Property Access Expressions in JavaScript

Thumbnail for 684

Expressions are the building blocks of JavaScript code, the mechanism you can use to manipulate data and change the state of an application. They are snippets of code that the JavaScript interpreter can evaluate to produce a value, and can be as simple as a literal value or as complex as a complicated arithmetic process that combines multiple values using a variety of operators to perform various operations on the data.

JavaScript provides a rich set of expressions that you can use to build an application with, and a robust set of operators you can use in many kinds of expressions. In this article we’ll take a look at Property Access Expressions.

Property Access Expressions

A property access expression provides access to the value of an object property or the value of an array element. JavaScript has two syntaxes for these expressions, as shown in the following code. You can use either syntax to access the value of an object property and just the second, using square brackets, to access an element of an array.

Using either type of access expression, JavaScript follows a general process for evaluating the overall property access expression. Keep in mind that an object in JavaScript is essentially a collection of name/value pairs.

  1. It first evaluates the expression before the . or [. If the value is null or undefined, it throws a type error because those values don’t have properties.
  2. If the value is not an object or array, JavaScript converts the value.
  3. If the expression uses the . notation with an identifier, JavaScript retrieves the value of that property from the object, which becomes the value of the overall expression. If the property doesn’t exist, the value is undefined.
  4. If the expression uses the [] notation, JavaScript evaluates the expression within the brackets and converts the value to a string, then reads that property from the object or element from the array. It again returns undefined if the property or array doesn’t exist.

The following code demonstrates a few variations of these property access expressions. It starts by defining an object with top, left, bottom, and right properties, then an array with numeric elements and the obj object. The first two console.log statements access the left property of the object using both types of access expression syntaxes. The third line emphasizes that what is contained between the square brackets is an expression, so JavaScript has to evaluate the expression and concatenate the letters of “left” before it can access the property. The next line accesses array element 2 (the third element in the zero-based array index) of the array. The final statement makes JavaScript evaluate the expression in the square brackets to determine which array element to access, which is the obj object, then accesses its left property. This last statement shows that you can mix the two syntaxes in a single expression. Figure 15 shows the results.

Figure 15. The results of property access expressions.

Get more JavaScript training Today!


Variable Cautions and Gotchas in JavaScript

Thumbnail for 688

When it comes to JavaScript, there are a few variable cautions and gotchas to be aware of.

Keep in mind that although the value stored in a JavaScript variable is strongly typed—a string, number, Boolean, or object—the variable can hold any type during program execution. There is no type defined as part of the declaration. So the following code, although convoluted and probably confusing to maintain, is perfectly legitimate. Don’t do this! Use each variable for a single purpose to make your code clearer and give it a name related to that purpose. In general, you should use each variable for a single type, even though JavaScript doesn’t enforce this.

Be careful when splitting a var statement across multiple lines! If you accidentally omit any commas, all of the subsequent variables will be declared as global variables, which pollutes the global namespace and causes hard to find bugs. So, for example, if you omitted the comma after the count variable is declared and initialized, as in the following code, JavaScript injects a semicolon at the end of the first line and the minMsgID and lastName variables will be global variables. (The indenting makes no difference to JavaScript.) This problem is avoided if you have the entire var statement on a single line in the code file or declare each variable in its own statement with the var keyword.

TIP: In ECMAScript 5/Strict mode, it is an error to assign a value to an undeclared variable. But in older versions of the standard, and in ECMAScript 5/Default mode, the variable is declared as a property of the global object as described above.

It is legal and generally harmless to declare a variable more than once with the var statement, although it takes extra typing and clutters up your code. If a later, redundant var statement also initializes the variable, it acts as a simple assignment statement. No matter how many times you declare a variable within its scope, you’ll have only a single instance of the variable.

Get more JavaScript training Today!

Object Comparisons in JavaScript

figure-21-comparing-objects

In our last article, we discussed Escape Sequences in String Literals and their use in JavaScript. In this article, we’ll take a deeper dive into JavaScript and look at the use of object comparisons.

Object Comparisons

Unlike primitive values, JavaScript compares objects by reference. This means that two object variables are equal only if the two variables hold a reference to the same object in memory. If the two variables hold a reference to two different objects in memory, even if the objects are the exact same—have the same properties, in the same order, all with the same values—the object variables are not the same.

Some code will show how this works. It starts by creating two objects in memory, obj1 and obj2, each with an identical set of properties each set to the same value. The first comparison checks to see if these objects are equal, which they are not. Then the code creates another object variable, obj3, and sets it to reference obj1. This time, because obj1 and obj3 both hold a reference to the same object in memory, the comparison is true. You can see these results in Figure 21.

Figure 21. Comparing Objects.

Next the code changes a value in obj1, setting its t property to 10. The code then displays the value of t for each of the three object variables and once again tests to see if obj1 is equal to obj3. You can see the results in Figure 22, which shows that t in obj1 and obj3 are still equal, but obj2 is unchanged because it is an entirely different object.

figure 22 changing value of an object with two references
Figure 22. Changing the value of an object with two references.

If you want to make a copy of an object in memory, rather than having two variables that reference the same object in memory, you have to write the code to do it. The following code shows two ways to copy an object. The first is a brute force way to do it, creating an empty object that will be the copy, and writing code to copy the value of each property from obj1 to obj4. The second way uses some nice features of JavaScript objects to loop through the objects’ property collection and the [] notation to reference object properties instead of the dot (.) notation.

WARNING! This is not robust code for copying objects in memory. It copies only one level of properties—you can have object properties in addition to primitive values—and will copy a base object’s properties as well, if any. There are ways to robustly copy objects in JavaScript, but that will have to wait until you learn more about JavaScript objects. Figure 23 shows the results displayed in the Console panel.

figure 23 results of creating two new duplicate objects in memory
Figure 23. The results of creating two new duplicate objects in memory.

If you want to inspect either obj4 or obj5, you can switch to the Scripts panel and put a breakpoint on the last line of code, the final console.log statement, and refresh the page. Then hover the mouse over either obj4 or obj5 to see its properties and values, as shown in Figure 24. As you can see, the properties of obj5 are identical to those in obj1 (remember that the code earlier changed it to 10).

figure 24 inspecting properties of an object in scripts panel
Figure 24. Inspecting the properties of an object in the Scripts panel.

TIP: When you first go to the Scripts panel, it may not have the JavaScript code
from the page loaded. Just refresh the page, and the panel should display the
code.

Get more JavaScript training Today!

Escape Sequences in String Literals Using JavaScript

Thumbnail for 692

One of the fundamental tasks handled by programming languages is to temporarily store and manipulate bits of data in memory, mostly strings and numbers, but often also dates and other special data types, called values. One of the defining characteristics of a programming language is the data types it supports and the features it has for working with those types. A language’s types define the kinds of values you can represent and work with. When you need to save a value for later use in the program, you can define a variable and store the value in it. A variable is a symbolic name for the value that you store in memory, and lets you refer to the value by name and, over the course of program execution, assign different values to the same variable.

Following is an explanation of Escape Sequences in String Literals and their use in JavaScript.

Escape Sequences in String Literals

When you need to include any of a number of characters that have special meaning within a string literal, you can create an escape sequence using a backslash to identify the special character. For example, if you absolutely must include the type of quote used as a string delimiter within the string, you can create an escape sequence as in the following string literal. By making it an escape sequence, the single quote will appear within the string, even though that is also the string delimiter.

The reason why this is called an escape sequence is that the backslash causes an escape from the usual interpretation of the single quote character in the previous example. Table 2 lists the available JavaScript escape sequences.

If you include the backslash in front of any other character than those shown in Table 2, JavaScript will ignore the backslash, such as if you include * in a string literal. This is risky however, because future versions of JavaScript could define new escape sequences that would give meaning to the sequence in your code. As unlikely as that may seem, it’s best to avoid the possibility of broken code in the future.

The following code demonstrates some of these escape sequences. Some lines are broken in random places to fit on the page, but each console.log statement should appear on a single line in a code file. Figure 3 shows the results in the Console panel.

Ch02_blog

Figure 3. The results in the Console panel of running sample escape sequence code.


Get more JavaScript training Today!