Skip to content. | Skip to navigation

Personal tools

Navigation

You are here: Home / Tips / AJAX Tips

AJAX Tips

通常是指客戶端的 JavaScript 特效功能,常見模組像是 jQuery 或 KSS 等。

Tooling Hell

JavaScript 的工具種類很多,Plone 已陸續調整內建支援,在 3.1 版本開始 jQuery 支援,在 4.0 版本開始 jQuery Tool 支援,在 4.3 版本開始移除 KSS 的內建支援。

Plone  p.a.jquery p.a.jquerytools
3.x  
4.2.2  1.4.4      1.3.2
4.3.0  1.7.2      1.5.5
4.3.1  1.7.2      1.5.5
4.3.2  1.7.2      1.5.6
4.3.7  1.7.2.1    1.7.0

p.a.jquerytools 要搭配 jquery.form jquery.tools

jQuery 可以用 Browser API 取代

jQuery QuickStart

$(fuction(){}) 是 $(document).ready(function(){}) 的縮寫,代表會等到 HTML 讀完才執行。原理介紹 入門影片 入門範例 版本議題 選單範例 "jq" 換成 "$" noConflict() method

整合進 Plone 的方式,有兩種,一是透過 portal_skins 最後存放在 ZODB 裡,二是透過 Resource Folder 從模組存取。可能要再註冊後,才能使用,註冊方式是在 portal_javascripts 手動新增,或是透過 GenericSetup 的 jsregistry.xml 在模組裡新增。利用 portal_javascripts 新增的檔案,會自動做到:檔案壓縮、檔案合併、載入條件的判斷、支援 IE 的條件語法。

"live" vs "on" event: 新版 jQuery 不建議使用 live event 改成 on event。

傳送 navroot 變數值

Comparison Table

利用 request 的 ajax_load 變數可以加快網頁內容的產生,當 ajax_load=1 或 ?ajax_load=1&ajax_include_head=1 時,HTML Tag 裡的 CSS 或 JavaScript 不會被載入,plone.portaltop 或 plone.portalfooter ViewletManager 不會被載入,Portlet 也不會被載入。從 Plone 4.0.3 開始,在 iframe 場合可以應用這個技巧。

<html>
<head></head>
<body>
 <h1>Boxing Plone</h1>
 <div>
  <iframe width="480" height="200"
          src="http://localhost:8080/Plone/login?ajax_load=1&ajax_include_head=1"></iframe>
 </div>
 <div>
  <iframe width="480" height="260"
          src="http://localhost:8080/Plone/sitemap?ajax_load=1&ajax_include_head=1"></iframe>
 </div>
</body>
</html>

在網址後面加上 ?disable_plone.leftcolumn=1 可以取消左側 Portlet 顯示,在 Page Template (範例 sitemap.pt) 的場合,可使用下列語法:

disable_column_one python:request.set('disable_plone.leftcolumn',1);
disable_column_two python:request.set('disable_plone.rightcolumn',1);

Image Popup

jQuery( function($) {
  $('img.image-right, img.image-left, img.image-inline')
    .prepOverlay({
      subtype: 'image',
      urlmatch: '/image_.+$',
      urlreplace: '/image_preview'
      });
});

iFrame Resizer: collective.js.iframeresizer

Plug-in: Page Piling MultiScroll

載入及執行順序

JavaScript 載入及執行順序可能會影響實際結果,參考 collective.z3cform.widgets collective.ckeditorcollective.carousel vs TinyMCE 的範例。內建的constructor 屬性用來儲存「建立物件的函式」參照值,不過,它可能會在執行過程中消失而造成錯誤

Nathan Van Gheem on collective.documentviewer: I have had EXTREMELY bad experience depending on those annoying python js packages where they break my addons and cause me to do a bunch of extra work. In fact because of this, collective.plonetruegallery does not depend on ANY collective.js packages and neither do it's add-on packages(collective.ptg.*). I've had this same conversion multiple times with other people that I'm having with you. Every time I've caved and included a collective.js requirement it's broken my addons multiple times afterwards for various reasons. I like have a tight coupling between the js required for an addon and the addon. The only way I can do this is include the js resources. And embedding the js in the template is better than including it in resource registries. It's silly to put things in the registry when you only need it for one view. Long term, something like requirejs or even just using fanstatic might be a better way to go.

collective.taxonomy: React/Redux view to edit taxonomy data

plone.app.jquery dependency 學習 Plone + jQuery 的建議: 單獨先看 jQuery 教學,試試 Accordion 範例,再練習 Browser View 呈現 jQuery 特效,再把 JavaScript CSS 檔案註冊到 portal_javascript 和 portal_css。

討論 jQuery UI 成為內建模組的優劣,待加 time / timezone 的支援,並改善 date input 功能,結論是 Plone 打算自行整理出輕量級的模組。

同時安裝兩種版本的 jQuery: collective.js.jqueryui

lazy loading carousel

Image Zoom

Plugin Example CloudZoom

Products.pipbox breaks JavaScript

Message Box for Browser Upgrading

Handle HTTP status code 500 explicitly

WebFont to Display Icon

safe compression in portal_javascripts, bundle 'default' or 'jqueryui'

Create JS Bundles: http://bower.io/

Register For Specific View

tomcom.plone.jssort

collective.js.dygraphs: Dygraphs JS Library UML Sequence Diagram

collective.js.jquerygatt cioppino.twothumbs

TOC Table of Content

bda.plone.ajax

結束 Overlay 指定 View Redirection Popup Overlay not Rendering

collective.js.jquery 造成 plone.app.contenttypes 衝突

Create a Mixin to share methods from view and tile, this way we have just one place to change.

class PhotoGalleryMixin:
  """Common methods and functions used by views and tiles."""
    def js_resources(self):
        """Return a list of JS resources that are not available in the
        registry, but need to be loaded anyway. This way the slideshow
        could use resources registered locally or globally.
        :returns: list of ids
        :rtype: list
        """
        js_registry = api.portal.get_tool('portal_javascripts')
        global_resources = js_registry.getResourceIds()
        return [r for r in JS_RESOURCES if r not in global_resources]

Media Type: application/javascript vs text/javascript

Dynamic Chartist.js Charts Using Flask and jQuery

HighlightSearchTerms: mark.js

<script type="text/javascript">
    jQuery(function($){
        $.datepicker.setDefaults(
            jQuery.extend($.datepicker.regional['zh-TW'],
            {dateFormat: 'yy/mm/dd'}));
    });
</script>

CSS

背景知識 CSS Specificity: Sorting Order

ID vs CLASS

DIV vs SPAN

Centering 凸排

Wrapping Text Around Image

Tab Styles Inspiration

Page Preloading Effect

Image Captions

FontAwesome Icono Cross Browser Inline-Block

Multiple ID Names Using the Same Code

Awesome Tutorials to Master Responsive Web Design

check CSS in context folder

Checkbox Hack All Select / Unselect

<head>
<script type="text/javascript">
function check_all(obj,cName)
{
  var checkboxs = document.getElementsByName(cName);
  for(var i=0;i<checkboxs.length;i++){checkboxs[i].checked = obj.checked;}
}
</script>
</head>

<body>
<p><input type="checkbox" name="all" onclick="check_all(this,'c')" />全選/全不選</p>
<p><input type="checkbox" name="c" value="" /></p>
<p><input type="checkbox" name="c" value="" /></p>
<p><input type="checkbox" name="c" value="" /></p>
<p><input type="checkbox" name="c" value="" /></p>
</body>

使用 jquery all deselect all checkbox 搜尋 Google Images 範例: 單層 多層

CSS3 Tutorial Simple and Smart CSS Snippets

HTML 5 JavaScript API Index Specific Visualizations Visualization Tools

HTML5 Rocks HTML5 Canvas Tutorials

HTML5 and CSS3 Fundamentals

border-radius safari

Products.Ploneboard CSS hides TinyMCE Styles

TinyMCE HTML5

PhantomJS 處理 CSS children selection in Overlay 並不理想。

CSS Shapes Editor for Brackets

Support Several Galleries At the Same Time

z-index dialog disappear: Products.ImageEditor

Misplaced Input Element in Chrome

Grid Layout Picachu Eevee

IE8 trim fuction: eea.tags IE11: z3c.form OrderedSelectWidget

Firefox Menu Heading

Pseudo Element Roundup 範例說明 printing

CSS Preprocessor 可以協助模組化,常見工具像 LESS、SASS、Stylus。

LESS Variable 範例 @nice-blue: #5B83AD; @light-blue: @nice-blue + #111; 透過 Mix-in 可以把設定值整批複製,也支援 Nested Rule 語法,並使用 ~'anything' 來 Escaping,使用 percentage() saturate() spin() 進行函式運算,使用 #Namespace > .mixin-name 來存取 Bundle 裡的 Mix-in 或 Variable,使用 @import "library"; 來載入 library.less 內容。

.clearfix {
  display: block;
  zoom: 1;

  &:after {
    content: " ";
    display: block;
    clear: both;
    visibility: hidden;
  }
}
.screen-color {
  @media screen {
    color: green;
    @media (min-width: 768px) {
      color: red;
    }
  }
  @media tv {
    color: black;
  }
}

Code Syntax Highlighting - plonetheme.fui uses google code prettify

Font Awesome HTML5 中文 Responsive 換行顯示

History Map with Timeline TimelineJS knightlab Vis.js d3-timeline Tiki-Toki OKFN TimeMapper

uri.js : URI parser

jQuery

Parallax Example Parallax Scrolling Demo + Tutorial

Selection Widget Background Color

1.7 版後 live() 改用 on() MultiSelect Dropdown Multiple Elements

確保文件完全載入再執行程式碼

(function($) { $(function() {
    // code here
}); })(jQuery);

小技巧:

document.getElementById('element').style.display = "none"
$('#element').hide()

Tab View of Folder or Collection: vs.tdi redomino.tabsandslides Popular Plugins

plone.app.jquerytools vs collective.js.jqueryui (big overhead): Products.DataGridField DateColumn

jQueryTools beforepost vs afterpost eea.facetednavigation - jQuery b_start[] vs Server b_start:int

整合 jQuery UI 的介紹 jQuery UI 造成 tab 失效 4.0 昇級到 4.2 案例 zettwerk.ui themeroller zettwerk.clickmap

Tabs

<!-- the tabs -->
<ul class="tabs">
<li><a href="#">Tab 1</a></li>
<li><a href="#">Tab 2</a></li>
</ul>
<!-- tab "panes" -->
<div class="panes">
<div>pane 1 content</div>
<div>pane 2 content</div>
</div>

$(".tabs").tabs(".panes > div");

Root Div Pattern

<div id="mytabs">
<h2>Title 1</h2>
<div class="pane">pane 1 content</div>
<h2>Title 2</h2>
<div class="pane">pane 2 content</div>
</div>

$("#mytabs").tabs(".pane", {tabs:'h2'});

FancyZoomView: github repo

dataTables collective.js.datatables DropDownMenu collective.superfish 需要新版 jQuery 的調整方法 FlexiNav

Sort Results By Date Table Export As PDF Excel PDF Generation

TimeJS: collective.timelines

jQuery Plugin for CSS Animated Page Transitions

jquery.dynatree.js 用到 jQuery UI

noUiSlider: plugin refreshless.com

jcarousel, jslide (from meteor theme)

Scrollable

<a class="prev browse left"></a>
<div class="scrollable">
 <div class="items">
  Multiple items in blocks
 </div>
</div>
<a class="next browse right"></a>

$(".scrollable").scrollable();

TextArea Scroll Bar

Reduced Scrollable for IE8: collective.carousel

建議使用 bundle 方式進行整合

$(document).ready vs $(window).load

TinyMCE new code

if until now you intialized you js code like:

$(document).ready(function() { 
// some initialization code 
}); 

you have to change it to:: 

function initPlugin(context) { 
// some initialization code 
} 
if ($.plone && $.plone.init) { 
    $.plone.init.register(initPlugin) 
} else { 
    $(document).ready(function() { initPlugin(document); }); 
}

modernizr

galleria: collective.nitf

plone.app.toolbar

plone.app.angularjs AngularJS + Yeoman KickStarter

Date Time Picker

jquery-timepicker with jquery-datepair plugin Show only Month and Year in jQuery UI DatePicker

1) jQuery Timer Plugin 2) Timepicki 3) PickMeUp 4) flipCountDown 5) Flipclock.js 6) Mobiscroll

HTML5 Sharing View: jQuery Reimplementation in Plone 4.3

template TAL 變數傳遞

Open New Popup Window and Post Data to It

collective.js.supersized

plone.formwidget.autocomplete Stops Working If collective.js.jqueryui Installed

新增活動時,沒問題,但在編輯活動時,最下方的儲存鈕和邊側資訊方框,都沒有出現,JavaScript 錯訊息是 Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method

首先追查到 jQuery UI 的討論,在 versions.cfg 裡有 collective.js.jqueryui = 1.10.3,到 github 看到和 plone.formwidget.autocomplete 衝突的訊息,表示 plone.formwidget.autocomplete 該被修訂

Overlays

搭配 plone.app.jquerytools

<a id="hitme" href="..."> link text </a>

$('#hitme').prepOverlay(
  { type: 'image' | 'ajax' | 'iframe' }
);
<a class="newsImageContainer"
 href=".../image/image_view_fullscreen">
  <imag ... />
</a> $('a.newsImageContainer').prepOverlay( { type: 'image', urlmatch: '/image_view_fullscreen$', urlreplace: '_preview' } );
<a id="hitme" href="..."> link text </a>
...
<form id="myform" ... </form>

$('#hitme').prepOverlay({
 type: 'ajax',
 filter: '#content>*',
 formselector: '#myform',
 noform: 'close' | 'reload' | 'redirect'
});

overlays and registration

Dynamic CSS based on Time

Instead trying to dynamically switch the theme server side, I would recommend a bit of javascript inline in the head and add an appropriate class name to the html element:

var hour = (new Date).getHours();
if (hour < 8 || hour > 20) {
   document.documentElement.className += " night"; }
else {
   document.documentElement.className += " day"; }

You can then use these classes in your CSS.

Content Link

Accordion

本質和 Tab 一樣 搭配 All Content View 的範例: 首先要找出作用的 HTML 段落,常見問題之一是,格式順序未必馬上符合 jQuery 的要求:

<div id="content-core">
 <h2 class="headline">
 <div class="item">
  <dl>Body stuff</dl>
 </div>
 <h2 class="headline">
 <div class="item">
  <dl>Body stuff</dl>
 </div>
</div>

下列是用來調換 h2 和 div class="item" 順序的程式碼:

<script type="text/javascript" language="javascript">
  jQuery(function($) {
    $("body.template-folder_full_view .item h2").each(function((){
      $(this).parent().before($(this));
    });
});
</script>

Plone.org example

collapsible form example: collective.simplemanagement

MegaMenu

implementation

rich text tile is not saving the content when edited from the compose view

image loading control

string replace

Unit Testing Browser JavaScript

jslint pass example at plone.app.event

Disable CSS/JavaScript Merging

Simple Rich Text

nitf collapsible

QR Codes

Spinner Animation

Regular Expression Library

jQuery Optimization

  • Select IDs first, then filter/find;
  • If not IDs, then go for tags;
  • Save & re-use selections;
  • Minimize iterations and work in iterations;
  • Use .detach(): don’t rebuild DOM elements;

JavaScript Optimization

  • Minimize work in iterations;
  • Don’t use eval;
  • Learn & use JS built-ins;
  • Learn & use regular expressions;
  • Break up the work: 1) Think UI; do work "just in time;" 2) document.ready vs. window.load 3) Think threads; use timers & events; 4) Weigh AJAX vs. latency issues

KSS

由 plone.app.kss 提供功能,在 Plone3 有個 kss-base-url 的 Header 設定值。

Remove Dependency: collective.panels

KSS portlet

Related content
Photo Gallery