Share Coding

Tutorials, Problems, Stuffs …

Category Archives: Javascript

jQuery scroll to top not working

var $container = $('html, body, .divProductList');	

$scrollToTop.on('click',function(){
    
    $container.animate({
        scrollTop : 0
    }, 300);
    return false;
});

The magic is in the $container selector. Put your list, html, body into the target.

AngularJS – Cross Domin Get data by $resource

For reference:

http://docs.angularjs.org/api/ngResource.$resource

Required:

http://code.angularjs.org/1.2.0rc1/angular-resource.js

Module Configuration:

var myApp = angular.module('MyApp', ['ngResource']);
myApp.config(['$routeProvider', ,'$httpProvider', function($routeProvider, $httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    ....
  }
]);

function: $resource(url[, paramDefaults][, actions]);

var User = $resource('http://localhost:port/sil/SilUserAuth.svc/Login', {port:':59217'}, { });
User.get({
       name: document.loginForm.email.value,
       password: document.loginForm.password.value
}, function (data) {
       alert(JSON.stringify(data));
});

Result on Firebug View:

GET http://localhost:59217/sil/SilUserAuth.svc/Login?name=abc&password=abc   200s OK 12ms

In ASP.NET MVC 4:

<script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/angular-resource.js")"></script>

Set httpProtocol on Web.config

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>

Problem 1

OPTIONS xxxxxxxxx (405 Method Not Allowed)

Solution
Remove the header from all requests :

"delete $httpProvider.defaults.headers.common['X-Requested-With'];"

Problem 2

Angularjs Error: destination.push is not a function

Solution
Define action type get / query / update / delete and  add isArray: true:

    var Papers = $resource('http://localhost:port/Sil/SilUserPaper.svc/UserPapers/:id', { port: ':59217' }, {
        get: { method: 'GET', params: {}, isArray: true }
    });
    Papers.get({
        id: 2
    }, function (data) {
        $scope.papers = data;
    });

How to improve your jQuery

1. Use unique ‘id’ when selecting (Fastest)

$('#btnTest'); //Correct
$('input#btnDiv'); //Wrong
$('#btnDiv #btnTest'); //Wrong

 
2. Use ‘tag’ before select ‘class’

$('input.setOfButton');

 
3. One select to do all works

// Correct
$('#btnTest')
	.val('Test')
	.css('color', 'red');
	.show();

// Wrong
$('#btnTest').val('Test');
$('#btnTest').css('color', 'red');
$('#btnTest').show();

 
4. Reduce append times

// Correct
var appendHTML = '';
for(var i=0; i<10; i++) {
	appendHTML += '<p>' + i + '</p>';
}
$('#divTest').append(appendHTML);

// Wrong
var $divTest = $('#divTest');
for(var i=0; i<10; i++) {
	$divTest.append('<p>' + i + '</p>');
}

Select excetly parent

Basically, this is the jQuery basic selector to select a html object.

$('#btnSubmit')

 

How to select a parent?

$('#btnSubmit').parent() // my parent
$('#btnSubmit parent') // my top parent

 

But browser will add <tbody> to our <table>, so that we can’t select excetly parent by

$('#btnSubmit').parent().parent().parent().parent().parent()

 

Solution:

$('#btnSubmit').closest('table')

Select the closest table parent, you may use class to instead table

Print Javascript Object: [object Object]

While you want to check out what’s inside the javascript object, you cannot directly alert the object.
This is how you print all the properties and values of javascript object.

// Assume the object names "data"

// 1. JSON
alert(JSON.stringify(data, null, 4));

// 2. Loop
var obj = data, opt = '';
for (prop in obj) opt += 'object[' + prop + '] = ' + obj[prop]+'\n---\n';
alert(opt);