JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.

Share tech news, updates, or what's on your mind.

Sign up to Post

Introduction


Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).  

The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least complicated way as possible.

There are also other frameworks that essentially do the same thing in their own way. Find what works for you. React is what Facebook is built on and is very popular. AngularJS has also gained a lot of momentum and worth checking out.

Knockout takes a basic HTML structure and applies logic (written by you) to control the insertion and removal of HTML elements. This keeps the markup simple and straightforward, especially when it comes to repetitive content.

It's incredibly easy with Knockout to create dynamic interactive web pages with simplified markup. I've seen markup get out of control when creating content both from the server side (e.g. using PHP) or via the client side (e.g. using jQuery), making it virtually impossible to troubleshoot issues with layout and styling. 

I come across many questions in the web dev topic areas that are related to issues with the asker's website. Invariably this starts with them being told to fix their markup and validate it through the The World Wide Web Consortium's (W3C) Validation service.  When a site doesn't validate, it is not guaranteed to work on all …
1
LVL 3

Expert Comment

by:mmoore
Really interesting stuff! So many technologies so little time.
A couple of typos you may wish to correct. "It incredibly easy" "know no only".
0
LVL 44

Author Comment

by:Rob
Thanks @mmoore :)
0
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
1
LVL 32

Author Comment

by:Marco Gasi
Well, I'm happy. But I've just realized that today is still May: will this article partecipate to the contest for the Blade-Runner HD?
0

What is Node.js?

Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event driven, which throws a whole new light on the way a server side app performs. As Node.js is the complete package (web HTTP server and server side language), there is dramatically less overhead in implementing it as a webserver when compared with a typical Apache (and PHP) or IIS (with ASP/PHP) installation.

Node.js is written in JavaScript, the most common client-side language around. This reduces the learning curve somewhat for most web developers as they understand JavaScript and how to code it.
 

Why is it Important and what are the Benefits?

Most of the server side languages I’ve used are built on sequential execution models, meaning one task has to finish before another one begins. For instance, PHP (in conjunction with the type of server it is running off e.g. Apache) will spawn a thread for each request made to the server. If that thread needs to get data from a database that takes a while or another request comes in, that thread is locked up and consuming resources. For a data intensive app with many concurrent connections, that could severly impede the server’s performance.

Node.js is single threaded (yes only one thread!) and is beneficial in applications where frequent blocking I/O requests
9

Introduction

Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this tutorial, I have to assume that you understand basic statistics and how to interpret the data shown in the charts outlined by this tutorial. Chart.js offers the following types of Charts: Line, Bar, Radar, Polar Area, Pie and Doughnut. It is possible to create your own types of charts but one step at a time. These are the types we'll be working with in this tutorial.
 

So what do you need to do to get started?

Bookmark the documentation! http://www.chartjs.org/docs/

Either use a Content Delivery Network (CDN) OR Download the ZIP package and include it with the other files of your website.

I personally recommend to use a CDN via this script tag (version 1.0.2)

<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>

Open in new window

If you want to have the Chart.js files on your server, download the ZIP from https://github.com/nnnick/Chart.js("Download Zip" found on the right of the page or click this link https://github.com/nnnick/Chart.js/archive/master.zip (may be subject to change) Download.JPGExtract all the files from the ZIP, however the ONLY file needed is the Chart.min.js, and include it in the relative section of your site: 

<script src="/relative/path/to/Chart.min.js"></script>

Open in new window


Add jQuery

While we're at it, let's add jQuery to your page:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

Open in new window

So now your page should look like this


Open in new window

4

Note: Assumed Knowledge

To implement the bookmarklets you will need to have some basic HTML knowledge. However, if you can't work out an action you'd like to perform, post your request below or in a question on the EE site and I or another Expert will do their best to code the required bookmarklet for you.

It should also be noted that a caveat to this approach is that the JavaScript at some point will change as the site evolves so any bookmarkets mentioned in this article are subject to change :)
 

Bookmarklets

Bookmarklets are very useful and an under utilised function when it comes to browsing the web. A bookmarklet is a bookmark that runs JavaScript on the page you are reading, whereas a bookmark as you may know it takes you to a URL.

I recently saw this article by Joe Winograd that got me thinking about what it would mean to Experts and askers on the EE site. After talking with the EE Moderator eenookami who contacted me about expanding on this type of capability, I thought I would express here just what this kind can do for you when on the EE site.
 

JavaScript & jQuery

To begin with, the EE site utilises JavaScript to capture and perform actions throughout the site. When you click on a button, perform a search, post a comment etc JavaScript is executed. Essentially any action you perform on the site is controlled via JavaScript
7
In Q3 of last year, Experts Exchange introduced a new Messaging System, allowing any member to communicate directly with other members.

During an especially long thread with a member, I wanted to go back to previous messages in the exchange to refresh my memory on an issue. However, the Message System doesn't have a Search function that allows you to search the contents of all messages in a thread. But then it occurred to me that I could take advantage of the search feature in my browser, Firefox (Edit>Find or Ctrl-F). However, to do that, all of the messages would have to be expanded by clicking the plus sign next to each one:
Plus-sign---Expand.jpgThat's very painful in a long thread! So I submitted an enhancement request entitled Need the ability to expand/collapse all messages in a thread  in the Messaging System testing project. An EE Administrator, eenookami, replied to my request with a fantastic work-around — JavaScript code to expand all messages in a thread, as well as JavaScript code to collapse all of them.

In the spirit of giving credit where credit is due, all of the credit goes to eenookami for this solution. My only minor contributions are taking the time to write the article in order to share the solution with other members of the EE community and adding an explanation of how to place the Expand All and Collapse All items on the Firefox Bookmarks Toolbar
6
LVL 2

Expert Comment

by:Rob Jurd
Great Article Joe and thanks for giving me kudos however no one would know about it without taking it a step further with this article contribution.

For those interested, it is called a bookmarklet and it will work it all browsers.  For those adventurous ones, you can write your own bookmarklets to do anything on the site you would otherwise do with a click or a keypress on your keyboard.  I'll leave the examples for your imagination...

The bug report that started this is: http://support.experts-exchange.com/customer/portal/articles/1162518

Cheers,

eenookami
0
LVL 69

Author Comment

by:Joe Winograd
Hi eenookami,

Thanks for the compliment and the Helpful Vote — I appreciate both! Additional thanks for the further explanation of bookmarklet — very interesting!

Btw, the link you posted for the bug report that started this does not seem to be right, but it gave me the idea to include that link in the article, which I will do in a moment. Regards, Joe
0
This is a quick introduction to working with Grunt.

What is Grunt?

Grunt is a tool that is used to automate certain tasks for a developer, such as CSS file concatenation, minimizing images and unit testing. These tasks have traditionally been handled by developers in order to ensure a website's or application’s performance. With tools like Grunt we can automate these processes and focus on more important tasks when building software.

Prerequisite:

You will need a basic knowledge of JavaScript. You will also need to be familiar with your operating system’s command prompt. Understanding of how to navigate file structure and perform basic tasks is important to using Grunt.

How to get started?
  1. In order to get started with your own handy-dandy automation tool, go to http://nodejs.org/ and download the latest version of Nodejs.
  2. Once Node has finished installing on your machine, open your computer's 'command prompt' and type in 'npm install –g grunt-cli'. This command tells Node Package Manager (npm) to globally install (-g) Grunt's (grunt) Command Line Interface (-cli). This is basically a fancy way of telling your machine that we would like to start using Grunt.
  3. After you’ve installed the Grunt CLI globally, go to http://gruntjs.com/plugins and choose a plugin that you would like to use inside of a project. For this tutorial I will be using the plugin "uglify" at https://www.npmjs.org/package/grunt-contrib-uglify
0
Introduction and Prerequisites
This article describes methods for detecting whether a client browser accepts and returns HTTP cookies and whether the client browser runs JavaScript.  Most client browsers will, by default, be configured to use cookies and JavaScript, but some may not do that, and it may be important to your application design to be aware of these client-side factors as you build your web documents.  For example, most shopping carts rely on cookies to store a pointer to the contents of the cart.  If your client has cookies disabled, the shopping cart would not work.  Rather than simply fail, it would be a better design to be able to tell the client about the dependency.  Or you might have a gallery that used jQuery to provide an attractive client experience.  If you knew that JavaScript was disabled you would be able to adjust the gallery behavior. 

These concepts seems like common sense in application design, but the client/server relationship has a structure that hinders this common sense approach.  The order of request and response events is an important principle.  All communication is initiated by the client.  The client makes a request, the server-side scripts run, and the server-side scripts are complete before the response is sent to the browser.  As a result, any of the characteristics of the client browser that are not part of the request
1
An introduction to Chrome Dev (and QA) Tools
Have you ever been asked to investigate memory or cpu usage of your company’s web app? Have you ever been asked to investigate where your company’s web app is spending time during its loading? Google’s chrome browser comes with a rich set of tools that can be used to investigate memory usage, CPU usage, object load times, network traffic and more. This article gives a quick rundown of some of what’s available through Google’s DevTools.

The suite of tools are referred to a ‘DevTools’ but, of course, anyone can make use of them, including QA folks. Chrome version 38.0 is used for this article. Since there are different versions of the tools your tools may look different.

To get started, click on the Chrome menu. In the drop down, look for ‘More Tools’ or something with a similar name. From that drop down, click on ‘Developer Tools’. You can also use a three keystroke group of shift-control-I (capital i) (Cmd-Opt-I for Mac) to launch the tools.
chromeDev1.png 
When the tools launch, you’ll see the different options across the tools banner. The Chrome DevTools Overview does a good job of introducing the set of tools.
chromeDev2.pngA quick rundown
  • Elements: As the name implies, with this tab selected you can see the DOM tree elements. Additonally, you can drill down into the structure of the tree and you can edit elements. The Editing Styles and The Dom page gives more details.
  • Network
5
LVL 5

Author Comment

by:Marlon Pearson
Are the images showing up in the article ? I see them when I'm in the editor, but they are
missing afterwards.
0
LVL 5

Author Comment

by:Marlon Pearson
Eric, thanks for the pointer to the editing process.
0

Introduction

A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer is "You can't." This is a restriction of the HTTP client / server protocol. The only time the server can send information to the client is in response to a request.  So it follows that we need a way for the client to request a progress report and a way for the server to send the progress report.  This article sets up the two parts of the application and builds them step-by-step so you can see exactly how this can be done.  We use jQuery and AJAX in a way that allows the client script to call the server-side script and to get back an indicator of progress.


The Visual Effect in the Browser

When we first load the client web page, we will have an area reserved for the progress bar.  As progress occurs (as indicated by the signal from the server) our progress bar will become visible and move across from left to right until the process is completed.  At the end, it will say "All Done" then it will fade from view and collapse out of the web page.  Here are screen-capture examples of the visual effects.  We used very bright colors for this example; your choice of size and color would be made with your design goals in mind.  These are settable via CSS.


Before the process starts:

jquery-progress-bar-1.pngAfter the progress bar appears:

jquery-progress-bar-2.pngAs the progress bar continues to show greater and greater progress:

jquery-progress-bar-3.pngWhen the progress indicator exceeds 99%:

jquery-progress-bar-4.pngAfter "All Done!" the progress bar fades out and disappears from the page:

jquery-progress-bar-5.png

The Server-Side Script

First we will build a simulation of the server side of the two-part application.  The server will sense the progress of our long-running job and will return a single value to the client - an integer, representing the percentage of completion.  In order to simulate the progress, we will use a simple counter which we will keep in the PHP session.  By storing the counter in the session, we can add to it on each request to the server-side script, creating the same effect we might see if the server-side script were taking an actual measurement of our progress toward a goal.  Have a look at line 15.  It's only there to simulate some kind of variation in the reported progress.  In real life, this "counting" scenario would be replaced by some programmatic method of determining the percentage of progress toward our goal.  The determination, however it is made, would be set into a positive integer of range 1-99 which is echo'ed to the browser output stream (and therefore returned to the client-side jQuery script that called our progress monitor).

<?php // demo/jquery_progress_bar_server.php
                                        error_reporting(E_ALL);
                                        
                                        // SESSION ALLOWS US TO HAVE STATIC VARIABLES
                                        session_start();
                                        
                                        // IF THIS IS THE FIRST STEP, SET THE PROGRESS BAR TO ZERO
                                        if (empty($_SESSION['progress']))
                                        {
                                            $_SESSION['progress'] = 0;
                                        }
                                        
                                        // INCREMENT THE PROGRESS COUNTER
                                        $advance = 10;
                                        $advance = rand(5,10);
                                        $_SESSION['progress'] += $advance;
                                        
                                        
                                        // IF THIS IS THE LAST STEP, ELIMINATE THE SESSION VARIABLE
                                        if ($_SESSION['progress'] > 99)
                                        {
                                            unset($_SESSION['progress']);
                                            session_write_close();
                                            die('100');
                                        }
                                        
                                        // RETURN THE PROGRESS
                                        echo $_SESSION['progress'];

The Client-Side Script

Once we have the server side of the application running, it's time to build the client side (the part that runs in the client's browser).  For this we use a conventional HTML5 web page.  These notes apply to the snippet below.


Line 8: This loads the latest "minified" jQuery framework.


Line 11-13: This starts the progress bar when the document.ready event fires.  In a real-world example, this might be started by a browser event, such as a mouse click.  But for our tests, it is nice to be able to refresh the browser and see the progress bar started immediately.  The script here tells the browser to run the loadProgressBar() function, and to address it to the div named #progressBar.  In theory it would be possible to have multiple progress bars on the page, but for this demonstration, one will do.  Note that for this example to work, the document.ready event handler is not required.  I only put it into the script as a placeholder since some other event might be the initial trigger for the progress bar.


Line 16: Sets the interval value to 1,000 milliseconds (one second).  Each time the interval timer expires, the script will call the server-side script for an update on the progress.  There is no hard-and-fast rule about a one-second interval; you can choose any values that makes sense for your needs.  You might want to experiment with faster or slower values.


Line 17: Sets the interval timer to call the function loadProgressBar() every time the intval expires.


Line 22: Defines the loadProgressBar() function.  The function takes one argument called "element."  This is the name of the outer wrapper div that encapsulates the progress bar.


Line 23: Every time loadProgressBar() is run, it calls the server-side script and retrieves an integer representing the percentage of completion of the background task.  This value is assigned to the JavaScript variable percent.


Line 24-28: If the percentage indicates that the progress is not yet complete, we recompute the width of the progress bar and animate the movement of the dark green background across the bar from left to right.


Line 29-36: When the percentage indicates that progress is complete, we are finished with the progress bar.  We take the following steps.

1. We remove the interval timer -- there is no need to call this function again.

2. We remove the background color from the progress bar.

3. We set the alignment to "center" and write "All Done!" in the middle of the progress bar

4. We use jQuery fade() and hide() functionality to cause the progress bar to act like the Cheshire Cat, disappearing from view.


Line 43-47: Our CSS defines the size and color of #progressBar div.


Line 49-57: Our CSS defines the div inside the #progressBar div.  It starts with a width of zero (which grows with each call to the loadProgressBar() function) and a background-color of dark green.  With this styling and the jQuery .animate() function, we can produce the visual effect of a progress bar that slides more-or-less smoothly across the screen.

 

5

Expert Comment

by:Danillo Leão Lopes
Very good!
0
This article is about getting you to think differently about Javascript's elements.  By element I'm referring to the primative types (boolean, number, string etc) but also arrays, dates, maths, regular expressions and functions.

I've been asked recently about scope, variables and anonymous functions, where it can get quite confusing understanding the relationships and the structure of the elements.  However, just thinking about them in a different way, and to me at least, it all started to make sense.

The purpose of this article is to reduce that confusion and simplify your understanding of the fundamentals of javascript.

All elements are Objects

Every element of javascript is a copy of the Object prototype but with it's own functions and properties.  You may or may not be familar with using objects in javascript but essentially you can capture any information in virtually any way.  An andress book entry object may look like this:
var myobject = { name: "Rob", address: "33 Over St", phone: 555-3745 };

Open in new window


Now you have an object that contains those name/value pairs.  The object can be passed to a function or sent over the internet so it's a great way to capture data in one place.
But what you've actually done is copy the generic Object prototype and added your own properties, ie name, address, phone.To reiterate, the generic Object protoype is a very simple object that every other element (including primative data types) is built on.  They are a copy of the prototype with their own functions and properties.

6

Expert Comment

by:K_dot
Rob,

I copied and pasted your code as in your example.  It contained errors and I was letting you know about them.  In your example,
"You can now use this to create new objects with these properties and functions."
Here is your code:
var newPerson = person("Rob",30,"555-4255");
newPerson.getDetails(); //returns the string "Rob 30 555-4255"

Open in new window

You are not using the 'new' operator.  I am trying to learn from your examples.
0
LVL 44

Author Comment

by:Rob
K_dot,

My sincere apologies.  You most certainly should be able to learn from the examples given and something has obviously gone amiss when I've pasted it here after completeing my obviously inadequate testing.

I appreciate your input and feedback and again thank you for picking this up.

I've submitted for review.

Cheers,

Rob
0
Background
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

I've seen a lot of confusion around what JavaScript frameworks are.  Every web developer has heard of (and probably used) JavaScript but I've seen some baulk at the mention of jQuery, MooTools, bootstrap and other JavaScript frameworks.  Some of the answers I've had are that the frameworks hasn't been authorised by their IT department or do I need to install it or no we only want to use JavaScript.

The confusion has led me to write an article that hopefully clears up exactly what is meant by the term of JavaScript framework.

Overview
A framework is just JavaScript encompassed within a JavaScript class or more commonly referred to as a namespace.  The idea of a framework has come about for two main reasons:

Browser compatibility
Simplicity

If you're familiar with jQuery or MooTools, you'll know about the $ object.  That's the namespace I'm referring to and has all the framework's functions embedded within it.  

To start with, I need to cover a bit about object oriented programming (OOP) as this is the basis of all JavaScript …
7
LVL 44

Author Comment

by:Rob
Yes, I guess they've got that flexibility to operate on any XML node based document.  I haven't done much of that but would you mind for my own learning what you mean by "other contexts".  Sounds like you've used a framework outside the browser?
0

Expert Comment

by:darrell_rials
Well Rob, there really aren't that many true JS 'frameworks' used outside of a web browser context, yet. I was thinking of something like a web application framework running on, say, the the NodeJS platform -- something like Express (http://expressjs.com/), for example. There, according to the documentation, you use the Express framework thusly:

var express = require('express');
var app = express();

Open in new window

Then, all calls to Express APIs are via the "app.VERB()" syntax.

I could easily see additional JS frameworks like this coming to a server-side or an OSGi-container-like platform; things like middleware frameworks, media streaming frameworks, et al.
0
The most up-to-date version of this article is on my Blog https://iconoun.com/blog/
3
LVL 37

Expert Comment

by:lherrou
An elegant solution, and I can think of other ways to use it as well.

I voted YES above :)
0
Introduction
HyperText Transfer Protocol or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to the WWW in the days after 2005 (and therefore after the advent of jQuery), that seem to evince a misunderstanding of the way the HTTP protocol works.  Since HTTP is the basic building block of web sites and web applications, a clear understanding of the protocol is required to understand how web sites really work.  And perhaps more importantly, it is necessary to understand the protocol so you can build a web site that works like another site you've seen and appreciated.  This article is intended to lift the cloud of confusion that has appeared in the years since the arrival of jQuery, CSS3, animation in web sites, and the phenomenon called Web 2.0.

The confusion has arisen in large measure because of the design movement of web interactivity away from the static page loads and into design paradigms that more closely mimic native applications.  If the hyperlink was the design element that launched the internet revolution, the event handler may be thought of as the design element that has most refined the client experience.  In all cases, at the foundation is the HTTP protocol.

HTTP is a Stateless Client/Server Protocol
Client/Server protocols are two-way communication mechanisms that allow humans to get information from web sites
19
LVL 15

Expert Comment

by:Eric AKA Netminder
Ray,

A typically outstanding article. I've been fumbling through telling people this stuff for a long time, so it's nice to have a clear resource to which to send them.

Thanks!

ep
0
Once again, I've opened my peers' code and was terrified. So I decided to write this article. I hope that would be useful for someone. At the same time I've found an easier way to explain it to newcomers. I will just give them a link to this very article.
Of course the number of such things is very large, so the article is limited to a few of them.

1. Constants

This problem is not only javascript one but programming in general. Let's consider an example:
$elem.on('keydown', function(e) {
    if (e.keyCode == 27) {
        //...
    }
});

Open in new window

What is the magic number 27? People who often face the code immediately say - this is the key ESC. But most developers, especially beginners, do not remember the code, have to get into the search engine and waste their time.
Of course you can add a comment that hands ESC in the code, but much more effective is to introduce a constant, KEY_ESC = 27, for example.

2. Getting of the identifier

Often you need to get the ID of the element (comment, post, user, etc.) to perform some action (for example, to assess the comments with ajax). And you can often find this approach:
var id = $(this).attr('id').substring(8);

Open in new window

As in the previous example, the developer has to wonder - what is that number 8. He has to climb in the html code, etc.

There are worse examples (pattern copied from a real project):
var last_id = $('#answer_pid' + id + ' li:first div').attr('id').substr(7);

Open in new window

As the result the slightest change in layout will lead to change js code.

Sometimes we can see something like this:
<div class="comment" id="comment_123"></div>

Open in new window

var id = $(this).attr('id').substring("comment_".length);

Open in new window

3
LVL 58

Expert Comment

by:tigermatt
Nice set of tips. THank you for the submission. I voted for this by clicking "Yes" at the top.

-Matt
0
LVL 2

Author Comment

by:uaoleg
Thank for your response!
0
jQuery is a JavaScript library that greatly simplifies JavaScript programming.

AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a new page load.  An HTTP request occurs, but it occurs as a result of a JavaScript event, rather than an explicit page load or form submission.  As a result, the web page takes on an appearance much like a desktop application, with smooth transitions as data is added or removed from the viewport.  This is often referred to as the "Web 2.0" effect.

I found myself looking around for a jQuery/AJAX "Hello World" example (that simplest of scripts to prove that the essential moving parts are working correctly).  There are lots of partial examples in many different places all over the WWW, but nothing seemed complete and well-documented, so I decided to write my own.  Here is the result of that effort.

The Server-Side of the Exercise
To make my example, I decided the essential parts would be the ability to send some data to the server and get a response back, so the first part of the exercise is the server-side script that produces a response containing the data it received from the AJAX request.  AJAX provides a RESTful interface.  The data for the request is sent via GET or POST and the response from the server is sent in the form of browser output.  As a result, it is very easy to test the back-end script. …
19

Expert Comment

by:Nico2011
Thanks Ray - very helpful - hope you are well!
0
LVL 36

Expert Comment

by:Loganathan Natarajan
It is very helpful.
0
Why host your videos on Youtube?

Though, it is possible to get the video file URL of a YouTube video using sites like http://www.keepvid.com, but doing it programmatically is a problem you would like to give a pass. Hosting videos on your website involves a lot of challenges like making those videos work on multiple platforms and browsers, and making sure that video streaming doesn't take all your server's bandwidth due to the sheer size of videos. YouTube is already taking care of all those things, so it make sense to put all your videos on YouTube and let YouTube handle all these problems.

Working code for Safari, Chrome, Iphone and Ipads

Fortunately, there is a way to embed a youtube video in your mobile app by writing the same code compatible to many browsers like Safari 4+, Chrome 6+, Iphone 3+, and Ipad 1 (iOS3+).

<object id="idVideo" name="idVideo" width="90%" height="70%" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
	<param name="movie" value="http://www.youtube.com/watch?v=gCAcU3p9GNo&hl=en_US&fs=1&rel=0&hd=1&border=0&enablejsapi=1"/>';
	<param name="allowFullScreen" value="true"/>';
	<param name="allowScriptAccess" value="always"/>';
	<param name="wmode" value="transparent"/>';
	<embed src="http://www.youtube.com/watch?v=gCAcU3p9GNo&hl=en_US&fs=1&rel=0&hd=1&border=0&enablejsapi=1" type="application/x-shockwave-flash" allowScriptAccess="always" allowfullscreen="true" width="100%" id="idVideoPlayer" name="idVideoPlayer" 

Open in new window

0
Hello,
It's been long time since I wrote my last article on this series. You may like to read first part of this series named Understanding-javasript-part-1-getting-started. Let's continue on with part 2. Today you will learn how to declare/create variables, how to use them, what are their types, and what are pop-up boxes.

*Introduction to Variables:

What are variables? Variables are nothing but a construct in which we store values. Variables are important in Javascript. You should get familiar with this term. Don't worry,by the end of this topic you will be more familiar with variables.

Creating Variables:

To create variable there is syntax you should be familiar with:

Syntax:
var your_variable_name = "string" or (number);

Open in new window

Notes,
Variables are declared by 'var' keyword. It is like a some set of characters which help browser to recognized that you are declaring variable.
After 'var' keyword you can declare name of your variable. Variables name can be anything you like,but make sure you are declaring a name which will further help you to recognized easily what you stored in that particular variable
After that values must be assign to variables. Use '=' assignment operator to assign values to variable.
You can also declare variable first and then assign value to it later in a script.
You can assign anything to variable like numbers ,strings,any data etc.
*Strings: Strings are words or character which you enters.
*Numbers: 14234536 anything
*Data:
2
This article discusses the difference between strict equality operator and equality operator in JavaScript.

The Need:
Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when writing code.

The equality operator is denoted as “==” while strict equality operator is denoted as “===”.

Equality operator: (==)

This comparison operator returns true only when they are equal without comparing their types.

If two operands are of different types, JavaScript converts the operands and then applies strict comparison between them.

For example,
true == 1;     //true, because 'true' is converted to 1 and then compared.
"2" == 2;       //true, because 2 (the integer) is converted to "2" (the string) and then compared.

Strict equality operator: (===)

This === operator is exists in JavaScript because JavaScript is weakly typed language. For other languages, it is not needed for type comparison because other languages already have reserved words available to perform those functions. But for JavaScript, these special comparison operators make more sense.
 
You can use this operator only when exact type of operand is important for comparison.

For example,
true === 1;   //false
"2" === 2;     // false

What JavaScript does for comparison?

When type conversion is needed, JavaScript converts String, Number, Boolean or Object operands as follows:

1. When
0
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition.

To share some of our best practices, possibly the most important thing we changed is to eliminate all body onloads and instead rely on a different loading design, which is extremely friendly when your application is to be included by many webpages.

Because it scales both in case of server-side rendering as well as cases of lazy loading content, we are pleased to share a simplified version of the approach as a best practices with Experts Exchange.

So lets start with some code and take, for example, a simple AJAX driven search application.

<html>
  <head>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
  </head>
  <body>
    <div class="my-search-app">
       <form action="/search">
         <input type="text" name="q" /><input type="submit" value="search" />
       </form>
       <div class="my-search-results"></div>
       <script type="text/javascript" src="my-search-app.js"></script>
     </div>
  </body>
</html>

Open in new window


In any other, non-portable, application the most sensible JQuery logic to add in my-search-app.js would be:

// Closure
(function(window, document, $) {

  $(document).ready(function() {
     // Capture search form submit and transfor into AJAX request
     $('form').submit(function() {
       // AJAX Logic and stuff
       fnResults = function(data) {
          $('.my-search-results').html('Results ... ');
       }
     });
  });

// End of closure
})(window, document, jQuery);

Open in new window


This portable approach is more complex but we'll explain later on.


Open in new window

3
LVL 49

Author Comment

by:Roonaan
Thanks, I can see the total, but was wondering if there was a breakdown somewhere.
0
This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big article at a time. You may also get in confusion with it and complexity is also high. So lets learn JavaScript we will together will have lots of fun and good company. :-)

Things you should know before you start learning JavaScript

To get started with JavaScript, you should have a basic, comfortable working knowledge of:
Basic HTML (Hyper Text Markup Language)
Basic CSS (Cascaded Style Sheets)
If you do not have a comfortable working knowledge of these topics, I suggest you read up on them before you continue.

If you are a programmer then, great! But if you not, then even better!

     Everyone is welcome in JavaScript. We will be learning JavaScript from scratch. So, if you know  another programming language, you may want to skip some of the basic topics, but I  suggest you resist that temptation because it may cause you confusion ahead. For those who are new to programming, you're in the right place.

"NO PROGRAMMING KNOWLEDGE IS REQUIRED TO GET STARTED WITH JavaScript".


History

    JavaScript was formed by Netscape developers in 1995. They named it as "LiveScript" that time. But in same period Sun's java was come into fame sun and Netscape …
5
LVL 32

Expert Comment

by:DrDamnit
If you've worked with him before, do you want to take it?
0

Expert Comment

by:mikeplastic
Nice article, I know more now than I did before.  Thank you for your effort.
0
The task

A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome.

So let’s take a number like this “12345678.91¿ and format it to “12 345 678.91¿. To be shorter I assign it to a variable and hustled up following line which produced desired format:
> var n = "12345678.91";
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\.|,\./g, '.'));
> "12 345 678.91"

Open in new window


How it’s made

First there is a string that has to be split somehow into triad. This is pretty simple – I’ve just used Regular expression with match and join methods to get the result back into a string using desired digital group separator (space in the case):
> n.match(/.{1,3}/g).join(' ');
> "123 456 78. 91"

Open in new window

The problem here is that RegExp is staring from left to right and produced wrong (from the task’s point of view) result. There is a two spaces where there shouldn’t be: after the dot and in the last triad (having two digits instead of three). First space I’ve eliminated adding regexp replace function.
> n.match(/.{1,3}/g).join(' ').replace(/\.\s/g, '.');
> "123 456 78.91"

Open in new window

Now it seems OK on the right of the dot. But last triad has still two digits. This is because RegExp rules passed to the match function are applied from left to right. So until dot is found it is impossible to predict how triad will be formed. Instead of applying more complicated regexp I’ve decided to reverse numbers before to add group separator.
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ');
> "19. 876 543 21"

Open in new window

1
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
well how we show it then
0
LVL 22

Author Comment

by:Ivo Stoykov
if you mean the result... Just assign it to a variable
// var res = n.toFixed(2).split('') ... put all the stuff here

Open in new window

0
In Part 1 we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'll add logic to find the solution to the maze using a depth-first search, and we'll animate the action to make it fun to watch.
Hex maze with solutionThink of a hedge maze (perhaps like the one in the movie The Shining or Harry Potter and the Goblet of Fire).  If you know that there is exactly one true path from start to finish, then it is pretty easy to solve.  Just put your left hand on one wall and keep touching that wall as you move forward.  That will force you to always make every available left turn.  When you reach a cul-de-sac (dead end), you'll circle around and retrace your path to a room has more than one exit and, this time, the left turn will be through a doorway you have not explored.
Winding through the mazeNow imagine that when you hit a cul-de-sac, you could zoom directly back to the room that had the most recent decision point.  Then you could resume with the "always turn left" routine and you would be exploring an uncharted path.  That's essentially the algorithm that I devised for solving this maze.

This is called a depth-first search because it goes as far as it can along one branch of the decision tree before it begins to explore a different branch.  The algorithm lends itself well to a stack-oriented implementation
8
LVL 50

Author Comment

by:DanRollins
If you want to see the program in action without doing a download, just click here.
0
LVL 18

Expert Comment

by:WaterStreet

Really neat
0
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2, we'll extend the program by adding a depth-first search algorithm that solves the maze.  The Hex Maze program is unusual and visually impressive since you can watch the action as the maze is created and solved.
A hexagonal-cell maze written in JavaScriptHexagons connect up into a regular lattice in nature and they are of scientific interest for many reasons.  Bees use hexagonal honeycombs because they enclose the maximum volume of honey with the minimum amount of beeswax and construction labor.  Carbon atoms naturally attach themselves in hexagonal patterns.  Throw in a few pentagons and you have buckmisterfullerine, one of my favorite molecules.  Have you ever noticed that the stars spangling "Ol' Glory" are arranged in a hexagonal pattern?
Hexagonal patterns are everywhere
Note:  There is an iconic Experts-Exchange question that relates to hexagonal cells.  It is historically significant because it involved a large number of top EE Experts (the aptly-named "A Team") working together while at Core Conference, 2008. See my LYIR 2008 posting for more on that, including a link to the original question and photos.
I first got interested in hexagonal cells back in 1979.  I had written a BASIC program to create a maze and it occurred to me that a maze built from hexagonal cells would be an interesting challenge. I wrote and published an article about it in a magazine named Creative Computing
14
LVL 18

Expert Comment

by:WaterStreet
Nice high-quality work.  Voted Yes, above
0
Introduction
HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is not checked?  Unlike the text-type input controls, the unchecked checkbox is simply absent from the request.  This situation makes it necessary for our action script to know in advance what checkboxes might or might not be present.  What if we have several checkboxes that are related and we want an all-or-nothing option?  We can use an array of checkboxes and a little JavaScript to make our forms easier for the client.  This script demonstrates some of the popular design patterns for using checkboxes in HTML, JavaScript and PHP.  

Initialization
In the code example, script initialization starts at line 10.  We set up an associative array of key=>value pairs.  This array is our data model.  It lets the script produce checkboxes that are generated dynamically, depending on the contents of the array.  If you wanted to add, for example, "Graduates" you just add that to the $options array following the pattern shown in the code snippet.  No other changes to either the form or action script would be needed.  The new option would appear automatically.  If you think creatively about this array you realize that it does not need to be hard-coded.  It might come from the results of a data base query.

The "Action" Script
8

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.