Jquery .on() method not working on dynamic content

A page that executes javascript every time an input field it checked and also load new data thru ajax.

My jquery selector

$(".te_multiselect_checkbox").on("change", function( e ) {} 

was not working on the new content. When I ran $(‘.te_multiselect_checkbox’) in the console before the new content was retrieve I would get http://x-v.it/uploads/capit/ge/n3/8y.jpg but after the new content was loaded I got

http://x-v.it/uploads/capit/4q/7x/s1.jpg
(x.fn.x.init)
I dont know if this happens because the page was architect to do so or javascript is doing it.

What I learned is the selector is not getting the new content change the selector to

$(document.body).on('change', '.te_multiselect_checkbox', function( e ) {}

Here is the explanation:
http://stackoverflow.com/questions/15090942/jquery-on-method-not-working-on-dynamic-content
http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements

tags:
jquery maintain selector when new ajax content
jquery get by class more than 100

Getting started with Node.js and express

# working in ubuntu 12.04

# add package to get latest version to not get errors
sudo add-apt-repository –yes ppa:chris-lea/node.js
sudo apt-get update

# install node.js and npm
sudo apt-get install nodejs npm

# install express framework
$ sudo npm install -g express
$ sudo npm install -g express-generator

# create project
$ express testexpress
$ cd testexpress
$ sudo npm install

# or if you wish to create project with hogan (handlebars) and less
$ express testexpress –hogan -c less

# to run the app
$ DEBUG=testexpress ./bin/www

# miscellaneous
$ npm install -g nodemon

// add code to bottom of app.js to run as 
// $ node app.js
module.exports = app;
/* Use PORT environment variable if it exists */ 
var port = process.env.PORT ||3000;
server = app.listen(port);
console.log('Server listening on port %d in %s mode', server.address().port, app.settings.env);

Google API maps example/snippet

Google API maps example/snippet:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false&language=en"></script>			

" ((ACOS(SIN($lat * PI() / 180) * SIN(this.latitude * PI() / 180) + COS($lat * PI() / 180) * COS(this.latitude * PI() / 180) * COS(($lng - this.longitude) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) "; 
			

<script>
/**
*
* uses google API to get location in the search text input 
* @author 2013-06-25
* 
*/

function searchLocations() {
    var deferred = $.Deferred();
    var address = $("#te_qkeywords").val();
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({address: address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.nb;
            var longitude = results[0].geometry.location.ob;

            $('#latitude').val(latitude);
            $('#longitude').val(longitude);

            if(latitude == undefined || longitude == undefined){
              console.log('%c FSQ ERROR: latitude or longitude is blank', 'color: red');
              return;
            }
            deferred.resolve();

        } else {
            alert(address + ' not found');
        }
    });
    return deferred;
};

$('#search_button').click(
  function(event){
      event.preventDefault();

      searchLocations().done(function(){
          $('#target').submit();
      });
});


</script>

<script type="text/javascript">
/*-------------------------------------------------
	Google Map API, 2013-07-01
--------------------------------------------------*/

var get_coordinate = function(coordinate){
		var str = document.URL;

		var n = str.search(coordinate);
		var http_request = str.substring(n);
		var and_sign = http_request.search('&');
		var equal_sign = http_request.search('=');
		return http_request.substring(equal_sign+1,and_sign);
};

var me = new google.maps.LatLng(get_coordinate('latitude'),get_coordinate('longitude'));

var fit_all_markers_in_map = new google.maps.LatLngBounds();

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  //center: new google.maps.LatLng(-33.92, 151.25), //default location
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();
var marker_position = [];
var distance_between_search = [];
var meters_to_miles = 0.000621371;
var marker, i;

for (i = 0; i < locations.length; i++) {  
    marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    icon: locations[i][3],
  });
  
  distance_between_search[i] = google.maps.geometry.spherical.computeDistanceBetween( me, marker.position ) * meters_to_miles;
  marker_position[i] = marker.position;
  
  //check if there a http request
  if ( document.URL.search('latitude') > -1 ){
  	$('#distance' + (i+1)).html(parseFloat(distance_between_search[i]).toFixed(2) + ' miles');
  }

  fit_all_markers_in_map.extend(marker.position);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

map.fitBounds(fit_all_markers_in_map);

var zoom_and_pan_to_marker = (function(){
	$('tr').hover(function() {
		map.setZoom(15);
		map.panTo(marker_position[this.id-1]);
	});
})();

/*---------
	End
----------*/

</script>

jQuery Deferreds

Just some examples that were useful to me


http://x-v.it/gdfug8

var myVar  = 1;
function test(){
    var deferred = new $.Deferred();
    setTimeout(function(){
        myVar = 2;
        deferred.resolve();
    },2000);
    
    return deferred; //or return deferred.promise()
}

test().done(function(){
    console.log(myVar);  //should execute after the call below
})

console.log(myVar); //should be one because this is excuded first ever though it after the above call
 

$.get( "includes/cifras.html", function( data ) {
    $( "#songs" ).html( data );
}).done( function(){
            var songs = new Array();
            $('.first_line').each(function(i){
                songs[i] = {}
                songs[i]['html'] = $(this).html();
                songs[i]['id'] = i;
            });

            songs.reverse();
            $.each( songs, function( key, value ) {
                $('#list').append('
' + value['html'] + '

'); }); $('.cifra').click(function(){ $('#stand').html($('.cifra-mono').eq(this.id).html()); $('#list').css('display','none'); $(".back").css('display','block'); }); }); $( ".back" ).click(function() { $('#stand').html(''); $('#list').css('display','block'); $(".back").css('display','none'); });

Phonegap jQuery Mobile error – same origin policy

I’m developing an android application thru phonegap and I like to test my application in Chrome However jquery mobile was causing this error->

XMLHttpRequest cannot load file:///home/sock/Desktop/phonegap-2.7.0/lib/android/example/assets/www/js/jquery.js?_=1369249074564. Origin null is not allowed by Access-Control-Allow-Origin. jquery.js:8416
XMLHttpRequest cannot load file:///home/sock/Desktop/phonegap-2.7.0/lib/android/example/assets/www/js/jquery.mobile-1.2.0.js?_=1369249074596. Origin null is not allowed by Access-Control-Allow-Origin.

The way around this is to close all chrome browsers and run this is the command line (I’m using ubuntu)

$ chromium-browser --allow-file-access-from-files

or

$ chromium-browser --disable-web-security --user-data-dir

Chrome will open again and now you will not get this error when you run your page.


I was receiving the error when doing ajay request:


XMLHttpRequest cannot load file:///home/example/assets/www/delete.txt. Origin null is not allowed by Access-Control-Allow-Origin.

this error occurs in chrome but doesnt occur in the app when deployed so I disable this warning for developing purpose by running

$ chromium-browser --disable-web-security

tags:
cross origin

Code Snippet: Simple Javascript Progress bar

This snippet uses jQuery

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <style>
        #border{
            border: 1px solid black;
            width:500px;
            height:16px;
        }
        #progress_bar {
            height:16px;
            width:0px;
            background: red;
        }
    </style>
</head>

<div id="border">
    <div id="progress_bar"></div>
</div>


<script>//progress/status bar    
var len = 3;
var bar_size = $('#border').width();
//alert(document.getElementById('border').width);
var increment = bar_size/len;
var fill = 0;
for(var i =0; i<len; i++){
	fill += increment;
        $('#progress_bar').css('width',fill+'px');
}
</script>

>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

on ubuntu ubuntu 12.04 (see getting-started-with-node-js)
$ apt-get install nodejs

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/

 

updated 2014-07-19

>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');
}

>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.