Tuesday, March 31, 2015

jQuery noconflict


Many JavaScript libraries use $ as a function or variable name just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $.We know by default, jQuery uses $ as shortcut for jQuery. Thus, if you are using another JavaScript library that uses the $ variable,you can run into conflicts with jQuery.In order to avoid these conflicts, you need to put jQuery in to no-conflict mode.

$.noConflict() method to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.

Long story short, jQuery already planned for library conflicts and has a quick solution. The no-conflict mode allows you to define your own shortcut, and of course it works like a charm.
It's easy to do - just put this line in your code somewhere:
var j = jQuery.noConflict();
For Example , in your page have id attribute called "result". If you not put the jQuery noConflict means you need to use the $ jQuery to call the id attribute like $("#result"). If you assign the jQuery.noConflict to a variable , then you can call the id attribute like variablename("#result")
Example : Try this jsfiddle



Unknown Software Engineer

Monday, March 30, 2015

Callback JavaScript


JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.
To prevent this, you can create a callback function. A callback function is executed after the current effect is finished.
Let's start with a very simple script that uses no callbacks. First we'll establish a super-quick HTML structure to output results to:
<html>
    <body>
        <p id="result">
        </p>
    </body>
</html>

And then we'll add a bit of JavaScript:

document.getElementById('result').innerHTML += ('starting ...');
document.getElementById('result').innerHTML += ('continuing ...');

document.getElementById('result').innerHTML += ('ending!');

Go ahead and run it for yourself. So, great … as you can see when you run this, it prints "ending!" before "continuing …" pretty much exactly as expected. And no good. We don't want to end in the middle. We want to end at the end.
So let's do that.
SETTIMEOUT() - FIRST CALLBACK
JavaScript has a function for delayed execution of commands. You give it a command to run, and the number of milliseconds to wait before running it. It's handy for a variety of reasons, but its value here is that when you use it, your JavaScript interpeter (in my case, Chrome … but any browser, as well as Node, will do the same) considers it an asynchronous, non-blocking request. Here's our new code:
document.getElementById('result').innerHTML += ('starting ...');
var myTimer = window.setTimeout(function() {
    document.getElementById('result').innerHTML += ('ending!');
}, 500);

document.getElementById('result').innerHTML += ('continuing ...');

check that out.Now we're back to having the right order in our output, even though the code's not sequential, because we're waiting half a second before executing an anonymous function that writes our "ending!" string. Finding the anonymous function thing confusing? You could also write the code like this:


document.getElementById('result').innerHTML += ('starting ...');

// Wait half a second before firing the writeEnding() function
var myTimer = window.setTimeout(writeEnding, 300);
document.getElementById('result').innerHTML += ('continuing ...');

// Define the Write Ending Function
function writeEnding() {
    // Write "ending!"
    document.getElementById('result').innerHTML += ('ending!');
}

Same exact thing, but now the function's not anonymous because we declared it at the bottom. We're still calling it with setTimeout, though, after 300 milliseconds. 

CREATING OWN CALLBACKS
 We've established that setTimeout uses a callback to enact a delayed execution of a function, but how do we write one of our own? Easy! Like this:


getData('http://javascripttech.blogspot.com/userlist', result);

document.getElementById('result').innerHTML += "show this before data loaded ...";
function getData(dataURI, callback) {
    // Normally you would actually connect to a server here.
    // We're just going to simulate a 2-second delay.
    var timer = setTimeout(function () {
        var dataArray = [123,579,456,258,476,458];
        callback(dataArray);
    }, 2000);
}
function result(myData) {
    document.getElementById('result').innerHTML += myData;

}

If you run this in jsfiddle, you'll see it behaves just as we want it to: even though the getData function is the first thing called, and takes two seconds to run, the script continues right along. When the two seconds are up and getData responds with data, then result fires and writes the data.

Unknown Software Engineer

How to detect if JavaScript is disabled ?


Nowadays almost all web pages using JavaScript programming language . It makes web pages functional for specific purpose and if disabled for some reason, the content or some functionality of the web page will not work as expected.  

Lets take one example :

     Here we have basic form validation :                                               
     
In the Name textbox input  we will have three events onfocus, onkeyup, onblur like below:

<input id="txtname"type="text"onfocus="validateIfEmpty('txtname') onblur="validateIfEmpty('txtname')" onkeyup="validateIfEmpty('txtname')"></input>

      Similarly in Gender textbox also will have same three events. validateIfEmpty is a javaScript function that will be call onfocus , onblur , onkeyup of the textbox.

Events :
onfocus -- The onfocus event occurs when an element gets focus. 

onblur -- The onblur event occurs when an object loses focus.

onkeyup -- The onkeyup event occurs when the user releases a key (on the keyboard).

Below script is  validateIfEmpty :

function(controlId) {
    var control = document.getElementById(controlId);
    if(control.value === ""){
        control.style.background = "red";
    }else{
        control.style.background = "white";
    }

In that method we will pass 'id' attribute of the textbox . If the textbox value is null then will show background color as red else white.

How to check the JavaScript is disabled ?

The <noscript> tag defines an alternate content for users that have disabled scripts in their browser or have a browser that doesn't support script.

We just place the code that we want to display when Javascript is not supported between noscript tags and the enclosed code will only be included in browsers that either don't recognise script or noscript tags (and therefore ignore both tags just displaying what is between them instead) or which recognise the tag and also identifies that Javascript has been turned off.

Example :

<noscript>Javascript  is disabled</noscript>

 Real Example pageTry it yourself

  In the above example at first you will able to see the form validation textbox , once you disabled the JavaScript in your browser setting you will see the following text message .

"It seems that you have disabled JavaScript, please enable JavaScript"

How to disable the JavaScript in chrome browser:

Steps to disable in chrome :

  1. On the web browser menu click on the "Customize and control Google Chrome" and select "Settings".
  2. In the "Settings" section click on the "Show advanced settings..."
  3. Under the the "Privacy" click on the "Content settings...".
  4. When the dialog window opens, look for the "JavaScript" section and select "Do not Allow all sites to run JavaScript ".
  5. Click on the "OK" button to close it.
  6. Close the "Settings" tab.
After steps completed click the Run with JS button in the jsBin example page.

  
Unknown Software Engineer

Sunday, March 29, 2015

Understanding Timers : setTimeout() and setInterval()


Browser provides a built-in scheduler which allows to setup function calls for execution after given period of time.


setTimeout :


The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

The Syntax is

var timerId = setTimeout(func | code, delay)

                        func | code -- Function variable or the string of code to execute.
                        delay -- Delay in 1000 ms . 1000 ms = 1 second


Cancelling the Execution :

 The ID value returned by setTimeout() is used as the parameter for          the clearTimeout() method.
            clearTimeout(timerId) 

Example : Try it yourself


setInterval :


The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

The Syntax is 

The setInterval(func|code, delay) method has same features as setTimeout.

var timerId = setInterval(func | code, delay)

Cancelling the Execution :

The ID value returned by setInterval() is used as the parameter for the clearInterval() method.

         clearInterval(timerId) 

Example : Try it yourself

Unknown Software Engineer

JavaScript regular expressions


Regular expressions is a form of pattern matching that you can apply on textual content.When you search for data in a text, you can use this search pattern to describe what you are searching for.

In JavaScript, regular expressions are often used with the two string methods: search(), replace(), match(), split().

Modifiers

Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc.

  • i -- Perform case-insensitive matching.
  • m -- Specifies that if the string has newline or carriage return characters.
  • g -- Perform a global match , find all matches rather that stopping after the match. 
Search :
The search() method uses an expression to search for a match, and returns the position of the match.


 Syntax : string.search(searchvalue)
   
                            searchvalue -- Required. A string will automatically be converted to a regular                                                              expression.
 ExampleTry it yourself

replace :
  The replace() method returns a modified string where the pattern is replaced.

Syntax : string.replace(searchvalue,newvalue)
         
                            searchvalue -- Required.The value or regular expression, that will be replaced buy                                                       the new value.
                             newvalue     -- Required.The value to replace the searchvalue with.

Example : Try it yourself

match :           
  The match() method searches a string for a match against a regular expression, and returns the matches, as an array object.

 Syntax : string.match(regexp)

                            regexp --  Required.The value to search for, as a regular expression.

Example : Try it yourself

split :
  The split() method is used to split a string into an array of substrings, and returns the new array.

Syntax : string.split(separator,limit)

                         separator -- Optional.Specifies the character, or the regular expression, to use for                                                     splitting the string. If omitted, the entire string will be returned.
                         limit        -- Optional. An integer that specifies the number of splits, items after the                                                    split limit will not be included in the array.

Example :  Try it yourself

Unknown Software Engineer

JavaScript Introduction


  • JavaScript is more popular and commonly used as a client side scripting language. This means that JavaScript code is written into an HTML page.When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it.
  • JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

Syntax :
  • A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.
  • You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way to keep it within the <head> tags.
      The <script> tag alert the browser program to begin interpreting all the text between              these tags as a script. So simple syntax of your JavaScript will be as follows
                                       
                                           <script>
                                            JavaScript Code
                                           </script>
Unknown Software Engineer