Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: JavaScript

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: JavaScript
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

JAVA SCRIPT - Testing for Features with Modernizr.load

Testing for Features with Modernizr load


Problem

You’re using newer technologies, and you want to make sure the client can support the technologies before you load them.

Solution

You can use a library such as Modernizr to handle basic HTML5/CSS differences be‐ tween browsers. But you can also use a companion tool, Modernizr.load, to test to see if an existing technology is supported

As an example, if you want to incorporate touch events in your application, you can use Modernizr to test whether they’re supported in an environment and only load the ap‐ plication script if they are. In the following code, the application is testing to see if the touch events, covered in Chapter 18, are supported. If they are, the application script is loaded:


Modernizr.load({
 test: Modernizr.touch,
 yep : 'touchtest.js'
});


EXPLAIN


Modern browser makers are highly competitive, which means that most of the modern technologies we want to use are already part of the browser your user is most likely using. Unfortunately, we can’t take it as given that every user is using the most modern browser, and that’s where a concept like feature detection enters. 

Years ago, when testing for browser differences, we’d check browser versions because browser companies didn’t release new versions all that often. The idea of doing this nowadays, when some of the companies seemingly release a new version every week, is ludicrous. 

Feature detection is a way of guaranteeing that the environment will support your application, regardless of browser version or client. Feature detection can be tedious, though, and tricky. That’s where a feature detection tool like Modernizr.load comes in. It comes with a set of feature detection tests already built in, as demonstrated in the solution. 

And you can use Modernizer.load plugins to check for others, or even create your own. To use Modernizr.load, go to the Modernizr site, check the features you want to test and/or support, and the site builds a custom library. To use the library, include the script in the page (in the head element, preferably after your style elements), and then include the links to your test scripts.


 You can also use the software to load a polyfill library to manage differences:


Modernizr.load({
 test: Modernizr.websockets,
 nope : 'websockets.js'
});

You can list multiple JavaScript files, separated by commas, for both the yep and nope properties.

JAVA SCRIPT - Finding the Perfect Library

 Finding the Perfect Library


Problem

You need functionality in your application, and you’re pretty sure someone somewhere must have already created it. So, other than using a search engine, how can you find good modules, libraries, and tools?

Solution

Look for resource sites that not only provide a listing of libraries, modules, and tools, but also provide information about their use, their popularity, and how active the sup‐ port is for them.

EXPLAIN

First of all, don’t knock search engines for finding good JavaScript source. By using Google’s Search tools and restricting results to the past year, I can easily find recent and up-to-date code, as well as interesting newcomers that haven’t yet achieved a high level of popularity. 

Still, you’re also just as likely to run into pages of Stack Overflow results rather than a library when searching for JavaScript functionality, so another option when looking for a new library is to search popular script resources sites.

 GitHub is a good resource for JavaScript libraries, modules, and tools, and you’ll also be able to see at a glance if the code is being maintained and how popular it is. You can search for specific functionality, or you can use the GitHub Explore page to find new and interesting 

GitHub projects by category. I especially recommend the Data Visual‐ ization category. Micro.js is a site featuring a small set of what it calls micro-frameworks. These are smaller, more purposed JavaScript libraries, all displayed in a fun little site. JSDB.io calls itself “the definitive source of the best JavaScript libraries, frameworks, and plugins,” and it is an excellent resource. 

Again, just search for the general type of functionality you need, such as canvas chart, and then peruse the results. The results even give you an approval percentage, and the returned page also provides information such as GitHub watchers, average time between commits, average forks, and average number of contributors. 

JAVA SCRIPT - Creating an Accessible Automatically Updated Region

Creating an Accessible Automatically Updated Region


Problem

You have a section of a web page that is updated periodically, such as a section that lists recent updates to a file, or one that reflects recent Twitter activity on a subject. You want to ensure that when the page updates, those using a screen reader are notified of the new information.

Solution 

Use WAI-ARIA region attributes on the element being updated:

<ul aria-alive="polite" aria-atomic="true" aria-relevant="additions" id="update" role="log">
</ul>

EXPLAIN

A section of the web page that can be updated after the page is loaded, and without direct user intervention, calls for WAI-ARIA Live Regions. These are probably the sim‐ plest ARIA functionality to implement, and they provide immediate, positive results. And there’s no code involved, other than the JavaScript you need to create the page updates.

updates the web page based on the contents of a text file on the server that the application retrieves using Ajax. I modified the code that polls for the updates to check how many items have been added to the unordered list after the update. If the number is over 10, the oldest is removed from the page: 


// process return
function processResponse() {
 if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
 var li = document.createElement("li");
 var txt = document.createTextNode(xmlhttp.responseText);
 li.appendChild(txt);
 var ul = document.getElementById("update");
 ul.appendChild(li);
 // prune top of list
 if (ul.childNodes.length &gt; 10) {
 ul.removeChild(ul.firstChild);
 }
 } else if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status != 200) {
 console.log(xmlhttp.responseText);
 }
}


With this change, the list doesn’t grow overly long. I made one more change, adding the ARIA roles and states to the unordered list that serves as the updatable live region:

<ul aria-atomic="false" aria-live="polite" aria-relevant="additions s" id="update" role="log">
</ul>

From left to right: the role is set to log, because I’m polling for log updates from a file, and only displaying the last 10 or so items. Other options include status, for a status update, and a more general region value, for an undetermined purpose. The aria-live region attribute is set to polite, because the update isn’t a critical update.

The polite setting tells the screen reader to voice the update, but not interrupt a current task to do so. If I had used a value of assertive, the screen reader would interrupt whatever it is doing and voice the content. Always use polite, unless the information is critical. The aria-atomic is set to false, so that the screen reader only voices new additions, based on whatever is set with aria-relevant.

It could get very annoying to have the screen reader voice the entire set with each new addition, as would happen if this value is set to true. Lastly, the aria-relevant is set to additions, as we don’t care about the entries being removed from the top. This setting is actually the default setting for this attribute, so, technically, it isn’t needed. In addition,

AT devices don’t have to support this attribute. Still, I’d rather list it than not. Other values are removals, text, and all (for all events). You can specify more than one, separated by a space. This WAI-ARIA–enabled functionality was probably the one that impressed me the most.

One of my first uses for Ajax, years ago, was to update a web page with information. It was frustrating to test the page with a screen reader (JAWS, at the time) and hear nothing but silence every time the page was updated. I can’t even imagine how frus‐ trating it was for those who needed the functionality. Now we have it, and it’s so easy to use. It’s a win-win.


JAVA SCRIPT - Performance Testing Different Coding Techniques

Performance Testing Different Coding Techniques



Problem

In JavaScript there are, typically, multiple ways you can code a solution. The problem then becomes determining which of the different ways performs best across different environments.

Solution

One approach is to use a performance testing tool, such as jsPerf, to try out the different approaches and then proceed accordingly. For instance. I wanted to determine which had better performance—using an anonymous function or a named function—when passed as a callback function in an Array method. In jsPerf, I set up an array of string elements and created the named function, rpl(), in the Preparation code section:


var charSet = ["**","bb","cd","**","cc","**","dd","**"];
function rpl (element) {
 return (element !== "**");
};

My first test case was using the anonymous function:

var newArray = charSet.filter(function(element) {
 return (element !== "**");
});

My second test case was using the named function:

var newArray = charSet.filter(rpl);

EXPLAIN

There are variations of performance testing, from the simple alternative testing demon‐ strated in the solution, to complex, involved load testing of entire systems. These types of testing aren’t used to discover whether there are bugs in the code, or if the code meets use requirements—unit testing should find the former, and some form of user compli‐ ance testing finds the latter. Performance testing is specifically for finding the best, most efficient approach to cre‐ ating your application, and then making sure it meets the demands placed on it when running at peak usage.  

Another approach to performance testing is profiling. Most browser debuggers have a built-in profiling capability. As an example, the popular Firebug debugger for Firefox has profiling built in and available with the click of the “Profile” button, 

Once you turn profiling on, you can run your user compliance tests as a way of generating good usage statistics, and then click the “Profile” button again. Firebug then generates a listing of functions called any time for them to respond.

Chrome also has extensive profiling capability, . To use it, open up the JavaScript Console, click the Profiles tab, and then start whichever profiling type you want to start. After you’ve used your application for some time, click the Profiles “Stop” button and view the results.


JAVA SCRIPT - Displaying a Flash of Color to Signal an Action

Displaying a Flash of Color to Signal an Action


Problem

Based on some action, you want to display a visual cue to signify the success of the action.

Solution

Use a flash to signal the success or failure of an action. While a red flash is standard for signaling either a successful deletion or an error, a yellow flash is typically used to signal a successful update or action:


var fadingObject = {
 yellowColor : function (val) {
 var r="ff"; var g="ff";
 var b=val.toString(16);
 var newval = "#"+r+g+b;
 return newval;
 },
 fade : function (id,start,finish) {
 this.count = this.start = start;
 this.finish = finish;
 this.id = id;
 this.countDown = function() {
 this.count+=30;
 if (this.count >= this.finish) {
 document.getElementById(this.id).style.background=
 "transparent";
 this.countDown=null;
 return;
 }
 document.getElementById(this.id).style.backgroundColor=
 this.yellowColor(this.count);
 setTimeout(this.countDown.bind(this),100);
 }
 }
};
...
// fade page element identified as "one"
fadingObject.fade("one", 0, 300);
fadingObject.countDown();

EXPLAIN


A flash, or fade as it is frequently called, is a quick flash of color. It’s created using a recurring timer that gradually changes the background color of the object being flashed. The color is varied by successively changing the values of the nondominant RGB colors, or colors from a variation of 0 to 255, while holding the dominant color or colors at FF. If, for some reason, the color can’t be perceived (because of color blindness or other factor), the color shows as successions of gray. 


As you progress down the figure, the color gets progressively paler, as the nondominant red and blue values are increased, from initial hexadecimal values of 00 (0) to FF (255). The color yellow used in the solution kept the red and green values static, while changing the blue. A red flash would keep the red color static, while adjusting both the green and blue. In the solution, 


I’m setting the beginning and ending colors for the flash when the application calls the fade method on the object, fadingObject. Thus, if I don’t want to start at pure yellow or end at white, I can begin or end with a paler color. A color flash is used to highlight an action. 

As an example, a red flash can signal the deletion of a table row just before the row is removed from the table. The flash is an additional visual cue, as the table row being deleted helps set the context for the flash. A yellow flash can do the same when a table row is updated. 

A flash can also be used with an alert message. In the following code snippet, I created an alert that displayed a solid color until removed from the page. I could also have used a red flash to highlight the message, and left the background a pale pink at the end: 


function generateAlert(txt) {
 // create new text and div elements and set
 // Aria and class values and id
 var txtNd = document.createTextNode(txt);
 msg = document.createElement("div");
 msg.setAttribute("role","alert");
 msg.setAttribute("id","msg");
 // fade
 obj.fade("msg", 0, 127);
 obj.redFlash();
 msg.setAttribute("class","alert");
 // append text to div, div to document
 msg.appendChild(txtNd);
 document.body.appendChild(msg);
}


The only requirement for the solution would be to either make the color-fade effect more generic, for any color, or add a new, specialized redFlash method that does the same as the yellow.

Also note the use of the ARIA alert role in the code snippet. Including an accessible effect ensures all your users will benefit, and as the code demonstrates, it doesn’t add any extra effort.

JAVA SCRIPT - Creating Hover-Based Pop-Up Info Windows

Creating Hover-Based Pop-Up Info Windows


Problem

You like the Netflix website’s pop-up window that displays when the mouse cursor is over a movie thumbnail, and you want to incorporate this functionality into your own application.

Solution

The Netflix-style of pop-up info window is based on four different functionalities. First, you need to capture the mouseover and mouseout events for each image thumbnail, in order to display or remove the pop-up window, respectively. In the following code, the cross-browser event handlers are attached to all images in the page:

window.onload=function() {
 var imgs = document.getElementsByTagName("img");
 for (var i = 0; i < imgs.length; i++) {
 imgs[i].addEventListener("mouseover",getInfo, false);
 imgs[i].addEventListener("mouseout",removeWindow, false);
 }
}

Second, you need to access something about the item you’re hovering over in order to know what to use to populate the pop-up bubble. The information can be in the page, or you can use web server communication to get the information:

function getInfo() {
 // prepare request
 if (!xmlhttp) {
 xmlhttp = new XMLHttpRequest();
 }
 var value = this.getAttribute("id");
 var url = "photos.php?photo=" + value;
 xmlhttp.open('GET', url, true);
 xmlhttp.onreadystatechange = showWindow;
 xmlhttp.send(null);
 return false;
}


Third, you need to either show the pop-up window, if it already exists and is not dis‐ played, or create the window. In the following code, the pop-up window is created just below the object, and just to the right when the web server call returns with the infor‐ mation about the item.

The getBoundingClientRect() method is used to determine the location where the pop up should be placed, and createElement() and create TextNode() are used to create the pop up:


// compute position for pop up
function compPos(obj) {
 var rect = obj.getBoundingClientRect();
 var height;
 if (rect.height) {
 height = rect.height;
 } else {
 height = rect.bottom - rect.top;
 }
 var top = rect.top + height + 10;
 return [rect.left, top];
}
// process return
function showWindow() {
 if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var response = xmlhttp.responseText.split("#");
 var img = document.getElementById(response[0]);
 if (!img) return;
 // derive location for pop up
 var loc = compPos(img);
 var left = loc[0] + "px";
 var top = loc[1] + "px";
 // create pop up
 var div = document.createElement("popup");
 div.id = "popup";
 var txt = document.createTextNode(response[1]);
 div.appendChild(txt);
// style pop up
 div.setAttribute("class","popup");
 div.setAttribute("style","left: " + left + "; top: " + top);
 document.body.appendChild(div);
 }
}

Lastly, when the mouseover event fires, you need to either hide the pop-up window or remove it—whichever makes sense in your setup. Since the application created a new pop-up window in the mouseover event, it removes the pop-up in the mouseout event handler:

function removeWindow() {
 var popup = document.getElementById("popup");
 if (popup)
 popup.parentNode.removeChild(popup);
 return false;
}

EXPLAIN


Creating a pop-up information or help window doesn’t have to be complicated if you keep the action simple and follow the four steps outlined in the solution. If the pop up provides help for form elements, then you might want to cache the information within the page, and just show and hide pop-up elements as needed. 

However, if you have pages like the ones at Netflix, which can have hundreds of items, you’ll have better perfor‐ mance if you get the pop-up window information on demand via a web service call (i.e., Ajax or WebSockets). The solution demonstrates that using web calls doesn’t add sig‐ nificant additional complexity to the application. When I positioned the pop up in the example, I didn’t place it directly over the object. 

The reason is that I’m not capturing the mouse position to have the pop up follow the cursor around, ensuring that I don’t move the cursor directly over the pop up. But if I statically position the pop up partially over the object, the web page readers could move their mouse over the pop up, which triggers the event to hide the pop up…which then triggers the event to show the pop up, and so on. 

This creates a flicker effect, not to mention a lot of network activity. If, instead, I allowed the mouse events to continue by returning true from either event handler function, when the web page readers move their mouse over the pop up, the pop up won’t go away. 

However, if they move the mouse from the image to the pop up, and then to the rest of the page, the event to trigger the pop-up event removal won’t fire, and the pop up is left on the page. 

The best approach is to place the pop up directly under (or to the side, or a specific location in the page) rather than directly over the object. This is the approach Netflix uses on its site. 

JAVA SCRIPT - Hiding Page Sections

 Hiding Page Sections



Problem

You want to hide an existing page element and its children until needed. 

Solution

You can set the CSS visibility property to hide and show the message:
msg.style.hidden="visible"; // to display
msg.style.hidden="hidden"; // to hide
or you can use the CSS display property:
msg.style.display="block"; // to display
msg.style.display="none"; // to remove from display

EXPLAIN

Both the CSS visibility and display properties can be used to hide and show ele‐ ments. There is one major difference between the two that impacts which one you’ll use. The visibility property controls the element’s visual rendering, but its physical pres‐ ence still affects other elements. When an element is hidden, it still takes up page space. 

The display property, on the other hand, removes the element completely from the page layout. The display property can be set to several different values, but four are of particular interest to us:

 • none: When display is set to none, the element is removed completely from display.
 • block: When display is set to block, the element is treated like a block element, with a line break before and after.
 • inline-block: When display is set to inline-block, the contents are formatted like a block element, which is then flowed like inline content.
 • inherit: This is the default display, and specifies that the display property is in‐ herited from the element’s parent.

There are other values, but these are the ones we’re most likely to use within JavaScript applications. Unless you’re using absolute positioning with the hidden element, you’ll want to use the CSS display property. Otherwise, the element will affect the page layout, pushing any elements that follow down and to the right, depending on the type of hidden element. There is another approach to removing an element out of page view, and that is to move it totally offscreen using a negative left value. 

This could work, especially if you’re cre‐ ating a slider element that will slide in from the left. It’s also an approach that the ac‐ cessibility community has suggested using when you have content that you want ren‐ dered by assistive technology (AT) devices, but not visually rendered. 


JAVA SCRIPT - Adding Text to a New Paragraph

Adding Text to a New Paragraph 



Problem

You want to create a new paragraph with text and insert it just before the second para‐ graph within a div element:

// use getElementById to access the div element
var div = document.getElementById("target");
// use getElementsByTagName and the collection index
// to access the second paragraph
var oldPara = div.getElementsByTagName("p")[1]; // zero based index
// create a text node
var txt =
document.createTextNode("The new paragraph will contain this text");
// create a new paragraph
var para = document.createElement("p");
// append the text to the paragraph, and insert the new para
para.appendChild(txt);
div.insertBefore(para, oldPara);

EXPLAIN

The text within an element is, itself, an object within the DOM. Its type is a Text node, and it is created using a specialized method, createTextNode().

The method takes one parameter: the string containing the text. shows a web page with a div element containing four paragraphs. The JavaScript creates a new paragraph from text provided by the user via a prompt.

The text could just as easily have come from a server communication or other process. The provided text is used to create a text node, which is then appended as a child node to the new paragraph. The paragraph element is inserted in the web page before the first paragraph.

Demonstrating various methods for adding content to a web page


<head>
<title>Adding Paragraphs</title>
</head>
<body>
<div id="target">
 
 There is a language 'little known,'

 Lovers claim it as their own.
 <br />

 
 Its symbols smile upon the land, 

 Wrought by nature's wondrous hand;
 <br />

 
 And in their silent beauty speak,

 Of life and joy, to those who seek.
 <br />

 
 For Love Divine and sunny hours 

 In the language of the flowers.
 <br />

</div>
<script>
 // use getElementById to access the div element
 var div = document.getElementById("target");
 // get paragraph text
 var txt = prompt("Enter new paragraph text","");
// use getElementsByTagName and the collection index
 // to access the first paragraph
 var oldPara = div.getElementsByTagName("p")[0]; //zero based index
 // create a text node
 var txtNode = document.createTextNode(txt);
 // create a new paragraph
 var para = document.createElement("p");
 // append the text to the paragraph, and insert the new para
 para.appendChild(txtNode);
 div.insertBefore(para, oldPara);
</script>
</body>
</html>

JAVA SCRIPT - Finding All Elements That Share an Attribute

Finding All Elements That Share an Attribute


Problem

You want to find all elements in a web document that share the same attribute. 

Solution

Use the universal selector (*) in combination with the attribute selector to find all ele‐ ments that have an attribute, regardless of its value:

var elems = document.querySelectorAll('*[class]');

The universal selector can also be used to find all elements with an attribute that’s as‐ signed the same value:

elems = document.querySelectorAll('*[class="red"]');


EXPLAIN 


The solution demonstrates a rather elegant query selector, the universal selector(*). The universal selector evaluates all elements, so it’s the one you want to use when you need to verify something about each element. In the solution, we want to find all of the ele‐ ments with a given attribute. To test whether an attribute exists, all you need to do is list the attribute name within square brackets ([attrname]). In the solution, we’re first testing whether the element contains the class attribute. If it does, it’s returned with the element collection:

var elems = document.querySelectorAll('*[class]');

+Next, we’re getting all elements with a class attribute value of red. If you’re not sure of the class name, you can use the substring-matching query selector:

var elements = document.querySelectorAll('*[class*="red"]');

JAVA SCRIPT - Chaining Your Object’s Methods

 Chaining Your Object’s Methods


Problem

You wish to define your object’s methods in such a way that more than one can be used at the same time, similar to the following, which retrieves a reference to a page element and sets the element’s style property: 


document.getElementById("elem").setAttribute("class","buttondiv");

Solution 

The ability to directly call one function on the result of another in the same line of code is known as method chaining. It requires specialized code in whatever method you want to chain. For instance, if you want to be able to chain the changeAuthor() method in the following code snippet, you must also return the object after you perform whatever other functionality you need:

function Book (title, author) {
 this.getTitle=function() {
 return "Title: " + title;
 };
 this.getAuthor=function() {
 return "Author: " + author;
 };
 this.replaceTitle = function (newTitle) {
 var oldTitle = title;
 title = newTitle;
 };
 this.replaceAuthor = function(newAuthor) {
 var oldAuthor = author;
 author = newAuthor;
 };
}
function TechBook (title, author, category) {
 this.getCategory = function() {
 return "Technical Category: " + category;
 };
 Book.apply(this,arguments);
 this.changeAuthor = function(newAuthor) {
 this.replaceAuthor(newAuthor);
 return this; // necessary to enable method chaining
 };
}
var newBook = new TechBook("I Know Things", "Smart Author", "tech");
console.log(newBook.changeAuthor("Book K. Reader").getAuthor());

EXPLAIN 


The key to making method chaining work is to return a reference to the object at the end of the method, as shown in the changeAuthor() method in the solution:

this.changeAuthor = function(newAuthor) {
 this.replaceAuthor(newAuthor);
 return this; // necessary to enable method chaining
};

Chaining is used extensively in JavaScript objects, and demonstrated throughout this book when we see functionality such as:

var result = str.replace(/
/g,'>');

JAVA SCRIPT - Rediscovering this with Prototype.bind

Rediscovering this with Prototype bind


Problem

You want to control the scope assigned a given function. 

Solution

Use the bind() method:
window.onload=function() {
 window.name = "window";
 var newObject = {
 name: "object",
 sayGreeting: function() {
 alert("Now this is easy, " + this.name);
 nestedGreeting = function(greeting) {
 alert(greeting + " " + this.name);
 }.bind(this);
 nestedGreeting("hello");
 }
 };
 newObject.sayGreeting("hello");
};


EXPLAIN


 this represents the owner or scope of the function. The challenge associated with this in JavaScript libraries is that we can’t guarantee which scope applies to a function. In the solution, the object has a method, sayGreeting(), which outputs a message and maps another nested function to its property, nestedGreeting.

Without the Function’s bind() method, the first message printed out would say, “Now this is easy, object”, but the second would say, “hello window”. The reason the second printout references a different name is that the nesting of the function disassociates the inner function from the surrounding object, and all unscoped functions automatically become the property of the window object.

What the bind() method does is use the apply() method to bind the function to the object passed to the object. In the example, the bind() method is invoked on the nested function, binding it with the parent object using the apply() method. bind() is particularly useful for timers, such as setInterval().

web page with a script that uses setTimeout() to perform a countdown operation, from 10 to 0. As the numbers are counted down, they’re inserted into the web page using the element’s innerHTML property.

 Demonstrating the utility of bind

If the setTimeout() function in the code sample had been the following:
setTimeout(this.countDown, 1000);

self = this An alternative to using bind(), and one that is still in popular use, is to assign this to a variable in the outer function, which is then accessible to the inner. Typically this is assigned to a variable named that or self:

window.onload=function() {
 window.name = "window";
 var newObject = {
 name: "object",
 sayGreeting: function() {
 var self = this;
 alert("Now this is easy, " + this.name);
 nestedGreeting = function(greeting) {
 alert(greeting + " " + self.name);
 };
 nestedGreeting("hello");
 }
 };
 newObject.sayGreeting("hello");
};


Without the assignment, the second message would reference “window”, not “object”

JAVA SCRIPT - Namespacing Your JavaScript Objects

Namespacing Your JavaScript Objects 


Problem 


You want to encapsulate your data and functions in such a way as to prevent clashes with other libraries.

Solution

Use an object literal, what I call a one-off object, to implement the JavaScript version of namespacing. An example is the following


var jscbObject = {
 // return element
 getElem : function (identifier) {
 return document.getElementById(identifier);
 },
stripslashes : function(str) {
 return str.replace(/\\/g, '');
 },
 removeAngleBrackets: function(str) {
 return str.replace(
/g,'>');
 }
};
var sample = "

testing\changes
";
var result = jscbObject.stripslashes(sample);
result = jscbObject.removeAngleBrackets(result);
console.log(result); //<div>testingchanges</div>


As mentioned elsewhere in this book, all built-in objects in JavaScript have a literal representation in addition to their more formal object representation. For instance, an Array can be created as follows:

var newArray = new Array('one','two','three');

or using the array literal notation:

var newArray = ['one','two','three'];

The same is true for objects. The notation for object literals is pairs of property names and associated values, separated by commas, and wrapped in curly brackets:

var newObj = {
 prop1 : "value",
 prop2 : function() { ... },
 ...
};

The property/value pairs are separated by colons. The properties can be scalar data values or they can be functions. The object members can then be accessed using the object dot-notation:

var tmp = newObj.prop2();

or:

var val = newObj.prop1 * 20;

or:

getElem("result").innerHTML=result;

Using an object literal, we can wrap all of our library’s functionality in such a way that the functions and variables we need aren’t individually in the global space. The only global object is the actual object literal, and if we use a name that incorporates functionality, group, purpose, author, and so on, in a unique manner, we effectively namespace the functionality, preventing name clashes with other libraries.

Advanced 


I use the term one-off with the object literal rather than the more commonly known singleton because, technically, the object literal doesn’t fit the singleton pattern. A singleton pattern is one where only one instance of an object can be created. We can say this is true of our object literal, but there’s one big difference: a singleton can be instantiated at a specific time rather than exist as a static construct, which is what the solution defines.


var mySingleton = (function () {
 // Instance stores a reference to the Singleton
 var instance;
 function init() {
 // Singleton
 // Private methods and variables
 function privateMethod(){
 console.log( "I am private" );
 }
 var privateVariable = "Im also private";
 var privateRandomNumber = Math.random();
 return {
 // Public methods and variables
 publicMethod: function () {
 console.log( "The public can see me!" );
 },
 publicProperty: "I am also public",
 getRandomNumber: function() {
 return privateRandomNumber;
 }
 };
 };
 return {
 // Get the Singleton instance if one exists
 // or create one if it doesn't
 getInstance: function () {
 if ( !instance ) {
 instance = init();
 }
 return instance;
 }
 };
})();
singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log( singleA.getRandomNumber() === singleB.getRandomNumber() );


The singleton uses an Immediately-Invoked Function Expression (IIFE) to wrap the object, which immediately returns an instance of the object. But not just any instance —if an instance already exists, it’s returned rather than a new instance.

The latter is demonstrated by the object’s getRandomNumber() function, which returns a random number that is generated when the object is created, and returns the same random number regardless of which “instance” is accessed.

JAVA SCRIPT - Preventing Any Changes to an Object

Preventing Any Changes to an Object



Problem

You’ve defined your object, and now you want to make sure that its properties aren’t redefined or edited by other applications using the object. 

Solution

Use Object.freeze() to freeze the object against any and all changes:
'use strict';
var test = {
 value1 : 'one',
 value2 : function() {
 return this.value1;
 }
}
try {
 // freeze the object
 Object.freeze(test);
 // the following throws an error in Strict Mode
 test.value2 = 'two';
 // so does the following
 test.newProperty = 'value';
 var val = 'test';
 // and the following
 Object.defineProperty(test, 'category', {
 get: function () { return test; },
 set: function (value) { test = value; },
 enumerable: true,
 configurable: true
 });
} catch(e) {
 console.log(e);
}

EXPLAIN


 ECMAScript 5 brought us several Object methods for better object management. The least restrictive is Object.preventExtensions(obj), , which dis‐ allows adding new properties to an object, but you can still change the object’s property descriptor or modify an existing property value.

The next, more restrictive method is Object.seal(), which prevents any modifications or new properties from being added to the property descriptor, but you can modify an existing property value. The most restrictive method is Object.freeze().

This method disallows extensions to the object and restricts changes to the property descriptor. In addition, Object.freeze() also prevents any and all edits to existing object properties. Literally, once the object is frozen, that’s it—no additions, no changes to existing properties.

The first property modification in the solution code:

test.value2 = "two";

results in the following error (in Chrome):

TypeError: Cannot assign to read only property 'value2' of #

If we comment out the line, the next object adjustment:

test.newProperty = "value";

throws the following error:

TypeError: Can't add property newProperty, object is not extensible


Commenting out this line leaves the use of defineProperty():

var val = 'test';
// and the following
Object.defineProperty(test, "category", {
 get: function () { return test; },
 set: function (value) { test = value; },
 enumerable: true,
 configurable: true
});


We get the final exception, for the use of defineProperty() on the object:

TypeError: Cannot define property:category, object is not extensible.

If we’re not using strict mode, the first two assignments fail silently, but the use of defineProperty() still triggers an exception (this mixed result is another good reason for using strict mode). Check if an object is frozen using the companion method, Object.isFrozen():

if (Object.isFrozen(obj)) ...

JAVA SCRIPT - Preventing Object Extensibility

Preventing Object ExtensibilitY


Problem

You want to prevent others from extending an object. 

Solution

Use the ECMAScript 5 Object.preventExtensions() method to lock an object against future property additions: 


'use strict';
var Test = {
 value1 : "one",
 value2 : function() {
 return this.value1;
 }
};
try {
 Object.preventExtensions(Test);
 // the following fails, and throws a TypeError in Strict mode
 Test.value3 = "test";
} catch(e) {
 console.log(e);
}


EXPLAIN 


The Object.preventExtensions() method prevents developers from extending the object with new properties, though property values themselves are still writable. It sets an internal property, Extensible, to false. You can check to see if an object is extensible using Object.isExtensible:


if (Object.isExtensible(obj)) {
 // extend the object
}


If you attempt to add a property to an object that can’t be extended, the effort will either fail silently, or, if strict mode is in effect, will throw a TypeError exception:

TypeError: Can't add property value3, object is not extensible

Though you can’t extend the object, you can edit existing property values, as well as modify the object’s property descriptor.

JAVA SCRIPT - Using Prototype to Create Objects

Using Prototype to Create Objects


PROBLEM


You want to create a new object, but you don’t want to add all the properties and methods into the constructor function. 

Solution

Use the object’s prototype to add the new properties:
Tune.prototype.addCategory = function(categoryName) {
 this.category = categoryName;
}
EXPLAIN Object is the ancestor for every object in JavaScript; objects inherit methods and prop‐ erties from the Object via the Object prototype. It’s through the prototype that we can add new methods to existing objects:


var str = 'one';
String.prototype.exclaim = function() {
 if (this.length == 0) return this;
 return this + '!';
}
var str2 = 'two';
console.log(str.exclaim()); // one!
console.log(str2.exclaim()); // two!


Before ECMAScript 5 added trim() to the String object, applications used to extend the String object by adding a trim method through the prototype object:

String.prototype.trim = function() {
 return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}


Needless to say, you’d want to use extreme caution when using this functionality. Ap‐ plications that have extended the String object with a homegrown trim method may end up behaving differently than applications using the new standard trim method. To avoid this, libraries test to see if the method already exists before adding their own.

We can also use prototype to add properties to our own objects.the new object, Tune, is defined using function syntax. It has two private data members, a title and an artist. A publicly accessible method, concatTitleArtist(), takes these two private data members, concatenates them, and returns the result. After a new instance of the object is created, and the object is extended with a new method (addCategory()) and data member (category) the new method is used to update the existing object instance.
.

 Instantiating a new object, adding values, and extending the object



function Tune(title,artist) {
 this.concatTitleArtist = function() {
 return title + " " + artist;
 }
}
// create instance, print out values
var happySong = new Tune("Putting on the Ritz", "Ella Fitzgerald");
// extend the object
Tune.prototype.addCategory = function(categoryName) {
 this.category = categoryName;
}
// add category
happySong.addCategory("Swing");
// print song out to new paragraph
var song = "Title and artist: " + happySong.concatTitleArtist() +
 " Category: " + happySong.category;
console.log(song);



The result of running the code is the following line printed out to the console:
"Title and artist: Putting on the Ritz Ella Fitzgerald Category: Swing"
One major advantage to extending an object using prototype is increased efficiency.

 When you add a method directly to a function constructor, such as the concat TitleArtist() method in Tune, every single instance of the object then has a copy of this function. Unlike the data members, the function isn’t unique to each object instance.

When you extend the object using prototype, as the code did with addCategory(), the method is created on the object itself, and then shared equally between all instances of the objects. Of course, using prototype also has disadvantages. Consider again the concat TitleArtist() method. It’s dependent on access to data members that are not accessible outside the object.

If the concatTitleArtist() method was defined using prototype and then tried to access these data members, an error occurs. If you define the method using prototype directly in the constructor function, it is created in the scope of the function and does have access to the private data, but the data is overridden each time a new object instance is created:


function Tune(title,artist) {
 var title = title;
 var artist = artist;
 Tune.prototype.concatTitleArtist = function() {
 return title + " " + artist;
 }
}
var sad = new Tune('Sad Song', 'Sad Singer')
var happy = new Tune('Happy', 'Happy Singer');
console.log(sad.concatTitleArtist()); // Happy Happy Singer

The only data unique to the prototype function is what’s available via this. There are twisty ways around this, but they not only add to the complexity of the application, they tend to undermine whatever efficiency we get using prototype. Generally,

if your function must deal with private data, it should be defined within the function constructor, and without using prototype. Otherwise, the data should be available via this, or static and never changing once the object is created.

JavaScript Calculate Distance Between Two Addresses

JavaScript Calculate Distance Between Two Addresses

 
javascript distance matrix api

In Previous Demo We See How To Use Auto Complete Location, Now From That Example I create a Another Demo Example For How To Calculate Distance Between Two Address.

 ( Note  : Address Must Be Exist in Google Autocomplete Address)

Let's Start!.

First You Need Api Key.

For New Users They Don't Know How To Get Api Key Please Visit this Link to Get YOUR API Key   

Link :  Api Key Link   

Step 1 : I create a html page with two input fields.
Start Address : <input type="text" placeholder="Start Address" id="startaddress">
<br>
End Address : <input type="text" placeholder="End Address" id="endaddress">
Step 2 : Adding a JavaScript function for Adding Google Auto Complete Location Event on Input Fields. On Our Page Ready I call this Function.
	function AutoComplete() {
                 //=============Input Fields 1 and Select it========
               var input1 = document.getElementById('startaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input1);

                 //=============Input Fields 2 and Select it========
               var input2 = document.getElementById('endaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input2);
	}

//===========================Call The Autocomplete Function of Our Page Ready===============
	    google.maps.event.addDomListener(window, 'load', AutoComplete);
Step 3 : Adding Distance Matrix JavaScript Api for Calcuating Distance and Time Taken.
function getDistance(){

	  var distanceService = new google.maps.DistanceMatrixService();
        distanceService.getDistanceMatrix({
                origins: [document.getElementById('startaddress').value],
                destinations: [document.getElementById('endaddress').value],
                travelMode: "DRIVING",
                unitSystem: google.maps.UnitSystem.METRIC,
                durationInTraffic: true,
                avoidHighways: false,
                avoidTolls: false
            },
            function (response, status) {
                if (status !== google.maps.DistanceMatrixStatus.OK) {
                    console.log('Error:', status);
                } else {
                    console.log(response);
                   //=======================Our Text View Where i Display Distance and Time Values===================
                    document.getElementById('distance').innerHTML=response.rows[0].elements[0].distance.text;
                    document.getElementById('distance2').innerHTML=response.rows[0].elements[0].distance.value;
                    document.getElementById('time1').innerHTML=response.rows[0].elements[0].duration.text;
                    document.getElementById('time2').innerHTML=response.rows[0].elements[0].duration.value;

                }
            });
    }
Complete Example Code :
<!DOCTYPE html>
<html>
<head>
	<title>Google Place</title>
	<style type="text/css">
		#distance,#distance2,#time1,#time2{
			background: yellow;
width: 160px;
display: inline-block;
height: 15px;
		}
	</style>
</head>
<body>
Start Address : <input type="text" placeholder="Start Address" id="startaddress">
<br>
End Address : <input type="text" placeholder="End Address" id="endaddress">
<br>
Distance : - In Text Format Value <span id="distance"></span> Only Numeric Value in Metres <span id="distance2"></span>
<br>
Time : - In Text Format Value <span id="time1"></span> Only Numeric Value in Seconds <span id="time2"></span>

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&key= YOUR_API_KEY_HERE"></script>
<script type="text/javascript">

function getDistance(){
	
	  var distanceService = new google.maps.DistanceMatrixService();
        distanceService.getDistanceMatrix({
                origins: [document.getElementById('startaddress').value],
                destinations: [document.getElementById('endaddress').value],
                travelMode: "DRIVING",
                unitSystem: google.maps.UnitSystem.METRIC,
                durationInTraffic: true,
                avoidHighways: false,
                avoidTolls: false
            },
            function (response, status) {
                if (status !== google.maps.DistanceMatrixStatus.OK) {
                    console.log('Error:', status);
                } else {
                    console.log(response);
                    document.getElementById('distance').innerHTML=response.rows[0].elements[0].distance.text;
                    document.getElementById('distance2').innerHTML=response.rows[0].elements[0].distance.value;
                    document.getElementById('time1').innerHTML=response.rows[0].elements[0].duration.text;
                    document.getElementById('time2').innerHTML=response.rows[0].elements[0].duration.value;

                }
            });
    }


	function AutoComplete() {
                 //=============Input Fields 1 and Select it========
               var input1 = document.getElementById('startaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input1);

                 //=============Input Fields 2 and Select it========
               var input2 = document.getElementById('endaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input2);
	}

//======================Register Focus out Listener on Input Fields so we calculate distance and Time
document.getElementById("startaddress").addEventListener("focusout", getDistance);
document.getElementById("endaddress").addEventListener("focusout", getDistance);



//===========================Call The Autocomplete Function of Our Page Ready===============
	    google.maps.event.addDomListener(window, 'load', AutoComplete);

</script>
</body>
</html>

Note : I Calculating Time For DRIVING you can this values by WALKING,BICYCLING. Need To Change Here Only : - travelMode: "DRIVING",


 

Javascript Autocomplete Location Tutorial

Javascript Autocomplete Location Tutorial

JavaScript AutoComplete Location

Sometimes we need a autocomplete Textfield in Web Development where we enter only some values then address will show suggestion now we can implement this Types of Input fields.?

Lets Start Today!.

Step  1 : Visit Google Developer Console .



Google Maps Developer


Step 2 : Select  "Google Places API JavaScript Library"

     LinkGoogle Place Api
Google Place Library


Step 3 : Click on Get Key Then .


Google Api key

Step 4 : Create a new project

Google map project

Step 5 : Copy Key .

Api key

Now Let's Start Our Code . 

index.html

 
<!DOCTYPE html>
<html>
<head>
 <title>Google Place</title>
</head>
<body>
 <input type="text" placeholder="Searc place" id="autocomplete">

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&key=YOUR_API_KEY"></script>
<script type="text/javascript">

 //===================function for set input to google auto complete===================
 function AutoComplete() {
       var input = document.getElementById('autocomplete');
            new google.maps.places.Autocomplete(input);
 }

     //=============Call  function when our page load completes====================
     google.maps.event.addDomListener(window, 'load', AutoComplete);

</script>
</body>
</html>
 
 
autocomplete location input
 Thanks!
1

JavaScript Alternatives Method SetInterval and ClearInterval in Android

JavaScript Alternatives Method SetInterval and ClearInterval in Android

 
Javascript Setinterval

Hello Friends as We know Switching from Web Developers to Android we Stuck in Some Situation of Methods and How we use Such Methods.

Here i Give a simple Method of JavaScript Which is.

SetInterval = for Creating Task Multiple Times Until we Not Stop it.
Clearinterval = For Stoping SetInterval Task.

Lets Create a Demo page and see How it Works?


<!DOCTYPE html>
<html>
<head>
 <title>Set Interval and Clear interval in JavaScript</title>
</head>
<body>
<p>Example of Set interval and Clear interval</p>
<div id="data">
 
</div>
<script type="text/javascript">
 var myHtmlDiv=document.getElementById("data");
 var loop=0;
 var s=setInterval(function(){
  myHtmlDiv.innerHTML+='A Text After 1 seconds <br>';
 
  if(loop==10){
   //stop my setinterval function after 10 times if you want infinte times executing then remove the if condition means no clearinterval method
   clearInterval(s);
  }
  loop++;
 },1000);
</script>
</body>
</html>


Result :

Javascript Setinterval



Now Lets How We Use this Methods in Android?

So We Can use This Method Simply in Android by Using this Methods

 
      final Timer timer= new Timer();
        timer.scheduleAtFixedRate(new TimerTask(){
            @Override
            public void run(){
                testi++;
                if(testi==5){
                    Log.i("Complete","TaskComplete");
                    timer.cancel();
                }
                Log.i("tag", "A Kiss every 5 seconds");
            }
        },0,5000);
0

Jquery (js) validation For 10 Digit Mobile Numbers

Jquery (js) validation For 10 Digit Mobile Numbers




After Testing All Answer not getting success . Some times input take alpha character also.
Here is the last full working code With Only number input also keeping in mind backspace button key event for user if something number is incorrect.

html : 

<input name="phone" id="phone" placeholder="Mobile Number" class="form-control" type="number" required>

Js :

<script>
$("#phone").keydown(function(event) {
k=event.which;
if((k>=96 && k<=105) || k==8)
{
     if($(this).val().length==10)
     {
         if(k==8)
         {
             return true;
         }
         else
        {
             event.preventDefault();
             return false;

         }
    }
}
else
{
     event.preventDefault();
     return false;
}

});
</script>
7

Jquery selectors and basic part 1





Jquery selectors and basics part 1




In this tutorial i will show you how to use jquery selector to select element in DOM (Document Object Model which is our Html Document) and get the value of element ,text of element ,add new value or text or html element to Dom elements.

Let's Get Started.

Example 1 :  id selector
id selector is unique it select only one element in DOM . if we created multiple id element with same name then it will select only select first id element in DOM.

<html>
<head>
<script src=”js/jquery.min.js”></script>

<!--calling local jquery script →

</head>
<body>
<p>Hello</p>
<p id=”demo1”>Jquery</p>
<p id=”demo”>Here this text we will be change by using jquery selector and functions.</p>
<script>
$(document).ready(function(){


$(“#demo”).text(“This is new text “);

//Here # Represent the id and .text() method is used to set text in demo.

$(“#demo1”).html(“<span>World</span>”);

//since .text method only change text if we want to.add html elements inside selected elements then we will use .html() method.

});

//Every jquery function we will not call until our DOM is not ready (document).ready is a function we call our all function inside this .this function defines that our dom is ready now we are ready to call function inside (document).ready.

</script>
</body>
</html>


Example 2 : Class selector
Class is not unique so we can select all element having same class and change text or what we want.


<html>
<head>
<script src=”js/jquery.min.js”></script>

<!--calling local jquery script →

</head>
<body>
<p class=”mdemo”>Hello</p>
<p class=”demo”>Jquery</p>
<p class=”demo”>Here this text we will be change by using jquery selector and functions.</p>
<p class=”mdemo1”>Jquery Class also supports multiple class selector we can select multiple class in a single selector.</p>
<script>
$(document).ready(function(){


$(“.demo”).text(“This is new text “);

//Here (.) Represent the class and .text() method is used to set text in demo.

$(“.mdemo1,.mdemo”).text(“This text change by multiple class selector”);

//multiple class selector can be use by class names separated by comma (,)

});


</script>
</body>
</html>

Example 3 : Element Selector

Element selector selects all element in DOM .

<html>
<head>
<script src=”js/jquery.min.js”></script>

<!--calling local jquery script →

</head>
<body>
<p>Hello</p>
<p id=”demo1”>Jquery</p>
<p id=”demo”>Here this text we will be change by using jquery selector and functions.</p>
<h2>Jquery Multiple element selector </h2>
<span>This text all change using multiple selector</span>
<script>
$(document).ready(function(){


$(“p”).text(“This is new text added in all p tag elements “);

//Here p Represent the tag name  and .text() method is used to set text in demo.

$(“h2,span”).text(“This is multiple text selector “);

//This is multiple jquery selector where elements are separated by comma (,).

});

</script>
</body>
</html>


Example 4 : first last first-child selector

:first - select only first element in dom
:last - select only last element in dom
:first-child - select all elements of first child elements

<script src="js/jquery.min.js"></script>

<!--calling local jquery script -->
</head>

<body>

<br />


<div id="demo1">
Jquery</div>
<div id="demo">
Here this text we will be change by using jquery selector and functions.</div>
<div>

Hello i am first-child selector element

This text not change<br />


</div>
<div>

Hello i am first-child selector element again<br />


This text not change<br />


</div>
<script>

$(document).ready(function(){

$("p:first").text("This is new text added in first p tag element ");

$("p:last").text("this is text added in last p elements");

$("div:first-child").text("This is first child selector first child in div element");
//Here p Represent the tag name  and .text() method is used to set text in demo.


});

</script>
4