Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Friday, April 6, 2012

Hello world in Node.js

First you need to install node.js. I'm running ubuntu 11.10 and I also needed to
$ apt-get install openssl libssl-dev

Create a file named test.js, and copy and paste the code below

//how to run the server output hello world
var http = require('http');

var server = http.createServer(function(request, response){
response.writeHead(200, {
'Content-type' : 'text/plain'
});
response.end('hello world');
});
// where the host in located
server.listen(8000); //see the code below
console.log('listening on http://127.0.0.1:8000'); //echo in the terminal whatever you want
To start the server go to the terminal and the run the script you created by typing
$ node test.js
Now go to the browser and enter http://127.0.0.1:8000 and your done.

Resource: http://net.tutsplus.com/tutorials/javascript-ajax/this-time-youll-learn-node-js/

Wednesday, February 29, 2012

Programming Languages Comparison

Programming languages are alike. If you know how to program in one language changes are you know how to program in other languages. However the only difference is the syntax. I always wanted a chart that showed this and I finally found it hyperpolyglot.org.

Thursday, February 9, 2012

Whitelist. A Javascript Object

Blacklisted are those who access were removed and whitelisted are those who are specifically granted access or privilege. Below is a Javascript whitelist object.

//START OBJECT
var white = {
list: new Array(),
request: function(permitted){
for(var value in this.list){
if(permitted == this.list[value]){
return true;
}
}
}
}
white.list = ['jon','max']; //set who has can have access
//END

//Lets test the object
if(white.request('jon')){
//if access granted
alert('welcome VIP')
}else{
//not granted access
alert('Access was never granted to you');
}

Friday, November 18, 2011

Javacript Chaining

Javascript chaining pattern is the process of stringing methods/functions together without
having to recall the object. jQuery made this pattern famous.

jQuery Example:
$('div').css('color','red').html("I'm a second chain");

How to create your own:

var chain = {
first: function(){ //a method
alert("I'm first");
return this; //this is the secret
},
second: function(){ //another method
alert("I'm second");
return this; //this is the secret
}
}

//The chain
chain.first(); //alerts only the first
chain.first().second().first(); //alerts first,second and first(order insensitive)
This benefits you because the object doesn't need to be rewritten every time you want to use a method, resulting in less code. Call it once and add the methods to it.

The secret lies in returning the object (this). It resets the object allowing the next chain to use it.

Thursday, November 10, 2011

Whitelist. A Javascript Object

Blacklisted are those who access were removed and whitelisted are those who are specifically granted access or privilege. Below is a Javascript whitelist object.

//START OBJECT
var white = {
list: new Array(),
request: function(permitted){
for(var value in this.list){
if(permitted == this.list[value]){
return true;
}
}
}
}
white.list = ['jon','max']; //set who has can have access
//END

//Lets test the object
if(white.request('jon')){
//if access granted
alert('welcome VIP')
}else{
//not granted access
alert('Access was never granted to you');
}

Monday, October 31, 2011

Best Javascript Debugger

While in production the best javascript debugger is the line of code below.
window.onerror = function(error,file,line){alert(error+'\n'+file+'\n'+line);}
Add it to the beginning of your script and the error will be alerted. The alert will have the error, file name and what line the error occurred on. Make sure to remove it once out of production mode.

Friday, October 28, 2011

Example: Small Javascript library

In jQuery you can call a function like $.ajax() and insert an object inside of it and each property does an action. Below I have simplified an example to demonstrate how this works.


//create the library
var lib = {
sum: function(num){ //create a method
var num1 = num.a;
var num2 = num.b;
this.result = num1 + num2;
},
table: 'table' //this is a random property, its not necessary
}

//call a method and create an object inside of it to send data to the library
lib.sum({
a : 1, //these are the properties that will be processed
b : 4
});
alert(lib.result); //output 5



//above is similar to the jQuery AJAX below
$("#input").keyup(function(){
var data = $('#input').val();
$.ajax({
url:"models/post.php", //these are the properties that will be processed
type: "post",
data: ({name:data, age:'15'}),
success:function(result){$(".result").html(result);}
});
});



jQuery Deconstructed is a rather nice way to look through the source. You will learn alot by studying it.

Wednesday, October 19, 2011

Web Charts - PHP and Javascript

pChart.net and jqPlot.com are two different libraries that allow you as a web developer create beautiful charts and graphs.

jqPlot is a javascript library that uses jQuery. jqPlot is great because it can pull data directly from multiple mediums such as csv, txt, json and so on. However it sucks because different charts may need different plugin files and you need to make sure the right script is included, but its still simple.

pChart is a PHP libray that uses its GD library. You may need to configure your php depending if this library is installed or not. pChart is a object oriented class that creates an image of a chart on the webpage. The webpage becomes an image which will not let you output any html. The only way you can link to the chart is by using <img> or <iframe> tag. Whats great is that you can create an image that can be save but what sucks is that you may not be able to use AJAX and it takes a huge load on your CPU.

Friday, October 14, 2011

Example: JSON

WARNING!! Do not test it in Chrome it will not work. Only live.

JSON: is used for data storage and can be an alternative to XML.

HTML:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script>
window.onerror = function(a,b,c){alert(a+b+c);} //if error alert
$(document).ready(function(){
//Short hand
$('button').click(function(){
$.getJSON("info.js", function(json) {
alert(json.name[1].first)
});

//Long
$.ajax({
async: false,
url: 'info.js',
dataType:'json',
success: function(json) {
ret = json.name[1].first;
}
});
});
});
</script>

<p>hello</p>
<button>Click Me</button>

JSON (info.js) - everything must have double quotes except numbers. You cannot comment in JSON. It has to look like the example below and it has to be in object/brackets {}

{
"name" : [{"first" : "Britney", "last":"Spears"},
{"first" : "Angelina", "last":"Jolie"}],
"age" : 25
}

Friday, October 7, 2011

Javascript Object Inheritance - Extend and Multiple

These two javascript functions does the inheritance
//inheritance
function extendCopy(obj){
var n = {};
for(var i in obj){
n[i] = obj[i];
}
n.uber = obj;
return n;
}

//multiple inheritance
function multi(){
var n={}, stuff, j=0, len = arguments.length;
for(j=0;j<len;j++){
stuff = arguments[j];
for(var i in stuff){
n[i] = stuff[i];
}
}
return n;
}

Below test the object to see if it worked
//Setting objections
var first_obj = {name:'first', doSomething: function(){alert(2+2);}}
var second_obj = {date:'today', location: 'USA'}
var third_obj = {felling:'happiness', status: 'fun'}
http://www.blogger.com/img/blank.gif
//append/inheritance first first_obj to second_obj
var second_obj = extendCopy(first_obj);
document.write(second_obj.name); // first

//add both the first_obj and third_obj at the same time
var fourth_obj = multi(first_obj,third_obj);
document.write(fourth_obj.felling);// happiness


Another example of javascript inheritance using constructors

Monday, October 3, 2011

Javascript String Manupulation Examples

Below are javascript functions to manipulate the URL and most common used string manipulators.
<script>
var content = encodeURI(window.location);
document.write(content + '<br >');

document.write(content.charAt(0) + '<br />'); //returns the character at the number position http://www.blogger.com/img/blank.gif
document.write(content.length + '<br />'); //string length
document.write(content.indexOf('a') + '<br />'); //position of first occurence
document.write(content.lastIndexOf('a') + '<br />'); //positions of last occurence
document.write(content.substring(5,10) + '<br />'); //substring(start,end)
document.write(content.substr(2,3) + '<br />'); // substr(start, length from start)
// Try not to confuse substr and substring the completely different

</script>
Additional JavaScript String Objects

Wednesday, September 14, 2011

Setting the input className to the object value

The code below creates and set the value of the object when filling out a form. This can be used for POST or GET method request.

<input type="text" class="balls" />
<input type="text" class="bat" />
<script>
var stat = {
data: {date: '2011-02-01', type: 'balls'},
column: //sets the value to stat.data
function(){
$('input').focusout(function () {
var attr = $(this).attr("class");//get the attribute (className) of tag
//create and set value for the object
stat.data[attr] = $(this).val(); //set value to stat.data
});
}() //this autostarts the function
}
<script/>

From locahost/stats website

Monday, September 5, 2011

Javascript Object Inheritance and Overwriting - Using Constructors

Read the comments(green text) in the code below
function shape(){ 
this.name='shape';
this.tostring = function() {return this.name;};
}

function TwoDshape(){
this.name = '2D shape';
}

function Triangle(side,height){
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){return this.side * this.height /2;};
}

//Inheritance
//overwriting objects sort of. if you print the TwoDshape.constructor it will show the assigned object but all the properties from inside both functions are accessible unless one has the same name, the original is printed so below shape() properties is added to TwoDshape() and TwoDshape() is added to Triagle(). making Triangle() have itself and shape() and TwoDshape() propeties within

TwoDshape.prototype = new shape();
Triangle.prototype = new TwoDshape();



//good idea to reset the constructor after inheriting, because overwrite the object has negative side effects
TwoDshape.prototype.constructor = TwoDshape;
Triangle.prototype.constructor = Triangle; http://www.blogger.com/img/blank.gif

var my = new Triangle(5,10);
document.write(my.getArea());
document.write(my.tostring());

The output is 25Triangle

Another example of javascript inheritance using the pure object

Special Thanks Object-Oriented Javascript

Friday, September 2, 2011

jQuery AJAX .load()

jQuery AJAX is wonderfully powerfull. The more I use it the more I like it. Its very simple compared to the pure AJAX javascript code. jQuery has a couple of different AJAX syntax but the simplest is the .load(). Choose which element you want to target and which location/file you want to pull content from. Barabam AJAX.

Example:
$('div').load('test.html');
Above changes the div tag in current page to the test.html

One cool feature is the ability to pull a selected portion of the location by having a space after the location name and specifying the part.

Example:
$('div').load('test.html #content');
Above changes the div tag in current page to the test.html where the id equals "content"

More information check .load() – jQuery API

Wednesday, August 24, 2011

Frameworks

Don't reinvent the wheel. Below are frameworks that allow you to code without having to start from scratch.

HTML - Boilerplate

PHP - CodeIgniter

CSS - Twitter Bootsrap

CSS structure - 960

Javascript - jQuery

Saturday, July 30, 2011

jQuery $.ajax and $.post

Below is an ajax jQuery code that allow uses for POST. Communication between two pages.

$.post is a simpler version with less features than $.ajax. In the code below they are both configured to do the same concept.






mouseover me Type in box to see ajax

Monday, July 25, 2011

How to redirect

Below are examples on how you can redirect your website. When someone visits your site and you want the traffic to go somewhere else. Choose your language, modify url and copy and paste.

Javascript:

<script>
location.replace("http://baligena.com") //or
location = "http://baligena.com";
</script>


PHP:

<?php
header( 'Location: http://www.baligena.com' ) ;
?>


HTML:

<meta HTTP-EQUIV='REFRESH' content='0'; url='http://www.baligena.com'>

Sunday, June 12, 2011

Adding Syntax Highlighting to Blogger

Do you want to show code on your blog like I'm doing below? Click Me to see instructions.

<?php 
echo "hello world";
$ball = "ball";
?>

Wednesday, May 18, 2011

printObj() => outputs object properties

The javascript function below is used to output the objects and its properties. Alternative to the php function => print_r
I use it mostly for looking up the document DOM eg. printObj(document)

Insert code inside JavaScript <script> tags
_________________________________________________

function printObj(obj) //reads the objects properties
{
var object ="";// sets the variable
for(var type in obj)
{object += type +"=> " + obj[type] + "<br /> ";}
document.write(object);
}

//create a new array or object
var num = new Array(1,2,3,45,6);
//outpuy the object and its properties by
printObj(num)
______________________________________________

Output:
0=> 1
1=> 2
2=> 3
3=> 45
4=> 6



bookmarklet: shows all the the p tags for the page. Copy and paste the code below in the address bar.

javascript:e = document.getElementsByTagName('p');function printObj(obj){var object ="";for(var type in obj){object += type +"=> " + e[type].innerHTML + "<br />";}document.write(object);}printObj(e);

Friday, April 15, 2011

Removing nav bar from blogger

Ever wanted to remove the bar on top of you blogger account because you don't want people to know your using a free service. The link below explains a real simple way.