Showing posts with label html. Show all posts
Showing posts with label html. Show all posts

Tuesday, 27 February 2018

AngularJS Hello World Example

Background

AngularJS is a client-side javascript framework developed by Google which can interact with HTML. It helps to easily create and maintain SPA (Single page applications)

Some of its features are -
  1. Helps create responsive applications
  2. Provides MVC capabilities
  3. Dependency injection
  4. Powerful and flexible with less code to write
NOTE: AngularJS is a very old framework. The first version is called AngularJS. Later versions are just called angular. You can see the detailed release history - https://github.com/angular/angular.js/releases. This post will try to explain a simple Hello World program in Angular JS. This is mainly for projects that are already on it. If you are starting a new project I would highly recommend to go with later angular versions. You can visit https://angular.io/  for the same.


 AngularJS Hello World Example

Let's start by writing our HTML file. Create a folder where you can store your code files. Now in this folder create two files -
  1. helloWorld.html
  2. helloWorld.js
And add following content to it -

helloWorld.html:

 <html>
    <head>
        <title>Hello World!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>       
        <script type="text/javascript" src="helloWorld.js"></script>
    </head>
    <body ng-app="helloWorldApp">

        <div ng-controller="helloWorldAppController" ng-init="init()">
                  <p>Enter Message here : <input type="text" ng-model="message"></p>
                   <p>Entered Message :  {{ message }}!</p>
        </div>

    </body>
</html>



helloWorld.js  :

 (function(){
    'use strict';
    console.log("In JS");
    var helloWorldApp = angular.module("helloWorldApp", []);
    helloWorldApp.controller("helloWorldAppController", function($scope) {
        $scope.init = function() {
            console.log("Init method called");
            $scope.message = "Hello World!";
        }
    });

})();



Now you can simply open the helloWorld.html file and see the changes. 

 

Understanding the code

Now that we saw the behavior let's try to understand the code.

In our code we have initialized a angular module using ng-app directive. In the javascript we get this module using andular.module() function.  Inside a module you can have multiple controllers controlling various parts of your html. In our case we have defined a controller called helloWorldAppController that controls the div element we have defined. In the javascript we are getting this controller from our module.


Once you have the controller you can define varibles and functions that you can access in the HTML controller by this particular controller. You can also notice the variable called "message" that is defined in the controller is accessible in the HTML using {{message}} syntax. You would also see the binding exist using the ng-model syntax. This is called two way binding. So value changed in the input field is immediately visible in same HTML using {{message}} syntax as well as the controller using $scope.message. In the html where we have declared controller we have also specified init method using ng-init and you can see this menthod defined in controller using $scope.init. This is called when controller is initialized and this function in the controller script initialized messages variable to "Hello World!" that is reflected in HTML page.



Lastly we have injected our controller script (helloWorld.js ) and  angular js script in the html for our angular js code to work. Make sure angular script is the 1st one added.

All keywords starting with ng- are angular directived.
  • ng-app
  • ng-controller
  • ng-init
  • ng-model 

Saturday, 11 June 2016

Greasemonkey script to replay Youtube videos once they finish

Background

In one of the previous post we saw a Greasemonkey script to block Game of thrones spoiler on facebook.  In this post we will see Greasemonkey script to replay Youtube videos once they finish. And we will see how to do this from very beginning including installing the plugin.



Setup

First step is to install the  Greasemonkey  plugin in firefox. There is a similar plugin in chrome called Tampermonkey. For demo purposes we will use firefox. So go ahead and install the plugin. URL is -




Once installed you can see it's icon besides navigation bar. There you can click to create a new user script -



Then you should see a window where you can create your script.



You can find the actual script on my github account - 

Related Links

Sunday, 15 November 2015

Create your own chrome plugin example demo

Background

In this post we will see how to create chrome plugins. We will see a simple demo plugin example in which when we click on the plugin icon we will will see the URL of current active TAB.


Getting Started

Create a directory where you will create files needed for your plugin. Lets call it "chrome_plugin" directory. 
  • First and foremost what you need is a file called manifest.json. This file essentially tell chrome browser details about your plugin like it's name, it's version, what permission it needs and the actual code files.

For our demo this file looks something like below -

{

  "manifest_version": 2,
  "name": "Open Source For Geeks Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },

  "permissions": [
   "activeTab"
   ]

} 


Contents of manifest.json file are basically json with plugin details. As you must have notices by now it references two essential resources -
  1. icon.png
  2. popup.html
  • Go ahead and put icon.png and create a file called popup.html is the same directory - "chrome_plugin".




 If you do not have the icon you can use the one above. It's 20*20 pixels icon.

  • Next edit popup.html with following contents - 

<!doctype html>

<html>
  <head>
    <title>OSFG Chrome Demo Plugin</title>
    <script src="popup.js"></script>
  </head>
  <body>

    <h1>Current Site URL : </h1>
    <br/>
    <div id="currentTabUrl"></div>
  </body>
</html>


Again a simple HTML file but note it asks to load a popup.js javascript file.

  •  Go ahead create a file called popup.js and add following contents to it -

function getCurrentActiveTabUrl(callback) {

  var tabQueryInfo = {
    active: true,
    currentWindow: true
  };

  chrome.tabs.query(tabQueryInfo, function(tabs) {
    var currentTab = tabs[0];
    var url = currentTab.url;]
    console.log(url);
    console.assert(typeof url == 'string', 'currentTab.url should be a string');
    callback(url);
  });

}
  

function renderOutput(outputText) {
  document.getElementById('currentTabUrl').innerHTML = "<a href='" + outputText + "'>" + outputText + "</a>";
}

document.addEventListener('DOMContentLoaded', function() {
  getCurrentActiveTabUrl(function(url) {
        renderOutput(url);
  });
});



Take some time to see the javascript code above. It essentially reads the current active TAB url and shows it in the popup in an anchor tag. And there you go your first chrome plugin is all set to be deployed.

NOTE : Most of the chrome APIs are asynchronous. So you cannot do something like -

var currTabUrl;
chrome.tabs.query(queryInfo, function(tabs) {
  currTabUrl= tabs[0].url;
});
alert(currTabUrl); // Will show "undefined" as chrome.tabs.query is async.


Deploying your chrome plugin

Deploying your plugin is again quite simple
  • Go to chrome://extensions/ URL is your chrome browser. Here you should see list of existing chrome extensions you are using.
  • Make sure "Developer Mode" check box is selected.

  • Now click on "Load Unpacked Extension" and select the folder you have plugin in - "chrome_plugin" directory is this case.

  • Now open any tab. You should see the plugin with icon you had put in the directory just besides Omnibox. Go to any URL and then click on the plugin icon.  



 You can download this sample chrome plugin code from here.

Appending custom methods to chrome right click Menu

Lets see how we can add custom functions to right click menu. Here is what we are going to do -  we will add a new option on right click which enables to search selected text in google maps.


The new manifest.json file looks like the following - 

{
  "manifest_version": 2,

  "name": "Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",
  
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "activeTab",
   "contextMenus"
   ]
}

Notice couple of differences here
  1. There is a new permission added called contextMenus. This basically lets you operator om chrome context menus.
  2. There is a new key added called background that basically tells chrome about background processes. You can specify scripts or page here.
 Next in background.js add following code

function searchgooglemaps(info)
{
 var searchstring = info.selectionText;
 chrome.tabs.create({url: "http://maps.google.com/maps?q=" + searchstring})
}

chrome.contextMenus.create({title: "Search Google Maps", contexts:["selection"], onclick: searchgooglemaps});


 And you are done. Reload the extension.



When you click on "Search Google Maps" you should see a new Tab opening with google maps and a search location of your desired selected String.


Related Links

Saturday, 7 November 2015

How To Add Google+ Follower Widget in your website or WordPress/Blogger blogs

Background

It been almost two and a half years since I am blogging on bloggers and I though it's time I see what wordpress has to offer. To surprise the UI is kind of complex and have limited widget support. Also it does not allow you to add plugins. After a few customizations I decided to add a Google+ followers widget but there unfortunately isn't one. Hence this post. It's a simple html/javascript. So you can plug it into any website. Bloggers as you know already has a widget for this.


How To Add Google+ Follower Widget in your blog/website

  • First create a simple text/html widget
  • Next add following javascript code to it
<div class="g-plus" data-action="followers" data-height="300" data-href="https://plus.google.com/102342595285863325267" data-source="blogger:blog:followers" data-width="320">
</div>
<script type="text/javascript">
      (function() {
        window.___gcfg = {'lang': 'en'};
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
      })();
    </script>


  • Next Save and Publish. You should now be able to see the widget on your wordpress site.
NOTE : Make sure you use your own G+ page URL as the value of data-href attribute in div tag.

You should see it get rendered as follows -


Saturday, 4 July 2015

Understanding CSS Specificity

Background

Life is good when you have a small web project with limited and simple CSS but as your project size grows and more CSS is to be applied complexity increases. 

In there are two or more conflicting CSS rules that point to the same element then your web browser will apply some rules to figure out which rule should be given higher precedence and be applied.

We term this rule weight as selectivity. More the selectivity more is the preference given to that rule.

Example


Enough of the theory lets see an example. Consider following html

<html>
    <head>
        <style type="text/css">
            .redbutton{color: red;}
            .bluebutton{color: blue;}
             #innerdiv input {color: green;}
        </style>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
        <script>
            function changecolor()
            {
                jQuery("#colorbutton").addClass("bluebutton");
            }
        </script>
    <title>Testing CSS Selectivity</title>
    </head>
    <body>
        <div id="ouderdiv">
            <div id ="innerdiv">
                <input id="colorbutton" type="button" class="redbutton" value="Click Me" onclick="changecolor()"/>
            <div>
        <div>
    </body>
    
</html>

What do you expect will be the color of the button on page load and on click ? Well think a bit and then try it out. Paste above html in a file and open it in any browser. Observer the color, click on the button and then observer the color again. 

Before Cick

After Click


Whats happening?

Have questions? Will be answered soon. Lets take a step back and review our html code. We have a button. For this button we provided a class called redbutton (which should make the button red) and then on click we are dynamically changing the class to bluebutton (which should make the button blue). But none of these worked. It is still green. As you must have guessed correctly by now there is another css rule that is getting applied.

#innerdiv input {color: green;}

But why? Because CSS specificity of this rule is more than other class rules that we have defined. Next natural question - How is css specificity determined by the browser?

How is CSS specificity calculated?

There are some basic rules to determine specificity of a CSS rule.

Determination of specificity of a CSS rule depends on what type of selector is used
  • HTML selector (Eg input) has specificity 1
  • Class selector (Eg .redcolor) has specificity 10
  • ID selector (Eg. #innerdiv) has specificity 100
And if you have multiple such selectors in an CSS rule then their individual specificity just get added to form rule specificity that is used by the browser to determine precedence.

Here are few example
  • a - specificity 1 (1 HTML selector)
  • div a - specificity 2 (2 HTML selectors,  1+1)
  • div .someclass - specificty 11 (1 HTML selector and 1 class selector, 1 + 10)
  • div #someid - specificity 101  (1 HTML selector and 1 id selector, 1 + 100)  
  • div #someid .someclass - specificity 111  (1 HTML selector and 1 id selector and 1 class selector, 1 + 100 + 10)  

and so on.... Hope you got the point.

Note : If two conflicting rules have same selectivity then the one applied or parsed later is picked up.

So lets apply it to our rules.

  • .redbutton{color: red;} - specificity 10 (1 class selector)
  • .bluebutton{color: blue;} - specificity 10 (1 class selector)
  • #innerdiv input {color: green;} - specificity 101 (1 id selector and 1 html selector, 100+1)
So how can we leverage this information now? Lets increase the specificity of first two color rules now.

  • #innerdiv .redbutton{color: red;} - specificity 110 (1 id selector and 1 class selector,100+10)
  • #innerdiv .bluebutton{color: blue;} - specificity 110 (1 id selector and 1 class selector,100+10)
  • #innerdiv input {color: green;} - specificity 100 (1 id selector and 1 html selector,100+1)

With above rules now test our page again.

 Before Click




 After Click




That's all with CSS selectivity. Ideal scenario is when no two rules conflict but in my personal experience conflicting rules are bound to happen for a big web project. This is when this rules come handle. Let me know if you still have any questions :).

Monday, 6 October 2014

Web scrapping using Jsoup Java library

Background

Websites are generally intended to humans to visit and go through it's content but we can very well automate this process. What happens when we hit a URL in the browser ? A GET or a POST request is sent to the server, server authenticates the request (if any) and replies with a response - typically a HTML response. Our browser understands the response and renders it in human readable form. If you know this it is no problem for a programmer to automate a REST API using CURL or HTTPClient , parse the response and fetch the interested data. 


Let me go a few steps ahead. Today we have many libraries in many languages that automate the process of sending requests, parsing the response and getting the data you are really interested in. They are know as Web Scrappers and the technique is know as Web scrapping.


Even see a text image validation or captcha before entering a  website ? Well it's there to ensure you are a human and not some bot (automated scripts like the one we will see in this post). Well then one would ask why do we need this web scrapping ? Heard of Google ? How do you think it shows you so accurate search result based on your search query or rather how does it know that a relevant page exists in first place? Yeah well......... web scrapping. Answering how does it get so accurate results is a bit tricky as it involves ranking algorithms and in depth knowledge of data mining. So lets skip that for now :)



Note

Web scrapping is not strictly ethical! and may be termed as hacking in some scenarios. So please check the legal policies of the website before trying anything like that. My intentions here are purely academic in nature :)

So do go ahead play with new libraries, new APIs, learn new things... but by staying withing the rules.

Web scrapping using Jsoup




So coming back to our title of the POST. we are going to use Jsoup library in Java to scrap web pages. As per their homepage info - 

  • jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.
  • jsoup implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do.
    •  scrape and parse HTML from a URL, file, or string
    • find and extract data, using DOM traversal or CSS selectors
    • manipulate the HTML elements, attributes, and text
    • clean user-submitted content against a safe white-list, to prevent XSS attacks
    • output tidy HTML jsoup is designed to deal with all varieties of HTML found in the wild; from pristine and validating, to invalid tag-soup; jsoup will create a sensible parse tree.
  • jsoup is designed to deal with all varieties of HTML found in the wild; from pristine and validating, to invalid tag-soup; jsoup will create a sensible parse tree.

Setup & Goal

Goal :  I am going to scrap my own blog - http://opensourceforgeeks.blogspot.in and then print all the post titles that come up in the 1st page.


Setup :

I am going to use Ivy dependency manager and Eclipse as I do for most of my projects.
I am using jsoup version 1.7.3. You can see the version in the maven repository. So my Ivy file looks something like below  -

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="OpenSourceForGeeks"
        module="WebScrapper"
        status="integration">
    </info>
    
    <dependencies>
    
        <dependency org="org.jsoup" name="jsoup" rev="1.7.3"/>
        
    </dependencies>
   

</ivy-module>



So go ahead build your project, resolve and add Ivy library. This would download the library and set it in your classpath. Create classes, packages to suit your requirement. My project structure looks like -



Code :

Add the following code in your WebScrapper class -

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 
 * @author athakur
 *
 */
public class WebScrapper {
    
    public static void main(String args[]) {
        WebScrapper webScrapper = new WebScrapper();
        String page = webScrapper.getPageData("http://opensourceforgeeks.blogspot.in/" );
        Document doc = Jsoup.parse(page);
        Elements elements = doc.select(".post-title > a");
        for(Element element : elements) {
            System.out.println("POST TITLE : " + element.childNode(0).toString());
        }
    }

    
    
    public String getPageData(String targetUrl) {
        URL url = null;
        URLConnection urlConnection = null;
        BufferedReader reader = null;
        String output = "";
       
        try {
            url = new URL(targetUrl);
        }
        catch(MalformedURLException e){
        System.out.println("Target URL is not correct. URL : " + targetUrl);
        return null;
        }
       
        try {
            urlConnection = url.openConnection();
            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String input = null;
            while((input = reader.readLine()) != null){
                output += input;
            }
            reader.close();
        }
        catch( IOException ioException) {
            System.out.println("IO Exception occurred");
            ioException.printStackTrace();
            return null;
        }
       
        return output;
       
    }

    
}



Go ahead, run the program and check the output.

Output

POST TITLE : What is object-oriented programming? - By Steve Jobs
POST TITLE : Experimenting with Oracle 11g R2 database
POST TITLE : Difference between DML and DDL statements in SQL
POST TITLE : Difference between a stored procedure and user defined function in SQL
POST TITLE : IO in Java (Using Scanner and BufferedReader)

Explanation

If you are aware of HTML/CSS  code is quite self explanatory. All you have to understand is how the select query works. If your HTML element had id="myId" we can refer it as #myId. Same goes for class. if your element had class="myClass" we can refer it as .myClass. Select query work exactly the same way. For more on syntax refer - 

In the select query that I have used I am simply saying parse the page and get me all the elements that are a(anchor tag) and are children of Element with class = "post-title". Display text of the anchor tag is the data we are interested in.

How did I know what class or id to search ? Well we need to do some manual searching. In my case first I parsed the whole page, printed it and searched for the pattern I was interested in. You can do the same by going to a page and inspecting the page source code - via browser.

Related Links


Sunday, 14 September 2014

Difference between block level elements and inline elements in HTML

Background

Most of you might already know HTML stands for HyperText Markup Language and is the standard markup language used to create web pages. HTML consists of elements. Most of the elements have stating and ending tag. For eg. <div></div>. Some don't need. For eg. <br />. You can read more about it on Wikipedia or w3schools. In this post I am going to cover what are basic blocks in a HTML.

Blocks in HTML

Elements in HTML are categorized into two types- 
  1. block level elements
  2. inline elements

When block level elements are rendered in a webpage they generally begin and end with a new line. For example <ul>, <table>, <h1>, <p>  tags. Inline elements comprise of tags that come inside(nested) block level element tags. For example <a>, <img>, <b>, <td>.

Difference

Picking this up directly from the W3 documentation -

Certain HTML elements that may appear in BODY are said to be "block-level" while others are "inline" (also known as "text level"). The distinction is founded on several notions:

  • Content model : Generally, block-level elements may contain inline elements and other block-level elements (Exception to this on paragraph/p tag). Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
  • Formatting : By default, block-level elements are formatted differently than inline elements. Generally, block-level elements begin on new lines, inline elements do not.

Below are some details on <div> and <span> elements which I have directly picked up from W3schools.I have used them a lot in web pages and JSPs but never knew the basic difference between them and their intended purpose.

<div>  element

  • The HTML <div> element is a block level element that can be used as a container for grouping other HTML elements.
  • The <div> element has no special meaning. Except that, because it is a block level element, the browser will display a line break before and after it.
  • When used together with CSS, the <div> element can be used to set style attributes to large blocks of content.
  • Another common use of the <div> element, is for document layout. It replaces the "old way" of defining layout using tables. Using <table> elements for layout is not the correct use of <table>. The purpose of the <table> element is to display tabular data.

<span> element

  • The HTML <span> element is an inline element that can be used as a container for text.
  • The <span> element has no special meaning.
  • When used together with CSS, the <span> element can be used to set style attributes to parts of the text.


Nesting block level elements inside the <p> tag… right or wrong?

As the documentation clearly says

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

You cannot use block level elements inside paragraph tag. Well no body stops you from adding it but here's what will happen  - opening <div> or any other block level tag will automatically close the <p> element.

Related Links



Saturday, 13 September 2014

Method overloading in Javascript

Background on method overloading

If you are from java or C# background then you must be familiar with the concept of method overloading. You can refer to following post on method overloading in java


Just to summarize (as far as java is considered) two methods are said to be overloaded if they have same method name but different method signatures. Also note method signature is the name of the method plus the number and types of arguments. Signature has nothing to do with return type. Also two methods cannot have same signature.

So for example

public void foo(String arg1);
public void foo(String arg1, String arg2);

are overloaded methods. Also note method overloading is a compile time phenomenon. Which method is to be used for execution is decided at compile time depending on the method signature.

Okay enough of Java overloading background. Lets head to javascript.



Method overloading in Javascript

Method overloading is not possible in Javascript in strict sense!

yeah that's right. You should not do something like

function foo(x)
{
  //some logic 
}

function foo(x,y)
{
  //some logic 
}

Why have i written "should not" rather than "cannot" is because no body can stop you from writing the methods above. It's just that it will not serve it's intended purpose. Why not ?-

The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.

So  foo(x,y) wold override foo(x) in above case.  So if I call method as foo(1) and as per what I have written above foo(x,y) will overwrite foo(x) why is there no some kind of error or Exception ? 

Well because when you specify arguments in the round brackets - they are just like synthetic sugar coating on the real arguments. This is where there is another JavaScript feature, which a lot beginners miss out on. In any JavaScript method, the arguments passed into the method are accessible via an Object array with the name arguments.

So lets say you now have a method

function func1(a,b,c)
{

   //some logic 
} 

and you call func1(1,2,3,4) then a=1(arguments[0]), b=2(arguments[1]),c=3(arguments[2]) and you c(arguments[3]). So as I said arguments inside round brackets are just to improve the functionality.


In fact for above method you can also call it like func1(1,2) and in this case arguments c and d will be undefined. Following the same argument above you can have a function defined with no argument and call it with any number of arguments.

You can check any variable if it is undefined in the following way (using typeof ) -


function func1(a,b,c,d)
{
   if(typeof a == 'undefined')
   {
      alert("a is undefined"); 
    }
     // and so on... 
}


So how do we resolve this issue ?

One of the way I think is suitable for most of the case is follows -

Lets say you have method

function foo(x)
{

} 


Instead of overloading method which is not possible in javascript you can define a new method

fooNew(x,y,z)
{
}


and then modify the 1st function as follows -

function foo(x)
{
  if(arguments.length==2)
  {
     return fooNew(arguments[0],  arguments[1]);
  }
} 

If you have many such overloaded method consider using switch than just if-else statements.

Related Links


Wednesday, 25 June 2014

How to Use JSON Objects With Twitter Bootstrap Typeahead

Background

Bootstrap is a free collection of tools for creating websites and web applications. It contains HTML and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions. (More on Wiki).

You can visit their official site for more details. You need to download it and add the css file and javascript file to your project. In this post i am going to cover how can we use JSON Object to autocomplete text fields.




To the Code.....

Add the following in your java script. You can put all typeahead calls in a single function and then call that function from your javascript in the HTML (or JSP) page.

var states = [];
var    map = {};
$('#search').typeahead({

    minLength: 0,

    source : function(query, process) {        

        states = [];

        map = {};
        //hardcoding this JSON but this would technically come from server
        var data = [
        {"stateCode": "CA", "stateName": "California"},
        {"stateCode": "AZ", "stateName": "Arizona"},
        {"stateCode": "NY", "stateName": "New York"},
        {"stateCode": "NV", "stateName": "Nevada"},
        {"stateCode": "OH", "stateName": "Ohio"}
    ];

    $.each(data, function (i, state) {
        map[state.stateName] = state;
        states.push(state.stateName);
    });

    process(states);
    },
    matcher: function (item) {
        //If user enters * show all possible entries
        if(this.query.trim().toLowerCase() == "*") {
            return true;
        }
        if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
            return true;
        }
    },
    updater: function (item) {
        //If you want to do something prior to updating value 
        selectedState = map[item].stateCode;
        return item;
    },
    sorter: function (items) {
        return items.sort();
    },
    highlighter: function (item) {
       // implementation
    },

});

Also you can override your typeahead class as follows for better looks

.typeahead {
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
}


Thats it for the autocomplete feature of twitter bootstrap. You can make ajax call to get the JSON data as follows

function getData(url, data, successCallback, errorCallback) {
    var requestType = "POST";
    var dataType = "json";
    make_ajax_call(url, data, requestType, dataType, successCallback, errorCallback);
}

function make_ajax_call(url, data, requestType, dataType, successCallback, errorCallback) {
    
    var request = {
        url : url,
        type : requestType,
        data : data,
        dataType : dataType,
        success : successCallback,
        error : errorCallback,
        async : false
    };
    jQuery.ajax(request);

}
You can import jquery using

<script src="http://code.jquery.com/jquery.js"></script>

Saturday, 7 June 2014

Open a new web page to show content using javascript.

Goal

In my last post I showed how can we get started with Web development by making a simple "Hello World" HTML web page. In  this post we will see how can we open a new window to show some content.

Getting Started

 Lets first create a web page that meets our requirement and then we can look at the javascript part.
Again create a file called index.html and add following content in it.

<html>
<header><title>Open Source For Geeks Tutorial</title></header>
<body>
<center>
<h1>Open Source For Geeks Demo</h1>
<table>
<caption>Demo Table</caption>
<tr>
<td>
Enter Some Text : 
</td>
<td>
<input type="text" name="textContent">
</td>
</tr>
<tr>
<td>
Click to Submit : 
</td>
<td>
<input type="button" value="Submit">
</td>
</tr>
</table>
</center>
</body>
</html>



Now view the page in the browser. You should see something like below


What we want to achieve is to enter some text in the text field then click the Submit button and we should be able to see the text content entered on a new page.

Following code is fully functional with javascript function.

<html>
<header>
<title>Open Source For Geeks Tutorial</title>
<script>
function openNewPage() {
    top.consoleRef=window.open('','myconsole',
        ',menubar=0'
       +',toolbar=1'
       +',status=0'
       +',scrollbars=1'
       +',resizable=1');
    top.consoleRef.document.writeln(
      '<html><head><title>Open Source For Geeks Tutorial</title></head>'
       +'<body bgcolor=white onLoad="self.focus()">'
       + '<h1><b><i>This is a new Window!</i></b></h1>'
       + '<textarea rows="40" cols="100">'
       + document.getElementById("SubmitTextID").value
       + '</textarea>'
       +'</body></html>'
     );
    top.consoleRef.document.close();
}
</script>
</header>
<body>
<center>
<h1>Open Source For Geeks Demo</h1>
<table>
<caption>Demo Table</caption>
<tr>
<td>
Enter Some Text : 
</td>
<td>
<input type="text"  id="SubmitTextID" name="textContent">
</td>
</tr>
<tr>
<td>
Click to Submit : 
</td>
<td>
<input type="button" value="Submit" onclick="openNewPage()">
</td>
</tr>
</table>
</center>
</body>
</html>


and lets try it out

Enter some text in the text field and click Submit button. The entered text should now come in the new window.



Now click the submit button. New Window will open as shown below


That was it! It's that simple.Just a java script function. There is a reason I have put the content inside <textarea> tag. This is because you can even have tags inside text area and they will be displayed as tag. That means if your text has <b> in it same will be displayed and will not be interpreted as bold tag. This was just a simple example but you can show complex data that is fetched from the server. You can also show some xml content in it.

Carefull!!!!

Be careful though. document.writeln() method takes a html input. So all your escaped characters will be "un-escaped". Meaning if your display text contains something like &amp; it will be replaced by  & and shown. If you really want to show the escaped characters you need to do something like below - 

function writeConsole(content,idx) {

     top.consoleRef=window.open('','myconsole' + idx,

        ',menubar=0'

       +',toolbar=1'

       +',status=0'

       +',scrollbars=1'

       +',resizable=1');

     top.consoleRef.document.writeln(

      '<html><head><title> Generated Content</title></head>'

       +'<body bgcolor=white onLoad="self.focus()">'

       + '<textarea rows="500" cols="500">'

       + '</textarea>'

       +'</body></html>'

     );

     top.consoleRef.document.close();

    

     var doc = top.consoleRef.document;

     var textarea = doc.getElementsByTagName('textarea')[0];

     textarea.value = content;

    }


I encountered this scenario and corresponding stack overflow question asked is

HTML Hello World Tutorial

Introduction

Our live as we are living now would not be the same without the internet. What we see while browsing internet are called web pages. What we use to browse these pages is called a browser (client). These pages are written using various technologies like HTML, CSS, JavaScript, JQuery etc. which are client side technologies. There are various backed (server side) technologies like JSP, Servlets that are used to build application that are deployed on the servers eg. Tomcat which help server users/clients request to browse a particular page. What user types in an address bar to fetch a web page is called URL(Universal resource locator). For example you may type http://google.com/. What you see before colon ':' (i.e http or Hypertext Transfer Protocol) is the protocol used to communicate with the server. It can also be https which is secure version of http protocol.You may see the use of this protocol when you browse a page to do some secure action like payments or transactions. Both HTTP and HTTPS fall under application layer in OSI model. Both of them have TCP as their underlying protocol. So basically when browser it to request a web page it first creates a TCP connection with the server and then uses HTTP or HTTPS to get the required pages to display.

Goal

Most of the basic tutorials can be found on W3Schools. Prior to moving to some advance tutorials on web development let me provide this basic Hello World HTML tutorial. Here we will simply crate a web page and open it in our browser that shows "Hello World!" text.

Getting Started

  • Create a file name index.html . Notice the extension html. It is required so that the browser and OS understands it is a web page and will be opened in a web browser.
  • Next add the following text in your file

    <html>
    <header><title>Open Source For Geeks Tutorial</title></header>
    <body>
    <center>
    <h1><b><i>Hello World!!</i></b></h1>
    </center>
    </body>
    </html>
    
  • Simply double click the file. It should open up in your default browser and should look like below

  • See how easy that was? Web pages that you visit in day to day life are much more complex. They have animations, dynamic contexts, logins etc but it all starts from Hello world :)

Understanding the language

  1. HTML is stands for Hyper Text Markup Language. You have bunch of tags that the browser understands and renders.
  2. Notice the <html></html> tag. This is the root element of your web page. Or kind of was. Modern browsers detect the html page even if this tag is not present.
  3. Next comes your tag <head></head> and <body></body>. As the name suggests head tag has your meta info like page titile. you can put it under <title></title> tag in your head. Notice the text on the tab in above image. Your java scripts also go in this head section.
  4. Body as the name suggests has your actual page content to be shown. Here we are simply displaying "Hello World !!" text. But notice the font ? Looks different ? That is because I used some tags.
  5. <center><center/> tag tell the browser that the element/tag that come in between must be rendered in the center of the browser. <b> is for bold and <i > is for italics. <h1> is the size tag that shows text with different size. You can go ahead and try <h2>... etc.
As I told earlier you will find much help on W3Schhools.  So do go through it if you are beginning with Web development. Let me know if you still have any doubts.
t> UA-39527780-1 back to top