Jquery,Coffeescript Snippet 모음
스타일 변화 시키기
$('HTML').addClass('JS');
* In your css */
.JS #myDiv{display:none;}
coffee script 에서 함수 호출
contents+="<li class='city_candidate' onclick='h(\""+data[v]+"\")'>"+v+"</li>"
@h = h = (set) ->
$('span#cityoutput').replaceWith("<span id='cityoutput'>"+set+"</span>")
Ajax Callback
url = "locations"
request = $.get url,data
request.success (data) -> $("#regionresults").html(data)
request.error (jqXHR, textStatus, errorThrown) -> $("#regionresults").append "AJAX Error: ${textStatus}."
Slide UP
jQuery ->
$(".search input").focus ->
if @value == "Search"
@value = ""
@className = "textinput" $(".search input").blur ->
if @value == ""
@value = "Search"
@className = "placeholder"
$('#message').css { border: '1px solid red' }
$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
Sticky layer
sticky = () ->
y = $(window).scrollTop()
if y > $('#topnavigation').height()
$('#topnavigation').css({
'position': 'fixed',
'top': '0',
'z-index': "4444"
'width': $('#top_navigation').width(), 'box-shadow': '0px 20px 20px -15px #CCC'
})
$('#topnavigation').removeClass("sixteen columns alpha")
$('#main').css({'padding-top': $('#topnavigation').height()})
else
$('#topnavigation').removeAttr('style')
$('#main').removeAttr('style')
$('#topnavigation').addClass("sixteen columns alpha")
$(window).scroll(sticky)
$(window).resize(sticky)
페이드인 메시지
msg = "world"
inv = "you"
show_message = (x,y) ->
$('span#message').hide().text(x).fadeIn(1000,
-> $('span#message').append('!')
)
$('#hint').hide().text(x).fadeIn(0)$ ->
showmessage msg,inv
[inv, msg] = [msg, inv]
$('span#message').click ->
showmessage inv,msg
[inv, msg] = [msg, inv]
message fadein and out
.fadeIn(30).fadeOut(1000);
다이나믹 add remove
$('input#addlanguageskill').on 'click', () ->
num = ($('.languageskillinnerbox').length)-1
newNum = new Number(num+1)
sourceElem = $('div#languageskill' +num)
newElem = sourceElem.clone().prop('id','languageskill'+newNum)
newElem.find("#userlanguageskillsattributes"+num+"languageid").prop({id:'userlanguageskillsattributes'+newNum+'languageid',name:'user[languageskillsattributes]['+newNum+'][languageid]'})
newElem.append('<input onclick="remove(\''+newElem.prop('id')+'\')" id="removelanguageskill"'+newNum+' type="button" value="Remove Language"/>')
sourceElem.after(newElem)
@remove = remove = (elemid) ->
alert "remove : "+elemid
$("#"+elem_id).remove()
Nested Model Form 예제
<% formfor @person do |personform| %> <%= personform.label :name %>
<%= personform.text_field :name %>
<% personform.fieldsfor :children do |child_form| %>
<%= childform.label :name %>
<%= childform.text_field :name %>
<% unless childform.object.newrecord? %>
<% # Don't forget to name both of these 'destroy' in Rails 3 %>
<%= childform.checkbox 'delete' %>
<%= childform.label 'delete', 'Remove' %>
<% end %>
<% end %>
<%= submit_tag %>
<% end %>
그리즈 몽키 ajax 콜
var jqxhr = $.ajax({
type: "POST",
url: trackback,
headers: {'User-Agent': 'Trackback',
'Content-Type':'application/x-www-form-urlencoded; charset=utf8'},
data: inputdata,
datatype:"text"
});
jqxhr.done(function() {
GMlog("Trackback Success : "+jqxhr.responseText);
});
jqxhr.fail(function(data,statusText,error) {
GM_log("Trackback faild : "+statusText+" [ "+error+", "+data.responseText+" ]");
});
셀렉트 박스 정렬
sortingSelectBox(selectTagId,sortBy,order)
selectTagId <select id="selectTagId"></select>
sortBy [0:Text, 1:Value] - default:0
order[0:Ascending, 1:Descending] - default:0
Examples
sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order
sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order
sortingSelectBox("mySelectTagId") sortBy Text in Ascending order
sortingSelectBox = (selectBoxId,sortBy,order) ->
sortBy ?= 0
order ?= 0
sortVal = 0
if order is 1 then sortVal = 2
orderValLeft = -1 + sortVal
orderValRight = 1 - sortVal
selectBox = $("select#"+selectBoxId)
options = $("select#"+selectBoxId+" option")
selectedVal = selectBox.val()
sortedOption = options.clone()
options.empty().remove()
switch sortBy
when 0
sortedOption.sort((left,right)->
leftText = left.text.toLowerCase()
rightText = right.text.toLowerCase()
if leftText < rightText then return orderValLeft
if leftText is rightText then return 0
orderValRight
)
else
sortedOption.sort((left,right)->
leftVal = left.value
rightVal = right.value
if leftVal < rightVal then return orderValLeft
if leftVal is rightVal then return 0
orderValRight
)
selectBox.append(sortedOption)
selectBox.val(selectedVal)
sortingSelectBox("country")
리다이렉트
// simulates similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
JQuery 데이터 타입
dataTypeString
Default: Intelligent Guess (xml, json, script, or html)
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are: "xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string.
multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
/*
If you wish to use any of the meta-characters
( such as !"#$%&'()*+,./:;?@[]^`{|}~ ) as a literal part of a name,
you must escape the character with two backslashes: . For example,
if you have an an element with id="foo.bar", you can use the selector
$("#foo.bar").
*/
Session based tokens
If you are using session based tokens, you probably generate a secure token when generating the session, and store that token in the session. When a request comes back to the server, you check that the token is included in the request and compare it to what's in the session. If it's the same token, you accept the request, if not you reject it.
To use this token with jQuery, you need to make it available to javascript. You typically do this by adding it as a javascript variable.
var csrftoken = '<%= tokenvalue %>';
Next, the trick is to bind to the global ajaxSend event, and add the token to any POST request
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});
rails-3-1-and-jquery-ui-assets 설정
# http://stackoverflow.com/questions/6133818/rails-3-1-and-jquery-ui-assets
$ cat app/assets/javascripts/application.js
//= require jquery
//= require jquery-ui
$ cat app/assets/stylesheets/application.css
/*
*= require vendor
*
*/
$ cat vendor/assets/stylesheets/vendor.css
/*
*= requiretree ./jqueryui
*
*/
vendor/assets/ $ tree
stylesheets
vendor.css
jqueryui
jquery-ui-1.8.13.custom.css
...
images
jqueryui
ui-bgflat0aaaaaa40x100.png
...
Finally run this command:
vendor/assets/images $ ln -s jquery_ui/ images
Get center
$(document).ready(function(){
jQuery.fn.center = function () {
this.css("top",$(window).height()/2-this.height()/2 + "px");
this.css("left",$(window).width()/2-this.width()/2 + "px");
return this;
}
$("#container").center();
});
Multiple selector
$("#txt1, #txt2, #txt3").keyup(fn);
Jquery check CKEditor
$(this).data('initialForm', $(this).serialize());
to
$(this).data('initialForm', $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor));
And a similar change to line 4 from
if ($(this).data('initialForm') != $(this).serialize()) {
to
var formData = $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor);
if ($(this).data('initialForm') != formData) {
Jquery Defer
(function() {
function getScript(url,success){
var script=document.createElement('script');
script.src=url;
var head=document.getElementsByTagName('head')[0],
done=false;
script.onload=script.onreadystatechange = function(){
if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
done=true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
// YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
});
})();
Scroll to top
var destination = $(‘#idToScrollTo’).offset().top;
$(‘html’).animate({scrollTop: destination},600);
CKEDITOR
config.toolbar = 'Modati'
config.toolbar_Modati = [['Bold', 'Italic', 'Underline','Strike', '-', 'RemoveFormat','-', 'Outdent','Indent','-','Blockquote','HorizontalRule', '-', 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','FontSize','TextColor','BGColor']]CKEDITOR.editorConfig = function( config )
{
config.toolbar = 'MyToolbar';
config.toolbar_MyToolbar =
[
{ name: 'document', items : [ 'NewPage','Preview' ] },
{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
{ name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'
,'Iframe' ] },
'/',
{ name: 'styles', items : [ 'Styles','Format' ] },
{ name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
{ name: 'tools', items : [ 'Maximize','-','About' ] }
];
};
config.toolbar = 'Full';
config.toolbarFull =
[
{ name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
{ name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
'HiddenField' ] },
'/',
{ name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv','-
','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
{ name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
'/',
{ name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
{ name: 'colors', items : [ 'TextColor','BGColor' ] },
{ name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] }
];
config.toolbarBasic =
[
['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About']
];
CKEDITOR.editorConfig = function( config )
{
config.extraPlugins = "customparagraph";
config.toolbar = [ [ 'ThinyP' ] ]; // add other toolbars and keep in mid this can be overwritten in page which loads CKEditor
};
<script type="text/javascript">
//<![CDATA[
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1',
{
extraPlugins : 'customparagraph',
toolbar :
[
[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
[ 'ThinyP' ]
]
});
//]]>
</script>
in the main ckeditor config-file there is an option to disable automatic <p> inserts. try to change the value of CKConfig.EnterMode and CKConfig.ShiftEnterMode for example to 'br'.
config.enterMode = CKEDITOR.ENTER_BR
lostmorethanfive, lostbeetweenfourandfive, lostbeetweenthreeandfour, lostbeetweentwoandthree, lostbeetweenoneandtwo, lostbeetweenzeroandone, gainedbeetweenzeroandone, gainedbeetweenoneandtwo,gainedbeetweentwoandthree, gainedbeetweenthreeandfour, gainedbeetweenfourandfive,gainedbeetweenfiveandsix, gainedbeetweensixandseven,gainedmorethanseven
출처