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

Thursday, August 20, 2015

HTML 5移动开发从入门到精通

HTML 5移动开发从入门到精通

This introduces some HTML5 elements.

Javascript elements:

1. selectors api
2. JSON parse/stringify
3. Hashchage event
4. async.defer for script
5. progress for ajax
6. DeviceOrientation
7. touch events

Html5 Tag elements:

1. progress: <progress max="100" value="30"></progress>
2. mark (highlight text): <mark>This is a mark</mark>
3. address (italic format)
4. Colgoup col
5. keygen
6. fieldset/legend
7. ol.li (reversed, start, type)
8. q (quotation)
9. contenteditable div

Tuesday, July 28, 2015

Bootstrap

== Summary of today's review of Bootstrap ==

Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. Bootstrap is completely free to download and use!
  • Download from: http://getbootstrap.com
  • Documentation on using JavaScript, CSS and Components are also on the above site.
  • Folder demo/ contains some nice examples of website templates. Good for quick start.
    • demo/assets/js/docs.min.js creates placeholder image. See examples/theme/ for examples.
    • In demo/examples/, for difference of static top and fixed top, you need to view in mobile phone mode.
    • Good ones for mobile: Carousel, cover, Dashboard, Grid, jumbotron-narrow, jumbotron, navbar-fixed-top, navbar-static-top, navbar, signin, sticky-footer-navbar, sticky-footer, theme.
  • Folder tests/ contains some tests of bootstrap.
  • Folder backup/ contains the downloaded boostrap zip distribution package.
  • Folder download/ contains the downloaded entire website of getbootstrap.com.
References:
  1. http://getbootstrap.com
  2. http://www.w3schools.com/bootstrap/

Saturday, May 9, 2015

Emscripten: An LLVM-to-JavaScript Compiler

This is very impressive.


Emscripten

Emscripten: An LLVM-to-JavaScript Compiler
Project main site: http://kripken.github.io/emscripten-site/
Wiki site: https://github.com/kripken/emscripten/wiki
Github project: https://github.com/kripken/emscripten


asm.js

An extraordinarily optimizable, low-level subset of JavaScript.
http://asmjs.org/


Tuesday, April 21, 2015

Greasemonkey

Greasemonkey can do some interesting tricks on a webpage.

Greasemonkey scripts (Javascript) can alter web page elements, add a div or box to the page, trigger button click events and others.

For example, here is a script that adds a checkbox before the link tag for ever <li> element:


// ==UserScript==
// @name       script name
// @namespace  http://my.homepage/
// @version    0.1
// @description  add marking checkbox.
// @match      http://matched_website.com

// @match      https://matched_website.com
// ==/UserScript==

function changhandler(event) {
    if (event.target.checked) {
        localStorage[event.target.name] = true;
    } else {
        localStorage.removeItem(event.target.name);
    }
}

[].forEach.call(
    document.getElementById('main').getElementsByTagName('li'),
    function(e) {
        var checkBox = document.createElement('input');
        checkBox.type = 'checkbox';
        checkBox.name = e.getElementsByTagName('a')[0].innerHTML;
        checkBox.checked = localStorage[e.getElementsByTagName('a')[0].innerHTML];
        checkBox.addEventListener('change', changhandler, false);
        oj.insertBefore(checkBox, null);
    }
);


[1] http://en.wikipedia.org/wiki/Greasemonkey

Monday, April 6, 2015

Friday, April 3, 2015

Play midi in browser by Javascript only

Midi files usually have very small size, but rich sound effects. HTML5 Audio tag supports wav, mp3 and ogg formats so far.  Here are methods to play midi music in web browser using Javascript only, with no plugin such as QuickTime.

I wrote the one at [7].

Features

  • Can specify these in constructor parameter list: midi, target, loop, maxLoop, end_callback.
    - midi: MIDI file path.
    - target: Target html element that this MIDI player is attached to.
    - loop: Optinoal. Whether loop the play. Value is true/false, default is false.
    - maxLoop: Optional. max number of loops to play when loop is true. Negative or 0 means infinite. Default is 1.
    - end_callback: Optional. Callback function when MIDI ends.
      e.g., use this to reset target button value from "stop" back to "play".
  • Can specify a debug div, to display debug message: setDebugDiv(debug_div_id).
  • Start/stop MIDI by: start(), stop().
  • If a MIDI started play, call start() again will stop and then restart from beginning.
This depends on other 5 javascript files (audio.js, midifile.js, replayer.js, stream.js, synth.js) from [2][3], which is a demo of [1]. This is related to [4], which is a powerful tool to play MIDI in browser.

The disadvantage of [2][3] is that it does not have control over how a MIDI file is played: when clicking on the link the file will be started multiple times and sounds chaotic; and there is no loop feature. Both are well handled by MidiPlayer.js here.

Another midi player javascript is in [5], but it cannot play multiple MIDI files at the same time, cannot play a MIDI file automatically after loading the page, and has no loop feature. All are handled by MidiPlayer.js here.

It can be a good idea to add MIDI support to HTML5 Audio tag, because MIDI files have much smaller size than wav/mp3, and the sound effects are very rich.

[1] http://matt.west.co.tt/music/jasmid-midi-synthesis-with-javascript-and-html5-audio/
[2] http://jsspeccy.zxdemo.org/jasmid/
[3] https://github.com/gasman/jasmid
[4] MIDI.js - Sequencing in Javascript.
[5] MIDI.js - The 100% JavaScript MIDI Player using W3C Web Audio
[6] Dynamically generating MIDI in JavaScript
[7]  The MidiPlayer javascript class

Javascript drag/drop event listener

It is a cool feature that file processing is triggered when you drag a file and drop it onto a web page.

For example, the midi player demo page index.html from [1] has this in header javascript:

    if (FileReader){
        function cancelEvent(e){
            e.stopPropagation();
            e.preventDefault();
        }
        document.addEventListener('dragenter', cancelEvent, false);
        document.addEventListener('dragover', cancelEvent, false);
        document.addEventListener('drop', function(e){
            cancelEvent(e);
            for(var i=0;i            var
                file = e.dataTransfer.files[i]
            ;
            if(file.type != 'audio/midi' && file.type != 'audio/mid'){
                continue;
            }
            var
                reader = new FileReader()
            ;
            reader.onload = function(e){
                midiFile = MidiFile(e.target.result);
                synth = Synth(44100);
                replayer = Replayer(midiFile, synth);
                audio = AudioPlayer(replayer);
            };
            reader.readAsBinaryString(file);
            }
        }, false);
    }


What this does is, when you drag and drop a midi file on the page, it'll be read and played.

HTML5 has native support for drag/drop event. See [2].

[1] https://github.com/gasman/jasmid
[2] Native HTML5 Drag and Drop

Tuesday, March 31, 2015

Javascript OOP

Javascript is a prototypical langaage. Its OOP is achieved by prototype instead of class. Prototype is kind of like decorator patten, that decorates a initially bare object with more functionalities.

Some links to Javascript OOP:
The most common syntax for defining a class is [3]:

if (typeof (classA == "undefined")) {

    // Another short-hand way of defining this class:  function classA() { ... }
    var classA = function() {
        this.property1 = 1;  // A public variable. Defined with "this.". To access, use "this.".
        var secret = 2;  // A private variable. Defined with "var". To access, don't use "this.".

        // A private method.
        // Another short-hand way of defining this:  function dec () { ... }
        var dec = function() {
             if (secret > 0) {
                secret -= 1;
            }
        }

       
        // A privileged method. Can access private variables and methods. Accessible to outside.
        // Defined with "this.".
        // Another way of defining this:  function getInfo() { ... }
        this.getInfo = function() {
            return secret + this.property1;
        }     
    }

    // A public method.
    classA.prototype.getColor = function() { return 'green'; }
}

To create an instance you do:

var objectA = new classA();

To inherit from classA you do something like this [2]:

function classB() {
    this.setValue(value);

classB.inherits(classA);

Promiscuous multiple inheritance is possible but hard and may suffer from name collision.

Other related concepts include swiss inheritance, parasitic inheritance etc.


Wednesday, November 5, 2014

How jQuery is written from scratch?

This probably helps: http://www.mikedoesweb.com/2012/creating-your-own-javascript-library/

This is a minimum javascript library whose grammar is very similar to jQuery: _('id').function(). It helps to understand how jQuery is written from scratch.

I think I can start writing a javascript library similar to jQuery now :).

Tuesday, October 21, 2014

jQuery 1.8 update on ajax call

jQuery ajax call uses different syntax since version 1.8 [1].


Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8 (but still works in 1.9.1). To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Get html in jQuery before 1.8:

$.ajax({
    url: 'test.html',
    dataType: 'html',
    success: function (data, textStatus, xhr)
    {
        console.log(data);
    },
    error: function (xhr, textStatus, errorThrown)
    {
        console.log('error: '+textStatus);
    }
});


The code above still works in 1.8. But the code below no longer works in 1.8:

$.post("get_news.php", { id: id }, function(data, status) {
    if (status == "success") {
        if ( data != '' ) {
            o.innerHTML = data;
        }
        return 1;
    } else {
        return 1; // ok
    }
}, 5);


Get html in jQuery since 1.8:

// cache: false is used to fetch the latest version
$.ajax({

    type: 'POST',
    url: "test.html",

    data: { id: id },
    dataType: 'html',
    cache: false
})
.done(function(data, textStatus, jqXHR)
{
    console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown)
{
    console.log('error: '+textStatus);
});



[1] http://www.sitepoint.com/ajax-jquery-1-8/

Wednesday, January 15, 2014

Javascript big int operation

Javascript int are actually float. When '&' bit-wise AND is used, the value is converted to integer and operated on. It's 32 bits only, and is signed by default. So for big int longer than this, there is no way to do bit-wise AND.

Here is a solution: first convert the input integer string (a string, not a int) into binary format, then do a bit by bit comparison. Code is below.

function BIGINT_AND(a, b) {
  a = toBinary(a);
  b = toBinary(b);

  for (var i = a.length - 1, j = b.length - 1; i >= 0 && j >= 0; -- i, -- j) {
    if (a[i] == 1 && b[j] == 1) return 1;
  }

  return 0;
}

// convert from decimal format to binary format
function toBinary(decNum){
    return parseInt(decNum,10).toString(2);
}

Thursday, November 10, 2011

iPhone/iPad hover function

The hover event (can be provided by css or javascript) is not supported in iPad/iPhone.

The workaround is use javascript: "onclick='javascript: f1();'". f1() is defined as:

function f1(o) {
if ( navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ) {
// do the hover work. for example:
var x = document.getElementById('elemId');
x.style.left = u.parentNode.offsetLeft + 'px'; // needed for positioning.
x.style.visibility = 'visible';
}
return true;
}

Some sources say one can also use ontouchstart() and ontouchend(). But they didn't work in my situation.

Friday, May 20, 2011

Thursday, June 3, 2010

Javascript resources

- Unbelievably easy javascript for sortable table header columns: Available here.
- Calendar date picker: datepickercontrol. Available here.
- Slider: Easy slider.

Blog Archive

Followers