GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

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

Wednesday, May 9, 2012

Query Suggestion

<h1>Drop Drown</h1>
<input type="text" id="text" onkeyup="show(event)"/>
<p id="view"></p>


<script>
var data = ["apple","banana","mango",
           "watermelon","orange","papaya"];

function show(event){
    var text = document.getElementById('text').value;
    var view = document.getElementById('view');
    var len = text.length;
    var plot = "";

    if (len==0){
        view.innerHTML = "";
        return;
    }

    // we iterate all the available data to match on 
    // the server
    for(i=0;i<data.length;i++){
        // we just take the query that match 
        // the first main of the saved words on the server.
        // for each length of the string.
        // we compare if the query from the user 
        //is match the defined words.
        if(text==data[i].substr(0,len)){
            plot = plot+"<br/>"+data[i];
        }
    }

    view.innerHTML = plot;
}

</script>

Share/Bookmark

Monday, May 9, 2011

JS -- AJAX

Introduction

AJAX is a mechenisme for communicating with server through background. It enables your client web site to load and sending data from and to server respectively without reloading the page.

Sending Data To Server

Here's a simple example on how to use ajax.

Program Code: Client Side

<input type="text" id="name"/>
<input type="button" value="Send" onclick="sending()"/>

<script>

function sending(){

  var name = document.getElementById('name').value;
  var ajax = new XMLHttpRequest();
  ajax.open("GET", "hello.php?name="+name, false);
  ajax.send();

}

</script>
It's not so complicated. The fisrt, you have the data. The second, you declare an object instance of ajax throught XMLHttpRequest. Then you send your data through ajax. Finish.
And on the server side, you need to write the code to handle it. Here's a code on PHP.

Program Code: hello.php

$name = $_GET['name'];
From the above code, you see that you handling the data as it comes from common request.


Share/Bookmark

JS - JSON

Introduction

JSON is a data format for transferring data as an alternative to XML. JSON is ligter than XML. The syntax is like mapping.

Program Code

var data = {
  "name": "Lady Gaga",
  "city": "New York",
  "age": 24
}
In the above example, we have JSON data format.


Share/Bookmark

Friday, April 1, 2011

JS - Simulation Of Gerak Peluru

<h1>Gerak Parabola</h1>
<p id="info" style="font: 12px sans-serif;">x: <span id="x"></span> | y: <span id="y"></span> | v: <span id="v"></span></p>
<canvas id="canvas" style="border: 1px solid blue;">Not Supported</canvas>
<div id="right" style="float: right; ">
 <table>
  <tr><td>Degree</td><td>:</td><td><input type="text" id="degree"/></td></tr>
  <tr><td>Initial Velocity</td><td>:</td><td><input type="text" id="velocity"/></td></tr>
  <tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="button" value="Run" onclick="run()"/></td></tr>
 </table>
</div>
<script>
var Lucia = Lucia || {};
Lucia.GerakParabola = function(){

// screen dimension
this.screenWidth = 500;
this.screenHeight = 200;

// getting the elements
this.canvas = document.getElementById('canvas');
this.xInfo = document.getElementById('x');
this.yInfo = document.getElementById('y');
this.vInfo = document.getElementById('v');

// setting the initial condition
this.ctx = canvas.getContext('2d');
this.canvas.height = this.screenHeight;
this.canvas.width = this.screenWidth;
this.ctx.fillStyle = '#88f';

// box properties
this.width = 10;
this.height = 10;

this.vBefore = 60;
this.vHozAfter = 0;
this.vVerAfter = 0;
this.degree = 60;
this.g = 10;
this.xBefore = 0;
this.xAfter = 0;
this.yBefore = 0;
this.yAfter = 0;
this.dt = 0.1;
 }
Lucia.GerakParabola.prototype.move = function(){

// getting the velocity component
this.vHozAfter = this.vBefore*Math.cos(this.toRadian(this.degree));
this.vVerAfter = this.vBefore*Math.sin(this.toRadian(this.degree)) - this.g*this.dt;

// getting the position of horizontal and vertical
this.xAfter = this.vBefore*this.dt*Math.cos(this.toRadian(this.degree));
this.yAfter = this.vBefore*this.dt*Math.sin(this.toRadian(this.degree)) - 0.5*this.g*this.dt*this.dt;

// summing the time
this.dt = this.dt+1;

// update the box;
this.ctx.clearRect(0, 0, 500, 200)
this.ctx.fillRect(this.xAfter, this.screenHeight - this.yAfter - this.height, this.width, this.height);

// display info
this.xInfo.innerHTML = Math.round(this.xAfter);
this.yInfo.innerHTML = Math.round(this.yAfter);
this.vInfo.innerHTML = Math.round(this.vHozAfter);
 
// setting the timer
var lol = this;
setTimeout(function(){lol.move();},1000);         
}

// convert degree to radian
Lucia.GerakParabola.prototype.toRadian = function(degree){
 return (degree/57);
}
Lucia.GerakParabola.prototype.setDegree = function(d){
 this.degree = this.toRadian(d);
}
Lucia.GerakParabola.prototype.setInitVelocity = function(v){
 this.vBefore = v;
}

function run(){
 var degree = document.getElementById('degree');
 var velocity = document.getElementById('velocity');
 var gp = new Lucia.GerakParabola();
// gp.setDegree(eval(degree.value));
// gp.setInitVelocity(eval(velocity.value));
 gp.move();
}
</script>

Share/Bookmark

Thursday, March 31, 2011

JS - Simulation Of Gravitational Forces

<h1>Canvas Element</h1>
<p style="font: 12px sans-serif;">height: <span id="h"></span><br/>velocity: <span id="v"></span></p>
<canvas id="canvas" style="border: 1px solid blue;">Not Supported</canvas>


Share/Bookmark

Wednesday, March 30, 2011

Canvas - Gravitational Forces

<!-- This program provide implementation for gravitational forces using Javascript OOP style -->

<h1>Gravitational Forces</h1>
<canvas id="canvas">Not Supported</canvas>

<script>
function GF(id){
 this.x = 30;
 this.y = 0;
 this.width = 50;
 this.height = 30;
 this.screen_width = 500;
 this.screen_height = 2000;
 this.vo = 0;
 this.vt = 0;
 this.ho = 0;
 this.ht = 0;
 this.canvas = document.getElementById(id);
 this.ctx = this.canvas.getContext('2d');
 this.canvas.height = this.screen_height;
 this.canvas.width = this.screen_width;
 this.g = 10;
 this.t = 0;

}
GF.prototype.drawLine = function(){
 for(var i=0;i<100;i++){
  this.ctx.fillStyle = '#444';
  this.ctx.fillText(i,1,i*30);
 }
}
GF.prototype.down = function(){
 this.ht = this.ho + 0.5 * this.g * this.t * this.t;
 this.vt = this.vo + this.g * this.t;
 this.t = this.t + 0.1;

 this.ctx.clearRect(20, 0, this.screen_width, this.screen_height);
 this.ctx.fillRect(this.x, this.ht, this.width, this.height);

 this.ctx.fillStyle = '#10f';
 this.ctx.fillText('v: '+Math.round(this.vt),this.x+5,this.ht+10);
 this.ctx.fillText('h: '+Math.round(this.ht),this.x+5,this.ht+20);
 this.ctx.fillStyle = '#af0';

 var d = this;
 setTimeout(function(){d.down();},100);

}

var gf = new GF('canvas');
gf.down();
gf.drawLine();

</script>

Share/Bookmark

Tuesday, March 29, 2011

AJAX - Sample Of Post Method

<table>
<tr><td>Name</td><td>:</td><td><input type="text" id="name"/></td></tr>
<tr><td>City</td><td>:</td><td><input type="text" id="city"/></td></tr>
<tr><td>Age</td><td>:</td><td><select id="age">
    <?php
        $output = '';
        for($i=21; $i<61; $i++){
            $output .= '<option value="'.$i.'">'.$i.'</option>';
        }
        echo $output;
    ?>
    </select></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td><input type="button" onclick="Send()" value="Send"/></td></tr>
</table>

<script>
    var lucia = lucia || {};
    lucia.getById = function(id){
        return document.getElementById(id);
    }
    function Send(){
        var name = lucia.getById('name');
        var city = lucia.getById('city');
        var age = lucia.getById('age');
       
        var data = {
            'name': name.value,
            'city' : city.value,
            'age' : age.value
        };
        var json_data = JSON.stringify(data);
       
        var ajax = new XMLHttpRequest();
        ajax.open('POST','hello.php', false);
        ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        ajax.send('data='+json_data);
       
        var response = eval('('+ajax.responseText+')');
       
       
       
       
    }
</script>

Share/Bookmark

Sunday, March 27, 2011

HTML5 - Rotate

To make rotate transformation, use translate first, then rotate, then back to translate again:
ctx.translate(230,10)
ctx.rotate(45/57)
ctx.translate(-230,-10);
ctx.fillRect(230, 10, 100, 100)
Share/Bookmark

Tuesday, March 22, 2011

JS - Namespace

To make namespace, do like
var lucia = lucia || {};

Then you can do
lucia.name = 'New York';
lucia.say = function(){
    alert('Okey');
}

More details:
<script>
var lucia = function(){
    return {
        methodA: function(){
            alert('Method A');
        },
        methodB: function(){
            alert('Method B');
        }
    }
};

var a = new lucia();
a.methodB()
a.methodA()

</script>

For private member:
<script>
    var lucia = function(){
    var name = 'Lucia Namespace';
    function say(){
        return name;
    }
    return {
        methodA: function(){
            alert('Method A');
        },
        methodB: function(){
            alert('Method B');
        }
    }
};

var a = new lucia();
a.methodB()
a.methodA()

</script>
Share/Bookmark

Sunday, March 20, 2011

Ajax - TinyMCE Saving

 To get the content of the editor of TinyMCE, use
function save(){
    var mce = tinyMCE.get('content');
    alert(mce.getContent());
}

For initializing the editor, use:
tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Skin options
        skin : "o2k7",
        skin_variant : "silver",       
});

To send the content to the server, use:
function send(){
    var data = tinyMCE.get('content').getContent();
    var ajax = new XMLHttpRequest();
    ajax.open('POST','hello.php',false);
    ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    ajax.send('data='+data);
}

Share/Bookmark

Ajax - Params In Post

To do sending parameter with post, what you need is do a little bit of code:

var ajax = new XMLHttpRequest();
ajax.open('POST', 'hello.php', false);
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// below is data you send
ajax.send('name=luna&city=denpasar');

With ajax, you can also get info response from server:
var content_length = ajax.getResponseHeader('Content-length');

Share/Bookmark

JS - Play With Closure

1. var data = ( function(){
        alert('hello');
   });
   data();

2. var data = ( function(name){
        alert(name);
   });
   data('Americas');

3. (function(){
        alert('Hello');
   })();

4. (function(name){
        alert(name);
   })('Americas');

Share/Bookmark

Thursday, March 17, 2011

JSON - Response As An Array

When you hope your json response as an array, not as an object, so do it like this one:
Server:
    $data = array();
    $data[] = 'lady gaga';
    $data[] = 'luna maya';
    $data[] = 'barack obama';

    echo json_encode($data);

Client:
    $data = eval('('+ajax.responseText+')');
    for(i=0; i<data.length; i++){
        element.innerHTML = innerHTML + data[i];
    }
Share/Bookmark

jQuery - Manipulating DOM

it's easy to do manipulating DOM using jQuery althought it's not compatible with the native DOM manipulation.
To insert content, use
before - insert outside before the selector
after - insert outside after the selector
append - insert in the inside but the last one
prepend - insert in the inside but the first one
detach - remove the selector as well as its content
empty - remove the all the child inside the selector
remove - remove the selector as well as its event and data.
insertAfter - insert content after the target
insertBefore - insert content before the target
Share/Bookmark

Sunday, March 13, 2011

JS - XML Manipulation

<h1>XML DOM</h1>
<div>Name: <span id="name"></span></div>
<div>City: <span id="city"></span></div>
<div>Age: <span id="age"></span></div>
<p id="info"></p>


Share/Bookmark

JS - Converting DOM To String

/**
 * Here's a code sample to convert xml string to dom, and xml dom
 * back to string;
 */

<h1>XML DOM</h1>
<script>
var text = '<?xml version=\"1.0\"?>';
text = text + '<data>';
text = text + '<name>Lady Gaga</name>';
text = text + '<city>New York</city>';
text = text + '</data>';

var parser = new DOMParser();

// convert text string to dom
var dom = parser.parseFromString(text,'text/xml');

// convert back dom to string of text
alert((new XMLSerializer()).serializeToString(dom));

</script>

Share/Bookmark

Saturday, March 12, 2011

JS - Local Storage On HTML5

To use local storage of HTML5, Just write:
<script>
localStorage.firstName = "Lady";
localStorage.lastName = "Gaga";

alert(localStorage.firstName +" "+ localStorage.lastName);
</script>
Share/Bookmark

JS - Drawing Path On Canvas

<h1>Canvas Tutorial</h1>
<canvas id="canvas" width="200" height="200">No Support</canvas>
<style>
canvas { border: 1px solid #ccc; background: yellow; -moz-box-shadow: 0 0 4px #ccc; -moz-border-radius: 4px;}
</style>

<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

context.fillStyle = "rgb(150,250,0)";

// Filled Shape
context.beginPath();

context.moveTo(10,10);
context.lineTo(100,10);
context.lineTo(100,100);
context.lineTo(10,100);

context.moveTo(150, 10);
context.lineTo(180, 10);
context.lineTo(180,100);
context.lineTo(150, 100);

context.fill()


// Stroke


</script>

Share/Bookmark

JS - Canvas Element Basic Drawing

Here's a canvas element - a new standard in HTML 5.
<canvas id="canvas" width="200" height="200">Not Supported</canvas>

Then in javascript block, you can manipulate it:
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

context.fillStyle = "rgb(150,250,0)";
context.fillRect(50,50,100,100); // x,y,width,height

context.fillStyle = "rgb(50, 1250, 50)";
context.fillRect(30, 90, 150, 20);  // draw rect

context.strokeRect(10,10,30,100);  // draw outline of rect

context.clearRect(100,100,20,20); // make transparent

</script>
Share/Bookmark

Thursday, March 10, 2011

PHP - XML In Sending Data

Here's a code on how to sending data from client to server in the form of xml format. You can see also at this link.
1. file index.php
<h1>Javascript And JSON</h1>
<p>Here's a demo on how to use json and ajax for sending data to server</p>
<div id="form">
    Name: <input type="text" id="name"/><br/>
    City: <input type="text" id="city"/><br/>
    Age: <input type="text" id="age"/><br/>
    <input type="button" onclick="sendData()" value="Save"/>
</div>
<div id="response"></div>

Share/Bookmark