I want to use iCheck library:
https://github.com/fronteed/iCheck
http://fronteed.com/iCheck/
When i init the element with the library it get warped like the documentation describe https://github.com/fronteed/iCheck/#how-it-works but with opacity zero.
You can see it here: http://jsfiddle.net/buRq7/8/
$(".ex-f").iCheck();
somebody have the same issue?
Thanks
My code is:
/*!
* iCheck v1.0.1, http://git.io/arlzeA
* =================================
* Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization
*
* (c) 2013 Damir Sultanov, http://fronteed.com
* MIT Licensed
*/
(function($) {
// Cached vars
var _iCheck = 'iCheck',
_iCheckHelper = _iCheck + '-helper',
_checkbox = 'checkbox',
_radio = 'radio',
_checked = 'checked',
_unchecked = 'un' + _checked,
_disabled = 'disabled',
_determinate = 'determinate',
_indeterminate = 'in' + _determinate,
_update = 'update',
_type = 'type',
_click = 'click',
_touch = 'touchbegin.i touchend.i',
_add = 'addClass',
_remove = 'removeClass',
_callback = 'trigger',
_label = 'label',
_cursor = 'cursor',
_mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent);
// Plugin init
$.fn[_iCheck] = function(options, fire) {
// Walker
var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]',
stack = $(),
walker = function(object) {
object.each(function() {
var self = $(this);
if (self.is(handle)) {
stack = stack.add(self);
} else {
stack = stack.add(self.find(handle));
};
});
};
// Check if we should operate with some method
if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) {
// Normalize method's name
options = options.toLowerCase();
// Find checkboxes and radio buttons
walker(this);
return stack.each(function() {
var self = $(this);
if (options == 'destroy') {
tidy(self, 'ifDestroyed');
} else {
operate(self, true, options);
};
// Fire method's callback
if ($.isFunction(fire)) {
fire();
};
});
// Customization
} else if (typeof options == 'object' || !options) {
// Check if any options were passed
var settings = $.extend({
checkedClass: _checked,
disabledClass: _disabled,
indeterminateClass: _indeterminate,
labelHover: true,
aria: false
}, options),
selector = settings.handle,
hoverClass = settings.hoverClass || 'hover',
focusClass = settings.focusClass || 'focus',
activeClass = settings.activeClass || 'active',
labelHover = !!settings.labelHover,
labelHoverClass = settings.labelHoverClass || 'hover',
// Setup clickable area
area = ('' + settings.increaseArea).replace('%', '') | 0;
// Selector limit
if (selector == _checkbox || selector == _radio) {
handle = 'input[type="' + selector + '"]';
};
// Clickable area limit
if (area < -50) {
area = -50;
};
// Walk around the selector
walker(this);
return stack.each(function() {
var self = $(this);
// If already customized
tidy(self);
var node = this,
id = node.id,
// Layer styles
offset = -area + '%',
size = 100 + (area * 2) + '%',
layer = {
position: 'absolute',
top: offset,
left: offset,
display: 'block',
width: size,
height: size,
margin: 0,
padding: 0,
background: '#fff',
border: 0,
opacity: 0
},
// Choose how to hide input
hide = _mobile ? {
position: 'absolute',
visibility: 'hidden'
} : area ? layer : {
position: 'absolute',
opacity: 0
},
// Get proper class
className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio,
// Find assigned labels
label = $(_label + '[for="' + id + '"]').add(self.closest(_label)),
// Check ARIA option
aria = !!settings.aria,
// Set ARIA placeholder
ariaID = _iCheck + '-' + Math.random().toString(36).replace('0.', ''),
// Parent & helper
parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''),
helper;
// Set ARIA "labelledby"
if (label.length && aria) {
label.each(function() {
parent += 'aria-labelledby="';
if (this.id) {
parent += this.id;
} else {
this.id = ariaID;
parent += ariaID;
}
parent += '"';
});
};
// Wrap input
parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert);
// Layer addition
helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent);
// Finalize customization
self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide);
!!settings.inheritClass && parent[_add](node.className || '');
!!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id);
parent.css('position') == 'static' && parent.css('position', 'relative');
operate(self, true, _update);
// Label events
if (label.length) {
label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) {
var type = event[_type],
item = $(this);
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
if ($(event.target).is('a')) {
return;
}
operate(self, false, true);
// Hover state
} else if (labelHover) {
// mouseout|touchend
if (/ut|nd/.test(type)) {
parent[_remove](hoverClass);
item[_remove](labelHoverClass);
} else {
parent[_add](hoverClass);
item[_add](labelHoverClass);
};
};
if (_mobile) {
event.stopPropagation();
} else {
return false;
};
};
});
};
// Input events
self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) {
var type = event[_type],
key = event.keyCode;
// Click
if (type == _click) {
return false;
// Keydown
} else if (type == 'keydown' && key == 32) {
if (!(node[_type] == _radio && node[_checked])) {
if (node[_checked]) {
off(self, _checked);
} else {
on(self, _checked);
};
};
return false;
// Keyup
} else if (type == 'keyup' && node[_type] == _radio) {
!node[_checked] && on(self, _checked);
// Focus/blur
} else if (/us|ur/.test(type)) {
parent[type == 'blur' ? _remove : _add](focusClass);
};
});
// Helper events
helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) {
var type = event[_type],
// mousedown|mouseup
toggle = /wn|up/.test(type) ? activeClass : hoverClass;
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
operate(self, false, true);
// Active and hover states
} else {
// State is on
if (/wn|er|in/.test(type)) {
// mousedown|mouseover|touchbegin
parent[_add](toggle);
// State is off
} else {
parent[_remove](toggle + ' ' + activeClass);
};
// Label hover
if (label.length && labelHover && toggle == hoverClass) {
// mouseout|touchend
label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass);
};
};
if (_mobile) {
event.stopPropagation();
} else {
return false;
};
};
});
});
} else {
return this;
};
};
// Do something with inputs
function operate(input, direct, method) {
var node = input[0],
state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked,
active = method == _update ? {
checked: node[_checked],
disabled: node[_disabled],
indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false'
} : node[state];
// Check, disable or indeterminate
if (/^(ch|di|in)/.test(method) && !active) {
on(input, state);
// Uncheck, enable or determinate
} else if (/^(un|en|de)/.test(method) && active) {
off(input, state);
// Update
} else if (method == _update) {
// Handle states
for (var state in active) {
if (active[state]) {
on(input, state, true);
} else {
off(input, state, true);
};
};
} else if (!direct || method == 'toggle') {
// Helper or label was clicked
if (!direct) {
input[_callback]('ifClicked');
};
// Toggle checked state
if (active) {
if (node[_type] !== _radio) {
off(input, state);
};
} else {
on(input, state);
};
};
};
// Add checked, disabled or indeterminate state
function on(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== true) {
// Toggle assigned radio buttons
if (!keep && state == _checked && node[_type] == _radio && node.name) {
var form = input.closest('form'),
inputs = 'input[name="' + node.name + '"]';
inputs = form.length ? form.find(inputs) : $(inputs);
inputs.each(function() {
if (this !== node && $(this).data(_iCheck)) {
off($(this), state);
};
});
};
// Indeterminate state
if (indeterminate) {
// Add indeterminate state
node[state] = true;
// Remove checked state
if (node[_checked]) {
off(input, _checked, 'force');
};
// Checked or disabled state
} else {
// Add checked or disabled state
if (!keep) {
node[state] = true;
};
// Remove indeterminate state
if (checked && node[_indeterminate]) {
off(input, _indeterminate, false);
};
};
// Trigger callbacks
callbacks(input, checked, state, keep);
};
// Add proper cursor
if (node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'default');
};
// Add state class
parent[_add](specific || option(input, state) || '');
// Set ARIA attribute
disabled ? parent.attr('aria-disabled', 'true') : parent.attr('aria-checked', indeterminate ? 'mixed' : 'true');
// Remove regular state class
parent[_remove](regular || option(input, callback) || '');
};
// Remove checked, disabled or indeterminate state
function off(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== false) {
// Toggle state
if (indeterminate || !keep || keep == 'force') {
node[state] = false;
};
// Trigger callbacks
callbacks(input, checked, callback, keep);
};
// Add proper cursor
if (!node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
};
// Remove state class
parent[_remove](specific || option(input, state) || '');
// Set ARIA attribute
disabled ? parent.attr('aria-disabled', 'false') : parent.attr('aria-checked', 'false');
// Add regular state class
parent[_add](regular || option(input, callback) || '');
};
// Remove all traces
function tidy(input, callback) {
if (input.data(_iCheck)) {
// Remove everything except input
input.parent().html(input.attr('style', input.data(_iCheck).s || ''));
// Callback
if (callback) {
input[_callback](callback);
};
// Unbind events
input.off('.i').unwrap();
$(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i');
};
};
// Get some option
function option(input, state, regular) {
if (input.data(_iCheck)) {
return input.data(_iCheck).o[state + (regular ? '' : 'Class')];
};
};
// Capitalize some string
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
// Executable handlers
function callbacks(input, checked, callback, keep) {
if (!keep) {
if (checked) {
input[_callback]('ifToggled');
};
input[_callback]('ifChanged')[_callback]('if' + capitalize(callback));
};
};
})(window.jQuery || window.Zepto);
$(".ex-f").iCheck();
And
<div class="my-checkbox">
<input class="ex-f" id="Finish" name="Finish" type="checkbox" value="1"> doesn't work
</div>
And
.my-checkbox {
border: 1px solid blue;
height: 20px;
}
.ex-f {
border: 1px solid red;
}
I found that the problem was with the CSS file, if it is not loaded the component is not showed, a working example:
http://jsfiddle.net/SUTMf/1/
$(document).ready(function(){
$('input').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_square',
increaseArea: '20%' // optional
});
});
today i encountered this problem. and the same problem.
but finally solved.
and the reason is:
my local golobal variable name is "_type" which maybe the keyword in iCheck or somethin' else .
when i have iCheck in my Html, i found that _type is already used as the picture showed
wish could help u and the others.
If you place it before the iCheck code, it works for me:
$(".ex-f").iCheck();
//iCheck function
Demo
Well, same thing happened to me, and the problem was a conflict with other javascript code included in the page. I removed it or changed it and it worked. I hope this could help somebody, I don't put the code in here because could be anything, just check your code just in case same thing is happening to you.
Related
I use a plugin that use this block of statements to display menus,Now I use it in angular js.
(function(window) {
'use strict';
var support = { animations : Modernizr.cssanimations },
animEndEventNames = { 'WebkitAnimation' : 'webkitAnimationEnd', 'OAnimation' : 'oAnimationEnd', 'msAnimation' : 'MSAnimationEnd', 'animation' : 'animationend' },
animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ],
onEndAnimation = function( el, callback ) {
var onEndCallbackFn = function( ev ) {
if( support.animations ) {
if( ev.target != this ) return;
this.removeEventListener( animEndEventName, onEndCallbackFn );
}
if( callback && typeof callback === 'function' ) { callback.call(); }
};
if( support.animations ) {
el.addEventListener( animEndEventName, onEndCallbackFn );
}
else {
onEndCallbackFn();
}
};
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function MLMenu(el, options) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
// the menus (<ul>´s)
this.menus = [].slice.call(this.el.querySelectorAll('.menu__level'));
// index of current menu
this.current = 0;
this._init();
}
MLMenu.prototype.options = {
// show breadcrumbs
breadcrumbsCtrl : true,
// initial breadcrumb text
initialBreadcrumb : 'all',
// show back button
backCtrl : true,
// delay between each menu item sliding animation
itemsDelayInterval : 60,
// direction
direction : 'r2l',
// callback: item that doesn´t have a submenu gets clicked
// onItemClick([event], [inner HTML of the clicked item])
onItemClick : function(ev, itemName) { return false; }
};
MLMenu.prototype._init = function() {
// iterate the existing menus and create an array of menus, more specifically an array of objects where each one holds the info of each menu element and its menu items
this.menusArr = [];
var self = this;
this.menus.forEach(function(menuEl, pos) {
var menu = {menuEl : menuEl, menuItems : [].slice.call(menuEl.querySelectorAll('.menu__item'))};
self.menusArr.push(menu);
// set current menu class
if( pos === self.current ) {
classie.add(menuEl, 'menu__level--current');
}
});
// create back button
if( this.options.backCtrl ) {
this.backCtrl = document.createElement('button');
this.backCtrl.className = 'menu__back menu__back--hidden';
this.backCtrl.setAttribute('aria-label', 'Go back');
this.backCtrl.innerHTML = '<span class="icon icon--arrow-left"></span>';
this.el.insertBefore(this.backCtrl, this.el.firstChild);
}
// create breadcrumbs
if( self.options.breadcrumbsCtrl ) {
this.breadcrumbsCtrl = document.createElement('nav');
this.breadcrumbsCtrl.className = 'menu__breadcrumbs';
this.el.insertBefore(this.breadcrumbsCtrl, this.el.firstChild);
// add initial breadcrumb
this._addBreadcrumb(0);
}
// event binding
this._initEvents();
};
MLMenu.prototype._initEvents = function() {
var self = this;
for(var i = 0, len = this.menusArr.length; i < len; ++i) {
this.menusArr[i].menuItems.forEach(function(item, pos) {
item.querySelector('a').addEventListener('click', function(ev) {
var submenu = ev.target.getAttribute('data-submenu'),
itemName = ev.target.innerHTML,
subMenuEl = self.el.querySelector('ul[data-menu="' + submenu + '"]');
// check if there's a sub menu for this item
if( submenu && subMenuEl ) {
ev.preventDefault();
// open it
self._openSubMenu(subMenuEl, pos, itemName);
}
else {
// add class current
var currentlink = self.el.querySelector('.menu__link--current');
if( currentlink ) {
classie.remove(self.el.querySelector('.menu__link--current'), 'menu__link--current');
}
classie.add(ev.target, 'menu__link--current');
// callback
self.options.onItemClick(ev, itemName);
}
});
});
}
// back navigation
if( this.options.backCtrl ) {
this.backCtrl.addEventListener('click', function() {
self._back();
});
}
};
MLMenu.prototype._openSubMenu = function(subMenuEl, clickPosition, subMenuName) {
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
// save "parent" menu index for back navigation
this.menusArr[this.menus.indexOf(subMenuEl)].backIdx = this.current;
// save "parent" menu´s name
this.menusArr[this.menus.indexOf(subMenuEl)].name = subMenuName;
// current menu slides out
this._menuOut(clickPosition);
// next menu (submenu) slides in
this._menuIn(subMenuEl, clickPosition);
};
MLMenu.prototype._back = function() {
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
// current menu slides out
this._menuOut();
// next menu (previous menu) slides in
var backMenu = this.menusArr[this.menusArr[this.current].backIdx].menuEl;
this._menuIn(backMenu);
// remove last breadcrumb
if( this.options.breadcrumbsCtrl ) {
this.breadcrumbsCtrl.removeChild(this.breadcrumbsCtrl.lastElementChild);
}
};
MLMenu.prototype._menuOut = function(clickPosition) {
// the current menu
var self = this,
currentMenu = this.menusArr[this.current].menuEl,
isBackNavigation = typeof clickPosition == 'undefined' ? true : false;
// slide out current menu items - first, set the delays for the items
this.menusArr[this.current].menuItems.forEach(function(item, pos) {
item.style.WebkitAnimationDelay = item.style.animationDelay = isBackNavigation ? parseInt(pos * self.options.itemsDelayInterval) + 'ms' : parseInt(Math.abs(clickPosition - pos) * self.options.itemsDelayInterval) + 'ms';
});
// animation class
if( this.options.direction === 'r2l' ) {
classie.add(currentMenu, !isBackNavigation ? 'animate-outToLeft' : 'animate-outToRight');
}
else {
classie.add(currentMenu, isBackNavigation ? 'animate-outToLeft' : 'animate-outToRight');
}
};
MLMenu.prototype._menuIn = function(nextMenuEl, clickPosition) {
var self = this,
// the current menu
currentMenu = this.menusArr[this.current].menuEl,
isBackNavigation = typeof clickPosition == 'undefined' ? true : false,
// index of the nextMenuEl
nextMenuIdx = this.menus.indexOf(nextMenuEl),
nextMenuItems = this.menusArr[nextMenuIdx].menuItems,
nextMenuItemsTotal = nextMenuItems.length;
// slide in next menu items - first, set the delays for the items
nextMenuItems.forEach(function(item, pos) {
item.style.WebkitAnimationDelay = item.style.animationDelay = isBackNavigation ? parseInt(pos * self.options.itemsDelayInterval) + 'ms' : parseInt(Math.abs(clickPosition - pos) * self.options.itemsDelayInterval) + 'ms';
// we need to reset the classes once the last item animates in
// the "last item" is the farthest from the clicked item
// let's calculate the index of the farthest item
var farthestIdx = clickPosition <= nextMenuItemsTotal/2 || isBackNavigation ? nextMenuItemsTotal - 1 : 0;
if( pos === farthestIdx ) {
onEndAnimation(item, function() {
// reset classes
if( self.options.direction === 'r2l' ) {
classie.remove(currentMenu, !isBackNavigation ? 'animate-outToLeft' : 'animate-outToRight');
classie.remove(nextMenuEl, !isBackNavigation ? 'animate-inFromRight' : 'animate-inFromLeft');
}
else {
classie.remove(currentMenu, isBackNavigation ? 'animate-outToLeft' : 'animate-outToRight');
classie.remove(nextMenuEl, isBackNavigation ? 'animate-inFromRight' : 'animate-inFromLeft');
}
classie.remove(currentMenu, 'menu__level--current');
classie.add(nextMenuEl, 'menu__level--current');
//reset current
self.current = nextMenuIdx;
// control back button and breadcrumbs navigation elements
if( !isBackNavigation ) {
// show back button
if( self.options.backCtrl ) {
classie.remove(self.backCtrl, 'menu__back--hidden');
}
// add breadcrumb
self._addBreadcrumb(nextMenuIdx);
}
else if( self.current === 0 && self.options.backCtrl ) {
// hide back button
classie.add(self.backCtrl, 'menu__back--hidden');
}
// we can navigate again..
self.isAnimating = false;
});
}
});
// animation class
if( this.options.direction === 'r2l' ) {
classie.add(nextMenuEl, !isBackNavigation ? 'animate-inFromRight' : 'animate-inFromLeft');
}
else {
classie.add(nextMenuEl, isBackNavigation ? 'animate-inFromRight' : 'animate-inFromLeft');
}
};
MLMenu.prototype._addBreadcrumb = function(idx) {
if( !this.options.breadcrumbsCtrl ) {
return false;
}
var bc = document.createElement('a');
bc.innerHTML = idx ? this.menusArr[idx].name : this.options.initialBreadcrumb;
this.breadcrumbsCtrl.appendChild(bc);
var self = this;
bc.addEventListener('click', function(ev) {
ev.preventDefault();
// do nothing if this breadcrumb is the last one in the list of breadcrumbs
if( !bc.nextSibling || self.isAnimating ) {
return false;
}
self.isAnimating = true;
// current menu slides out
self._menuOut();
// next menu slides in
var nextMenu = self.menusArr[idx].menuEl;
self._menuIn(nextMenu);
// remove breadcrumbs that are ahead
var siblingNode;
while (siblingNode = bc.nextSibling) {
self.breadcrumbsCtrl.removeChild(siblingNode);
}
});
};
window.MLMenu = MLMenu;
})(window);
and customized java script :
(function() {
var menuEl = document.getElementById('ml-menu');
mlmenu = new MLMenu(menuEl, {
// breadcrumbsCtrl : true, // show breadcrumbs
// initialBreadcrumb : 'all', // initial breadcrumb text
backCtrl : false, // show back button
// itemsDelayInterval : 60, // delay between each menu item sliding animation
onItemClick: loadDummyData // callback: item that doesn´t have a submenu gets clicked - onItemClick([event], [inner HTML of the clicked item])
});
//mobile menu toggle
var openMenuCtrl = document.querySelector('.action--open'),
closeMenuCtrl = document.querySelector('.action--close');
openMenuCtrl.addEventListener('click', openMenu);
closeMenuCtrl.addEventListener('click', closeMenu);
function openMenu() {
classie.add(menuEl, 'menu--open');
}
function closeMenu() {
classie.remove(menuEl, 'menu--open');
}
// simulate grid content loading
var gridWrapper = document.querySelector('.content');
function loadDummyData(ev, itemName) {
ev.preventDefault();
closeMenu();
gridWrapper.innerHTML = '';
classie.add(gridWrapper, 'content--loading');
setTimeout(function() {
classie.remove(gridWrapper, 'content--loading');
gridWrapper.innerHTML = '<ul class="products">' + dummyData[itemName] + '<ul>';
}, 700);
}
})();
I want convert a part of this below customized script to angular js.
mlmenu = new MLMenu(menuEl, {
// breadcrumbsCtrl : true, // show breadcrumbs
// initialBreadcrumb : 'all', // initial breadcrumb text
backCtrl : false, // show back button
// itemsDelayInterval : 60, // delay between each menu item sliding animation
onItemClick: loadDummyData // callback: item that doesn´t have a submenu gets clicked - onItemClick([event], [inner HTML of the clicked item])
});
I use it as this in angular but it has error .
$scope.menuEl = document.getElementById('ml-menu');
var menuEl = document.getElementById('ml-menu'),
mlmenu = new MLMenu(menuEl, {
// breadcrumbsCtrl : true, // show breadcrumbs
// initialBreadcrumb : 'all', // initial breadcrumb text
backCtrl: false, // show back button
// itemsDelayInterval : 60, // delay between each menu item sliding animation
onItemClick: $scope.loadDummyData // callback: item that doesn´t have a submenu gets clicked - onItemClick([event], [inner HTML of the clicked item])
});
How can I do it ?
I think you should wrap your plugin with AngularJS directive https://docs.angularjs.org/guide/directive
I.e. create directive that uses your plugin and initialize it on marked DOM.
angular.module('yourModule')
.directive('mlMenu', function() {
return {
restrict: 'A',
link: function (scope, element) {
var mlmenu = new MLMenu(element,
...
}
};
});
Than in HTML
<div data-ml-menu></div>
And if you are going to modify scope in plugin listeners do not forget to use scope.$apply() wrapper.
I have set up the Cloudinary TinyMCE Plugin and everything seems to be working properly, however, when they popup loads, the Cloudinary CMS screen doesn't resize to the popup. I'm wondering if someone can take a look at the plugin and let me know if there is an easy fix. I can't seem to find anything. Here is a screenshot of the popup:
There is a resize function in cloudinaryimage/js/image.js:
var CloudinaryImageDialog = {
preInit : function() {
tinyMCEPopup.requireLangPack();
},
init : function(ed) {
var base = location.href.replace(/\/[^\/]+$/, '');
var controller = {
socket: new easyXDM.Socket({
name: base + "/easyXDM.name.html",
swf: base + "/easyxdm.swf",
remote: tinyMCE.settings.cloudinary_cms_url,
remoteHelper: "https://cloudinary.com/easyXDM.name.html",
container: "cldimage",
props: {style: {width: "100%", height: "99%"}},
onMessage: function(message, origin){
var json = JSON.parse(message);
switch (json.message) {
case "insert_into_post":
CloudinaryImageDialog.insert_into_post(json);
break;
case "done":
CloudinaryImageDialog.close();
break;
}
},
onReady: function() {
controller.resizeWatcher();
el = ed.selection.getNode();
if (el && el.nodeName == 'IMG') {
var html = ed.selection.getContent({format : 'html'});
controller.socket.postMessage(JSON.stringify({
message: "edit_image",
html: html
}));
}
}
}),
currentWidth: 0,
currentHeight: 0,
resizeWatcher: function() {
jQuery(window).resize(CloudinaryImageDialog.update_window_dimensions);
},
update_window_dimensions: function() {
}
};
},
insert_into_post : function(args) {
delete args.message;
delete args.href;
args["style"] = '';
if (args.align && args.align != '') {
if (args.align == 'left' || args.align == 'right')
args["style"] = "float: " + args.align;
else if (args.align == 'center')
args["style"] = "display: block; margin: auto";
else
args["style"] = "vertical-align: " + args.align;
delete args.align;
}
tinyMCEPopup.restoreSelection();
var ed = tinyMCEPopup.editor;
el = ed.selection.getNode();
// Fixes crash in Safari
if (tinymce.isWebKit) ed.getWin().focus();
if (el && el.nodeName == 'IMG') {
ed.dom.setAttribs(el, args);
} else {
tinymce.each(args, function(value, name) {
if (value === "") {
delete args[name];
}
});
ed.execCommand('mceInsertContent', false, ed.dom.createHTML('img', args), {skip_undo : 1});
ed.undoManager.add();
}
CloudinaryImageDialog.close();
},
close : function() {
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.editor.focus();
tinyMCEPopup.close();
}
};
CloudinaryImageDialog.preInit();
tinyMCEPopup.onInit.add(CloudinaryImageDialog.init, CloudinaryImageDialog);
I figured it out. All that had to be done was add height: 100% to html in image.htm.
We are doing some logic in php to output the image, so the url doesn't have .jpg/etc
This is causing fancybox to exit at the point below where its checking the type. What is the correct way to fix this?
_start: function (index) {
var coming = {},
obj,
href,
type,
margin,
padding;
index = getScalar( index );
obj = F.group[ index ] || null;
if (!obj) {
return false;
}
coming = $.extend(true, {}, F.opts, obj);
// Convert margin and padding properties to array - top, right, bottom, left
margin = coming.margin;
padding = coming.padding;
if ($.type(margin) === 'number') {
coming.margin = [margin, margin, margin, margin];
}
if ($.type(padding) === 'number') {
coming.padding = [padding, padding, padding, padding];
}
// 'modal' propery is just a shortcut
if (coming.modal) {
$.extend(true, coming, {
closeBtn : false,
closeClick : false,
nextClick : false,
arrows : false,
mouseWheel : false,
keys : null,
helpers: {
overlay : {
closeClick : false
}
}
});
}
// 'autoSize' property is a shortcut, too
if (coming.autoSize) {
coming.autoWidth = coming.autoHeight = true;
}
if (coming.width === 'auto') {
coming.autoWidth = true;
}
if (coming.height === 'auto') {
coming.autoHeight = true;
}
/*
* Add reference to the group, so it`s possible to access from callbacks, example:
* afterLoad : function() {
* this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : '');
* }
*/
coming.group = F.group;
coming.index = index;
// Give a chance for callback or helpers to update coming item (type, title, etc)
F.coming = coming;
if (false === F.trigger('beforeLoad')) {
F.coming = null;
return;
}
type = coming.type;
href = coming.href;
if (!type) {
F.coming = null;
//If we can not determine content type then drop silently or display next/prev item if looping through gallery
if (F.current && F.router && F.router !== 'jumpto') {
F.current.index = index;
return F[ F.router ]( F.direction );
}
return false; // this returns false
}
I was able to fix this by adding attribute but it should really just default to image type if its not able to auto work this out.
<a href="" data-fancybox-type="image" class="fancybox">
I'm facing weird behaviour of Jit Infovis i'm using. I have two different html files that include a load json function from a Javascript file. The function is using infovis library to display a hypertree map from a json file. Both two html files load the same json file.
One html file has been succeeded rendering the map properly. But another one has not. It renders the map almost properly, but after i debugged it, i got it not iterating over the root node. Then, the root node becames inactive without label and clickability.
This is the js function i'm using.
var labelType, useGradients, nativeTextSupport, animate;
(function () {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff)) ? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
var Log = {
elem: false,
write: function (text) {
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
this.elem.style.left = (350 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(slugParam, pageParam) {
var isFirst = true;
var isSetAsRoot = false;
// alert(slugParam+ " | "+pageParam);
var url = Routing.generate('trade_map_buyer_json', { slug : slugParam, page : pageParam });
//init data
$.getJSON(url, function (json) {
var type = 'Buyer';
//end
var infovis = document.getElementById('infovis');
infovis.style.align = "center";
infovis.innerHTML = '';
// infovis.innerHTML = '<img align="center" id="gifloader" style="margin-left:50%; margin-top:50%" src="{{ asset('/bundles/jariffproject/frontend/images/preloader.gif') }}" width="30px" height="30px"/>'
var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50;
url = url.replace("/json/", "/");
window.history.pushState("object or string", "Title", url);
//init Hypertree
var ht = new $jit.Hypertree({
//id of the visualization container
injectInto: 'infovis',
Navigation: {
enable: false,
panning: 'avoid nodes',
},
//canvas width and height
width: w,
height
: h,
//Change node and edge styles such as
//color, width and dimensions.
Node: {
dim: 9,
overridable: true,
color: "#66FF33"
},
Tips: {
enable: true,
type: 'HTML',
offsetX: 0,
offsetY: 0,
onShow: function(tip, node) {
// dump(tip);
tip.innerHTML = "<div style='background-color:#F8FFC9;text-align:center;border-radius:5px; padding:10px 10px;' class='node-tip'><p style='font-size:100%;font-weight:bold;'>"+node.name+"</p><p style='font-size:50%pt'>"+node.data.address+"</p></div>";
}
},
Events: {
enable: true,
type: 'HTML',
onMouseEnter: function(node, eventInfo, e){
var nodeId = node.id;
var menu1 = [
{'set as Root':function(menuItem,menu) {
menu.hide();
isSetAsRoot = true;
console.log(nodeId);
init(nodeId, 0);
}},
$.contextMenu.separator,
{'View details':function(menuItem,menu) {
}}
];
$('.node').contextMenu(menu1,{theme:'vista'});
}
},
Edge: {
lineWidth: 1,
color: "#52D5DE",
overridable: true,
},
onBeforePlotNode: function(node)
{
if (isFirst) {
console.log(node._depth);
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
isFirst = false;
}
},
onPlotNode: function(node)
{
if (isSetAsRoot) {
var nodeInstance = node.getNode();
var nodeId = nodeInstance.id;
init(nodeId, 0);
isSetAsRoot = false;
}
},
onBeforeCompute: function (domElement, node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
type = isOdd(dot._depth) ? 'Supplier' : 'Buyer';
},
//Attach event handlers and add text to the
//labels. This method is only triggered on label
//creation
onCreateLabel: function (domElement, node) {
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
domElement.innerHTML = node.name;
// if (node._depth == 1) {
console.log("|"+node.name+"|"+node._depth+"|");
// }
$jit.util.addEvent(domElement, 'click', function () {
ht.onClick(node.id, {
onComplete: function () {
console.log(node.id);
ht.controller.onComplete(node);
}
});
});
},
onPlaceLabel: function (domElement, node) {
var style = domElement.style;
style.display = '';
style.cursor = 'pointer';
if (node._depth <= 1) {
style.fontSize = "0.8em";
style.color = "#000";
style.fontWeight = "normal";
} else if (node._depth == 2) {
style.fontSize = "0.7em";
style.color = "#555";
} else {
style.display = 'none';
}
var left = parseInt(style.left);
var w = domElement.offsetWidth;
style.left = (left - w / 2) + 'px';
},
onComplete: function (node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
console.log(dot._depth);
var connCount = dot.data.size;
var showingCount = '';
if (connCount != undefined) {
var pageParamInt = (parseInt(pageParam)+1) * 10;
var modulus = connCount%10;
showingCount = (pageParamInt - 9) + " - " + pageParamInt;
if (connCount - (pageParamInt - 9) < 10) {
showingCount = (pageParamInt - 10) + " - " + ((pageParamInt - 10) + modulus);
}
} else {
connCount = '0';
showingCount = 'No Connections Shown'
}
}
});
//load JSON data.
ht.loadJSON(json);
//compute positions and plot.
ht.refresh();
//end
ht.controller.onComplete();
});
}
function isEven(n)
{
return isNumber(n) && (n % 2 == 0);
}
function isOdd(n)
{
return isNumber(n) && (n % 2 == 1);
}
function isNumber(n)
{
return n === parseFloat(n);
}
function processAjaxData(response, urlPath){
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
out = out + "\n\n"
console.log(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
What's probably causing this?
Please check whether there is conflict id. Basically infovis render each nodes by the id.
And if there is an DOM element that has the same id with one DOM element of a node. It would conflict and won't render
you can check it by duming dom element iterating over the nodes.
I'm trying to programmatically bind events to fields. The "data-bind > events > change" attribute(s) is/are being added to the DOM element just fine. For instance, this is the HTML generated by my script:
<select id="MainContent_DetailsContent_TypeOfLoss" class="valid" name="TypeOfLoss" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source: TypeOfLoss, events: { change: TypeOfLoss_updateSourceUsingValue }" style="display: none;">
However, when I change the value of the DropDownList (just for example), I get the following error:
TypeError: handler is not a function
path/to/app/Assets/Lib/kendo/src/js/kendo.web.js
Line 6923
I don't know what's going on - the TypeOfLoss_updateSourceUsingValue method/property DOES exist in the corresponding View-Model (KendoDOMBinder._viewModel).
Any ideas? I'm using kendoui.web.2013.1.319.
KendoDOMBinder: function (viewModel) {
var binder = Object.create({
_viewModel: {},
_widgets: {},
_root: {},
init: function (viewModel) {
this._viewModel = viewModel || Object.create(kendo.observable());
this._widgets = App.Config.Widgets.defaults();
return this;
},
bindField: function (node, bindings) {
var that = this,
val = [],
ds,
events = [],
event,
target,
fnCallback,
callback;
// Empty data attributes will crash Kendo
if (App.Utilities.isEmpty(bindings) === false) {
// TODO: Should be using strategy pattern to process data attributes
$.each(bindings, function (type, binding) {
switch (type) {
case 'source':
ds = App.Data.DataSource.Factory(binding)
val.push(type + ': ' + node.name);
that._viewModel.set(node.name, ds);
break;
case 'value':
// Make sure the property doesn't exist before adding it
if (that._viewModel.hasOwnProperty(binding) === false) {
// Add the property
that._viewModel.set(binding, '');
// TODO: accept function
}
break;
case 'events':
break;
case 'field':
event = binding.event || 'change';
type = binding.type;
target = binding.target;
if (binding.type == 'triggerUpdate') {
fnCallback = [node.name, binding.callback].join('_');
//console.log(fnCallback);
// Make sure the property doesn't exist before adding it
if (that._viewModel.hasOwnProperty(fnCallback) === false) {
// Define the callback
switch (binding.callback) {
case 'updateSourceUsingValue':
// Add the property
fnCallback = that._viewModel.set(fnCallback, function () {
alert("Doing something");
});
//console.log(that._viewModel);
events.push(event + ': ' + fnCallback);
break;
case 'updateUsingValue':
break;
}
}
}
break;
default:
val.push(type + ': ' + binding);
break;
}
});
if (events.length > 0) {
val.push('events: { ' + events.join(', ') + ' }');
}
}
console.log(val.join(', '));
node.setAttribute('data-bind', val.join(', '));
return this;
},
unbindField: function (key) {
//this._viewModel.unbind;
return this;
},
bind: function (selector) {
selector = selector || 'body';
kendo.bind($(selector), this._viewModel);
},
createFunction: function (ns, fn) {
var nsArray = ns.split(/\./),
currentNode = this._root,
newNS;
while (nsArray.length > 1) {
newNS = nsArray.shift();
if (typeof currentNode[newNS] === "undefined") {
currentNode[newNS] = {};
}
currentNode = currentNode[newNS];
}
if (fn) {
currentNode[nsArray.shift()] = fn;
} else {
currentNode[nsArray.shift()] = {};
}
}
});
return binder.init(viewModel);
}