Category Archives: Javascript

[Javascript] parentNode.insertBefore(newnode, existingchild)

ref. http://reference.sitepoint.com/javascript/Node/insertBefore

This method is fantastically useful, but it can be tricky to remember the syntax. I remember it as a little sentence, like this: “into parent, insert new before old”.

If you don’t have a parent reference, it’s easy to extrapolate one from the node you do have:

 old.parentNode.insertBefore(new, old);

Conversely, if you only have a parent reference you can still insert at the beginning (providing that the parent has at least one child node already):

 parent.insertBefore(new, parent.firstChild);

Or the end (which is exactly equivalent to appendChild):

 parent.insertBefore(new, null);

[Javascript] Handlebars precompiling templates

ref. http://net.tutsplus.com/tutorials/javascript-ajax/introduction-to-handlebars/
http://berzniz.com/post/24743062344/handling-handlebars-js-like-a-pro

== Handlebars precompiling templates

1. download the Node.js package through npm :
sudo npm install handlebars -g

2. create a file for your template and compile it like so: -m: minimize output
app/assets/javascripts> mkdir templates
vim hello.handlebars
<p>Hello {{name}}</p>

handlebars ./templates/ -f ./templates/templates.js -m

3. simply include the output file along with the run-time version(handlebars.runtime.js) of Handlebars (you can use the regular version, but it’s larger) and type the following:

vim application.js
//= require handlebars-1.0.rc.1.min
//= require ./templates/templates
or
//= require andlebars.runtime
//= require ./templates/templates

 

Source Code:

var template = Handlebars.templates['hello'];
var html = template({ name: ‘World’ });

Mixing precompiling and runtime compiling templates

Handlebars.getTemplate = function(name) {
	if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
		$.ajax({
			url : 'templates/' + name + '.handlebars',
			success : function(data) {
				if (Handlebars.templates === undefined) {
					Handlebars.templates = {};
				}
				Handlebars.templates[name] = Handlebars.compile(data);
			},
			async : false
		});
	}
	return Handlebars.templates[name];
};

[Javascript] underscorejs _.all(), _.any() methods

Determine whether all of the elements match a truth test. Delegates toECMAScript 5‘s native every if available. Aliased as all.
  _.every = _.all = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = true;
    if (obj == null) return result;
    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
    each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };
Determine if at least one element in the object matches a truth test. Delegates to ECMAScript 5‘s native some if available. Aliased as any.
  var any = _.some = _.any = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
    each(obj, function(value, index, list) {
      if (result || (result = iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

 

[Javascript] Array.prototype.slice.call( arguments, 0 )

ref. https://shanetomlinson.com/2010/converting-arguments-to-a-javascript-array/

Convert arguments to an array of javascript

var testFunction = function() {  
  // Create a new array from the contents of arguments  
  var args = Array.prototype.slice.call(arguments);  
  
  var a = args.shift();  
  console.log("The first argument is: %s", a);  
  
  // send the remaining arguments to some other function  
  someOtherFunction(args);  
};  

Change Underscore.js template settings

== template ==
_.template(templateString, [data], [settings])

http://underscorejs.org/#template

: Template functions can both interpolate variables, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>

var compiled = _.template("hello: <%= name %>");
compiled({name : 'moe'});
=> "hello: moe"

var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list, {people : ['moe', 'curly', 'larry']});
=> "<li>moe</li><li>curly</li><li>larry</li>"

var template = _.template("<b><%- value %></b>");
template({value : '<script>'});
=> "<b><script></b>"

You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge."

If ERB-style delimiters aren’t your cup of tea, you can change Underscore’s template settings to use different symbols to set off interpolated code.
* Define an interpolate regex to match expressions that should be interpolated verbatim,
* an escape regex to match expressions that should be inserted after being HTML escaped,
* and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string.

== Underscore.js Template Settings =

// Underscore.js Template Settings
_.templateSettings = {
    interpolate: /\{\{\=(.+?)\}\}/g,
    escape: /\{\{\-(.+?)\}\}/g,
    evaluate: /\{\{(.+?)\}\}/g
};
var compiled = _.template("hello: {{= name }}");
compiled({name : 'moe'});
=> "hello: moe"

var list = "{{ _.each(people, function(name) { }} <li>{{= name }}</li> {{ }); }}";
_.template(list, {people : ['moe', 'curly', 'larry']});
=> "<li>moe</li><li>curly</li><li>larry</li>"

var template = _.template("<b>{{- value }}</b>");
template({value : '<script>'});
=> "<b>&lt;script&gt;</b>"

[JavaScript] Google Chart Tools

ref. https://developers.google.com/chart/interactive/docs/

Introduction to Using Chart Tools

Google Chart Tools provide a perfect way to visualize data on your website. From simple line charts to complex hierarchical tree maps, the chart galley provides a large number of well-designed chart types. Populating your data is easy using the provided client- and server-side tools.

Google Chart Tools

[Javascript] 숫자를 한글로 변환하기

ref. http://www.technote.co.kr/php/technote1/board.php?board=apple&command=body&no=968


<HTML>
<HEAD>
    <TITLE>숫자를 한글로 변환합니다</TITLE>
<script>
<!--
Number.prototype.read = function() {
    if (this == 0) return '영';
    var phonemic = ['','일','이','삼','사','오','육','칠','팔','구'];
    var unit = ['','','십','백','천','만','십만','백만','천만','억','십억','백억','천억','조','십조','백조'];
    var ret = '';
    var part = new Array();
    for (var x=0; x<String(this).length; x++) part[x] = String(this).substring(x,x+1);
    for (var i=0, cnt = String(this).length; cnt > 0; --cnt,++i) {
        p = phonemic[part[i]];
        p+= (p) ? (cnt>4 && phonemic[part[i+1]]) ? unit[cnt].substring(0,1) : unit[cnt] : '';
        ret+= p;
    }
    return ret;
}
//-->
</script>
<form>
숫자 입력폼에 숫자만 넣어보세요..<br>
숫자 : <input type="text" name="num" onKeyUp="this.form.han.value=Number(this.value).read()"><br>
문자 : <input type="text" name="han">
</form>

[Javascript] Rails-like number_with_delimiter in javascript

ref. http://kevinvaldek.posterous.com/number-with-delimiter-in-javascript
- http://sleeplesscoding.blogspot.com/2011/02/rails-like-numberwithdelimiter-in.html

function number_with_delimiter(number, delimiter) {
  number = number + '', delimiter = delimiter || ',';
  var split = number.split('.');
  split[0] = split[0].replace(/(d)(?=(ddd)+(?!d))/g, '$1' + delimiter);
  return split.join('.');
};
var num = 12345678;  
var str = num.number_with_delimiter();  
alert(str); 
Number.prototype.number_with_delimiter = function(delimiter) {
    var number = this + '', delimiter = delimiter || ',';
    var split = number.split('.');
    split[0] = split[0].replace(
        /(d)(?=(ddd)+(?!d))/g,
        '$1' + delimiter
    );
    return split.join('.');    
};
number_with_delimiter(12345678)
> 12,345,678

number_with_delimiter(12345678, ':')
> 12:345:678

number_with_delimiter(12345678.555)
> 12,345,678.555

[jQuery] jQuery – Prototype js 의 $ 변수 충돌 피하기

참조: http://api.jquery.com/jQuery.noConflict/

방법1) This technique is especially effective in conjunction with the .ready() method’s ability to alias the jQuery object, as within callback passed to .ready() we can use $ if we wish without fear of conflicts later:

<script type="text/javascript" src="other_lib.js"></script><script type="text/javascript" src="jquery.js"></script><script type="text/javascript">// <![CDATA[
  jQuery.noConflict();
  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });
  // Code that uses other library's $ can follow here.
// ]]></script>

예제)

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script><script type="text/javascript">// <![CDATA[
  jQuery.noConflict();

  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
    $("div p").show();
  });

  // Code that uses other library's $ can follow here.
  document.observe("dom:loaded", function(){
    $("content").style.display = "block";
    //$$('div#content').invoke('show');
  });
// ]]></script>

Relinquish jQuery’s control of the ‘$’ variable.

code using $ as alias to jQuery

방법2) Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope.

jQuery.noConflict();
(function($) {
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library

예제)

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script><script type="text/javascript">// <![CDATA[
  jQuery.noConflict();

  (function($) { 
    $(function() {
      // more code using $() as alias to jQuery
      $("div p").show();
    });
  })(jQuery);

  // other code using $() as an alias to the other library
  document.observe("dom:loaded", function(){
    $("content").style.display = "block";
  });
// ]]></script>

Relinquish jQuery’s control of the ‘$’ variable.

code using $ as alias to jQuery

[jQuery] Dropdown menu

<style>
#container {
  position: relative;
}

#menu {
  position: absolute;
  top: 0;
  right: 0;
}

#menu, #menu ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

#menu li {
  float: left;
  background: #FFF;
}

#menu a {
  display: block;
  padding: 5px;
  width: 130px;
}

#menu li ul {
  position: absolute;
  left: -999em;
  width: 140px;
}

#menu li:hover ul, #menu li ul:hover {
  left:auto;
}

</style>

<ul id="menu">
    <li><a href="#">What's new?</a>
          <ul class="active">
            <li><a href="#">Weekly specials</a></li>
            <li><a href="#">Last night's pics!</a></li>
            <li><a href="#">Users' comments</a></li>
          </ul>

    </li>
    <li><a href="#">Member extras</a>
        <ul>
            <li><a href="#">Premium Celebrities</a></li>
            <li><a href="#">24-hour Surveillance</a></li>
        </ul>
    </li>

    <li><a href="#">About Us</a>
        <ul>
            <li><a href="#">Privacy Statement</a></li>
            <li><a href="#">Terms and Conditions</a></li>
            <li><a href="#">Contact Us</a></li>
        </ul>
    </li>
</ul>

<script>
$(document).ready(function(){
  $('#menu li ul').css({
    display: "none",
    left: "auto"
  });
  $('#menu li').hover(function() {
    $(this)
    .find('ul')
    .stop(true, true)
    .slideDown('fast');
  }, function() {
    $(this)
    .find('ul')
    .stop(true,true)
    .fadeOut('fast');
  });
}); 
</script>