EDIT: code link with better formatting:
EDIT: code updated with improvements from JSHint
http://pastebin.com/hkDQfZy1
I am trying to use $.fn to create a new function on jQuery objects by using it like:
$.fn.animateAuto = function(x,y) { }
And calling it by:
var card = $(id);
.....
var expanderButton = card.find(".dock-bottom");
.....
expanderButton.animateAuto('height', 500);
and I get:
Uncaught TypeError: expanderButton.animateAuto is not a function
What am I doing incorrectly? The $.cssHooks extension works just fine along with $.fx.
Here is the code:
var CSS_VIS = 'visibility'
var CSS_VIS_VIS = 'visible';
var CSS_VIS_HID = 'hidden';
var CSS_TEXTBOX_CONTAINER = ".text-box-container";
$.cssHooks['rotate'] = {
get: function (elem, computed, extra) {
var property = getTransformProperty(elem);
if (property) {
return elem.style[property].replace(/.*rotate\((.*)deg\).*/, '$1');
} else {
return '';
}
},
set: function (elem, value) {
var property = getTransformProperty(elem);
if (property) {
value = parseInt(value);
$(elem).data('rotatation', value);
if (value == 0) {
elem.style[property] = '';
} else {
elem.style[property] = 'rotate(' + value % 360 + 'deg)';
}
} else {
return '';
}
}
};
$.fn.animateAuto = function (prop, speed) {
return this.each(function (i, el) {
el = jQuery(el);
var element = el.clone().css({ 'height': 'auto' }).appendTo("body");
var height = element.css("height");
var width = element.css("width");
element.remove();
if (prop === "height") {
el.animate({ 'height': height }, speed);
} else if (prop = "width") {
el.animate({ 'width': width }, speed);
} else if (prop = "both") {
el.animate({ 'height': height, 'width:': width }, speed);
}
});
}
$.fx.step['rotate'] = function (fx) {
$.cssHooks['rotate'].set(fx.elem, fx.now);
};
function getTransformProperty(element) {
var properties = [
'transform',
'WebkitTransform',
'MozTransform',
'msTransform',
'OTransform'];
var p;
while (p = properties.shift()) {
if (element.style[p] !== undefined) {
return p;
}
}
return false;
}
function isExpanded(card) {
return card.find(CSS_TEXTBOX_CONTAINER).css(CSS_VIS) == CSS_VIS_VIS;
}
function expandCard(id) {
var card = $(id);
var isCardExpanded = isExpanded(card);
var expanderButton = card.find(".dock-bottom");
card.animate({
height: isCardExpanded ? '80px' : '270px'
}, 500);
var startValue = isCardExpanded ? 1 : 0;
var endValue = isCardExpanded ? 0 : 1;
var visibilityValue = isCardExpanded ? CSS_VIS_HID : CSS_VIS_VIS;
var textBoxes = card.find(CSS_TEXTBOX_CONTAINER);
textBoxes.fadeTo(0, startValue);
textBoxes.css(CSS_VIS, visibilityValue).fadeTo(500, endValue);
var topValue = isCardExpanded ? 'auto' : '200px';
if (isCardExpanded) {
expanderButton.animateAuto('height', 500);
} else {
expanderButton.animate({
top: '200px'
}, 500);
}
expanderButton.find("span").text(isCardExpanded ? "More Info" : "Less Info");
var buttonthing = expanderButton.find("button");
expanderButton.find("button").animate({ rotate: isCardExpanded ? 0 : -180 });
};
The issue is that jQuery was loaded multiple times. I am using ASP.NET MVC5 and was loading jQuery in the PartialView (re-usable UI control) and the main page which was causing my extension to be overriden.
I would post code but it would be too verbose and has nothing to do with jQuery or JavaScript. To solve though, all I did was remove the jQuery script import from the PartialView since jQuery is imported on every page by the master page.
Thanks everyone for helping out though, you all proved to me that this was not a simple problem that I was overthinking and that more research was necessary.
Related
I have a Multi-Level Accordion Menu - from a FAQ - with 2 levels.
Each level have a 13 Questions / Answers.
My problem:
One of the Questions/Answers have a lot of information. (almost 10 pages).
The other Questions/Answers have 3, 4 lines of information each.
The Question with many information is number 7.
Then When I click on question 7 - the answer 7 is open. with many information, and the user must scroll down the page to read all.
Until here, OK. no problem.
but at end - If I click on Question 8 - to read the answer, the menu closes question 7 (ok) - open question 8 (ok) - but the page still in the footer - the page dont scrolls up with the faq..
With all other questions - because they are small - I can see in same screen almost all 13 questions + the answer opened.
With question 7 - no. the page scrolls down and don't scrolls up - when we close the question 7.
There is a way to solve this? I think I need to create an anchor for each question..
Tks a lot!
https://jsfiddle.net/27sdLvmh/
Please, click on Question 7, scrool down to read the answer and then click on question 8. the menu scrolls up - but the screen no.. and the user was lost in the footer of the page.. :D
JS:
;(function ( $, window, document, undefined ) {
var pluginName = 'accordion',
defaults = {
transitionSpeed: 300,
transitionEasing: 'ease',
controlElement: '[data-control]',
contentElement: '[data-content]',
groupElement: '[data-accordion-group]',
singleOpen: true
};
function Accordion(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Accordion.prototype.init = function () {
var self = this,
opts = self.options;
var $accordion = $(self.element),
$controls = $accordion.find('> ' + opts.controlElement),
$content = $accordion.find('> ' + opts.contentElement);
var accordionParentsQty = $accordion.parents('[data-accordion]').length,
accordionHasParent = accordionParentsQty > 0;
var closedCSS = { 'max-height': 0, 'overflow': 'hidden' };
var CSStransitions = supportsTransitions();
function debounce(func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this,
args = arguments;
function delayed() {
if (!execAsap) func.apply(obj, args);
timeout = null;
};
if (timeout) clearTimeout(timeout);
else if (execAsap) func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
function supportsTransitions() {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition';
if (typeof s[p] == 'string') {
return true;
}
var v = ['Moz', 'webkit', 'Webkit', 'Khtml', 'O', 'ms'];
p = 'Transition';
for (var i=0; i<v.length; i++) {
if (typeof s[v[i] + p] == 'string') {
return true;
}
}
return false;
}
function requestAnimFrame(cb) {
if(window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame) {
return requestAnimationFrame(cb) ||
webkitRequestAnimationFrame(cb) ||
mozRequestAnimationFrame(cb);
} else {
return setTimeout(cb, 1000 / 60);
}
}
function toggleTransition($el, remove) {
if(!remove) {
$content.css({
'-webkit-transition': 'max-height ' + opts.transitionSpeed + 'ms ' + opts.transitionEasing,
'transition': 'max-height ' + opts.transitionSpeed + 'ms ' + opts.transitionEasing
});
} else {
$content.css({
'-webkit-transition': '',
'transition': ''
});
}
}
function calculateHeight($el) {
var height = 0;
$el.children().each(function() {
height = height + $(this).outerHeight(true);
});
$el.data('oHeight', height);
}
function updateParentHeight($parentAccordion, $currentAccordion, qty, operation) {
var $content = $parentAccordion.filter('.open').find('> [data-content]'),
$childs = $content.find('[data-accordion].open > [data-content]'),
$matched;
if(!opts.singleOpen) {
$childs = $childs.not($currentAccordion.siblings('[data-accordion].open').find('> [data-content]'));
}
$matched = $content.add($childs);
if($parentAccordion.hasClass('open')) {
$matched.each(function() {
var currentHeight = $(this).data('oHeight');
switch (operation) {
case '+':
$(this).data('oHeight', currentHeight + qty);
break;
case '-':
$(this).data('oHeight', currentHeight - qty);
break;
default:
throw 'updateParentHeight method needs an operation';
}
$(this).css('max-height', $(this).data('oHeight'));
});
}
}
function refreshHeight($accordion) {
if($accordion.hasClass('open')) {
var $content = $accordion.find('> [data-content]'),
$childs = $content.find('[data-accordion].open > [data-content]'),
$matched = $content.add($childs);
calculateHeight($matched);
$matched.css('max-height', $matched.data('oHeight'));
}
}
function closeAccordion($accordion, $content) {
$accordion.trigger('accordion.close');
if(CSStransitions) {
if(accordionHasParent) {
var $parentAccordions = $accordion.parents('[data-accordion]');
updateParentHeight($parentAccordions, $accordion, $content.data('oHeight'), '-');
}
$content.css(closedCSS);
$accordion.removeClass('open');
} else {
$content.css('max-height', $content.data('oHeight'));
$content.animate(closedCSS, opts.transitionSpeed);
$accordion.removeClass('open');
}
}
function openAccordion($accordion, $content) {
$accordion.trigger('accordion.open');
if(CSStransitions) {
toggleTransition($content);
if(accordionHasParent) {
var $parentAccordions = $accordion.parents('[data-accordion]');
updateParentHeight($parentAccordions, $accordion, $content.data('oHeight'), '+');
}
requestAnimFrame(function() {
$content.css('max-height', $content.data('oHeight'));
});
$accordion.addClass('open');
} else {
$content.animate({
'max-height': $content.data('oHeight')
}, opts.transitionSpeed, function() {
$content.css({'max-height': 'none'});
});
$accordion.addClass('open');
}
}
function closeSiblingAccordions($accordion) {
var $accordionGroup = $accordion.closest(opts.groupElement);
var $siblings = $accordion.siblings('[data-accordion]').filter('.open'),
$siblingsChildren = $siblings.find('[data-accordion]').filter('.open');
var $otherAccordions = $siblings.add($siblingsChildren);
$otherAccordions.each(function() {
var $accordion = $(this),
$content = $accordion.find(opts.contentElement);
closeAccordion($accordion, $content);
});
$otherAccordions.removeClass('open');
}
function toggleAccordion() {
var isAccordionGroup = (opts.singleOpen) ? $accordion.parents(opts.groupElement).length > 0 : false;
calculateHeight($content);
if(isAccordionGroup) {
closeSiblingAccordions($accordion);
}
if($accordion.hasClass('open')) {
closeAccordion($accordion, $content);
} else {
openAccordion($accordion, $content);
}
}
function addEventListeners() {
$controls.on('click', toggleAccordion);
$controls.on('accordion.toggle', function() {
if(opts.singleOpen && $controls.length > 1) {
return false;
}
toggleAccordion();
});
$(window).on('resize', debounce(function() {
refreshHeight($accordion);
}));
}
function setup() {
$content.each(function() {
var $curr = $(this);
if($curr.css('max-height') != 0) {
if(!$curr.closest('[data-accordion]').hasClass('open')) {
$curr.css({ 'max-height': 0, 'overflow': 'hidden' });
} else {
toggleTransition($curr);
calculateHeight($curr);
$curr.css('max-height', $curr.data('oHeight'));
}
}
});
if(!$accordion.attr('data-accordion')) {
$accordion.attr('data-accordion', '');
$accordion.find(opts.controlElement).attr('data-control', '');
$accordion.find(opts.contentElement).attr('data-content', '');
}
}
setup();
addEventListeners();
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Accordion( this, options ));
}
});
}
})( jQuery, window, document );
Hey check this demo
changes line 191 -> 194
setTimeout(function()
{
$('html, body').animate({ scrollTop: $content.prev().offset().top }, "fast");
},(1000/60)+200);
I'm currently working on a project, where I'm using the following slider in the overal site:
S3Slider
For the particular page I'm currently working on I'm also making use of Walter Zorns' Drag&Drop image library. (Link Here)
Now when I start to make use of the SET_DHTML function, which is required for using the D&D library, my slider starts throwing errors:
Uncaught TypeError: Cannot read property 'contains' of null
The line number given, sends me to the following line:
if($(itemsSpan[currNo]).css('bottom') == 0) {
Which lies in the following piece of code:
s3Slider = function(id, vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 2000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderTopstory");
var itemsSpan = $("#sliderContent .sliderTopstory span");
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true) {
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
/* This line -> */if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function( ) {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};
Why is this error being thrown?
Thanks.
I think your problem lies in these two lines:
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
If jQuery doesn't find the item in the array, it's going to send you a value of -1 (on the top line) which will then be changed to 0 because you added 1. Now, if currNo is 0 on the second line, it's going to change it back to -1, which will return you undefined. Maybe try and change it to do this instead:
var currNo = jQuery.inArray(current, items);
if (currNo === items.length - 1) {
currNo = 0;
}
I'm not positive this is the problem, but I can see this becoming an issue if it's not the problem you're currently having.
It works in chrome.But when i use with Mozilla Firefox then it shows this
" A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.
Script: http://localhost/tsdev_v2/resources/js/libs/jquery-1.8.3.js:6841"
My code is...
<script>
/*$("table").stickyTableHeaders();*/
/* $(function(){
$("table").stickyTableHeaders();
});*/
$(document).ready(function() {
$("table").stickyTableHeaders({fixedOffset:40});
});
</script>
<script>
;(function ($, window, undefined) {
'use strict';
var name = 'stickyTableHeaders',
id = 0,
defaults = {
fixedOffset: 0,
leftOffset: 0,
marginTop: 0,
objDocument: document,
objHead: 'head',
objWindow: window,
scrollableArea: window
};
function Plugin (el, options) {
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
base.id = id++;
// Listen for destroyed, call teardown
base.$el.bind('destroyed',
$.proxy(base.teardown, base));
// Cache DOM refs for performance reasons
base.$clonedHeader = null;
base.$originalHeader = null;
// Keep track of state
base.isSticky = false;
base.hasBeenSticky = false;
base.leftOffset = null;
base.topOffset = null;
base.init = function () {
base.setOptions(options);
base.$el.each(function () {
var $this = $(this);
// remove padding on <table> to fix issue #7
$this.css('padding', 0);
base.$originalHeader = $('thead:first', this);
base.$clonedHeader = base.$originalHeader.clone();
$this.trigger('clonedHeader.' + name, [base.$clonedHeader]);
base.$clonedHeader.addClass('tableFloatingHeader');
base.$clonedHeader.css('display', 'none');
base.$originalHeader.addClass('tableFloatingHeaderOriginal');
base.$originalHeader.after(base.$clonedHeader);
base.$printStyle = $('<style type="text/css" media="print">' +
'.tableFloatingHeader{display:none !important;}' +
'.tableFloatingHeaderOriginal{position:static !important;}' +
'</style>');
base.$head.append(base.$printStyle);
});
base.updateWidth();
base.toggleHeaders();
base.bind();
};
base.destroy = function (){
base.$el.unbind('destroyed', base.teardown);
base.teardown();
};
base.teardown = function(){
if (base.isSticky) {
base.$originalHeader.css('position', 'static');
}
$.removeData(base.el, 'plugin_' + name);
base.unbind();
base.$clonedHeader.remove();
base.$originalHeader.removeClass('tableFloatingHeaderOriginal');
base.$originalHeader.css('visibility', 'visible');
base.$printStyle.remove();
base.el = null;
base.$el = null;
};
base.bind = function(){
base.$scrollableArea.on('scroll.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.on('scroll.' + name + base.id, base.setPositionValues);
base.$window.on('resize.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.on('resize.' + name, base.toggleHeaders);
base.$scrollableArea.on('resize.' + name, base.updateWidth);
};
base.unbind = function(){
// unbind window events by specifying handle so we don't remove too much
base.$scrollableArea.off('.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.off('.' + name + base.id, base.setPositionValues);
base.$window.off('.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.off('.' + name, base.updateWidth);
};
base.toggleHeaders = function () {
if (base.$el) {
base.$el.each(function () {
var $this = $(this),
newLeft,
newTopOffset = base.isWindowScrolling ? (
isNaN(base.options.fixedOffset) ?
base.options.fixedOffset.outerHeight() :
base.options.fixedOffset
) :
base.$scrollableArea.offset().top + (!isNaN(base.options.fixedOffset) ? base.options.fixedOffset : 0),
offset = $this.offset(),
scrollTop = base.$scrollableArea.scrollTop() + newTopOffset,
scrollLeft = base.$scrollableArea.scrollLeft(),
scrolledPastTop = base.isWindowScrolling ?
scrollTop > offset.top :
newTopOffset > offset.top,
notScrolledPastBottom = (base.isWindowScrolling ? scrollTop : 0) <
(offset.top + $this.height() - base.$clonedHeader.height() - (base.isWindowScrolling ? 0 : newTopOffset));
if (scrolledPastTop && notScrolledPastBottom) {
newLeft = offset.left - scrollLeft + base.options.leftOffset;
base.$originalHeader.css({
'position': 'fixed',
'margin-top': base.options.marginTop,
'left': newLeft,
'z-index': 3 // #18: opacity bug
});
base.leftOffset = newLeft;
base.topOffset = newTopOffset;
base.$clonedHeader.css('display', '');
if (!base.isSticky) {
base.isSticky = true;
// make sure the width is correct: the user might have resized the browser while in static mode
base.updateWidth();
$this.trigger('enabledStickiness.' + name);
}
base.setPositionValues();
} else if (base.isSticky) {
base.$originalHeader.css('position', 'static');
base.$clonedHeader.css('display', 'none');
base.isSticky = false;
base.resetWidth($('td,th', base.$clonedHeader), $('td,th', base.$originalHeader));
$this.trigger('disabledStickiness.' + name);
}
});
}
};
base.setPositionValues = function () {
var winScrollTop = base.$window.scrollTop(),
winScrollLeft = base.$window.scrollLeft();
if (!base.isSticky ||
winScrollTop < 0 || winScrollTop + base.$window.height() > base.$document.height() ||
winScrollLeft < 0 || winScrollLeft + base.$window.width() > base.$document.width()) {
return;
}
base.$originalHeader.css({
'top': base.topOffset - (base.isWindowScrolling ? 0 : winScrollTop),
'left': base.leftOffset - (base.isWindowScrolling ? 0 : winScrollLeft)
});
};
base.updateWidth = function () {
if (!base.isSticky) {
return;
}
// Copy cell widths from clone
if (!base.$originalHeaderCells) {
base.$originalHeaderCells = $('th,td', base.$originalHeader);
}
if (!base.$clonedHeaderCells) {
base.$clonedHeaderCells = $('th,td', base.$clonedHeader);
}
var cellWidths = base.getWidth(base.$clonedHeaderCells);
base.setWidth(cellWidths, base.$clonedHeaderCells, base.$originalHeaderCells);
// Copy row width from whole table
base.$originalHeader.css('width', base.$clonedHeader.width());
};
base.getWidth = function ($clonedHeaders) {
var widths = [];
$clonedHeaders.each(function (index) {
var width, $this = $(this);
if ($this.css('box-sizing') === 'border-box') {
var boundingClientRect = $this[0].getBoundingClientRect();
if(boundingClientRect.width) {
width = boundingClientRect.width; // #39: border-box bug
} else {
width = boundingClientRect.right - boundingClientRect.left; // ie8 bug: getBoundingClientRect() does not have a width property
}
} else {
var $origTh = $('th', base.$originalHeader);
if ($origTh.css('border-collapse') === 'collapse') {
if (window.getComputedStyle) {
width = parseFloat(window.getComputedStyle(this, null).width);
} else {
// ie8 only
var leftPadding = parseFloat($this.css('padding-left'));
var rightPadding = parseFloat($this.css('padding-right'));
// Needs more investigation - this is assuming constant border around this cell and it's neighbours.
var border = parseFloat($this.css('border-width'));
width = $this.outerWidth() - leftPadding - rightPadding - border;
}
} else {
width = $this.width();
}
}
widths[index] = width;
});
return widths;
};
base.setWidth = function (widths, $clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var width = widths[index];
$origHeaders.eq(index).css({
'min-width': width,
'max-width': width
});
});
};
base.resetWidth = function ($clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var $this = $(this);
$origHeaders.eq(index).css({
'min-width': $this.css('min-width'),
'max-width': $this.css('max-width')
});
});
};
base.setOptions = function (options) {
base.options = $.extend({}, defaults, options);
base.$window = $(base.options.objWindow);
base.$head = $(base.options.objHead);
base.$document = $(base.options.objDocument);
base.$scrollableArea = $(base.options.scrollableArea);
base.isWindowScrolling = base.$scrollableArea[0] === base.$window[0];
};
base.updateOptions = function (options) {
base.setOptions(options);
// scrollableArea might have changed
base.unbind();
base.bind();
base.updateWidth();
base.toggleHeaders();
};
// Run initializer
base.init();
}
// A plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[name] = function ( options ) {
return this.each(function () {
var instance = $.data(this, 'plugin_' + name);
if (instance) {
if (typeof options === 'string') {
instance[options].apply(instance);
} else {
instance.updateOptions(options);
}
} else if(options !== 'destroy') {
$.data(this, 'plugin_' + name, new Plugin( this, options ));
}
});
};
})(jQuery, window);
</script>
In my jquery-1.8.3.js:6841
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
How to recover this ? Please help.
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 am using Lazy Load Jquery plugin here on my test page: http://bloghutsbeta.blogspot.com/2012/03/testing-2_04.html
And this is the minified script for lazyload:
Code:
<script src="http://files.cryoffalcon.com/javascript/jquery.lazyload.min.js" type="text/javascript" charset="utf-8"></script>
this one is to trigger lazy load:
Code:
<script type="text/javascript" charset="utf-8">
$(function() {
$("img").lazyload({
effect : "fadeIn"
});
});
</script>
In the above script I have added fadeIn effect to it, I don't know if I have done it right according to script writting I am not good in scripts ^^ So, I would like have an advise if it's well written or there is some comma mistake.
But that is not my important question, all of the above lazy load plugin is used with QuickSand Jquery plugin that I am using for sorting.
QuickSand Jquery Plugin requires callback function if it's tooltip or Lazy Load, So can someone kindly tell me how to make lazy load work together with quicksand jquery.
Here is the quicksand's script:
Code:
<script type="text/javascript">
(function(cash) {
$.fn.sorted = function(customOptions) {
var options = {
reversed: false,
by: function(a) {
return a.text();
}
};
$.extend(options, customOptions);
$data = $(this);
arr = $data.get();
arr.sort(function(a, b) {
var valA = options.by($(a));
var valB = options.by($(b));
if (options.reversed) {
return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
} else {
return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
}
});
return $(arr);
};
})(jQuery);
$(function() {
var read_button = function(class_names) {
var r = {
selected: false,
type: 0
};
for (var i=0; i < class_names.length; i++) {
if (class_names[i].indexOf('selected-') == 0) {
r.selected = true;
}
if (class_names[i].indexOf('segment-') == 0) {
r.segment = class_names[i].split('-')[1];
}
};
return r;
};
var determine_sort = function($buttons) {
var $selected = $buttons.parent().filter('[class*="selected-"]');
return $selected.find('a').attr('data-value');
};
var determine_kind = function($buttons) {
var $selected = $buttons.parent().filter('[class*="selected-"]');
return $selected.find('a').attr('data-value');
};
var $preferences = {
duration: 800,
easing: 'easeInOutQuad',
adjustHeight: 'dynamic'
};
var $list = $('#data');
var $data = $list.clone();
var $controls = $('ul#gamecategories ul');
$controls.each(function(i) {
var $control = $(this);
var $buttons = $control.find('a');
$buttons.bind('click', function(e) {
var $button = $(this);
var $button_container = $button.parent();
var button_properties = read_button($button_container.attr('class').split(' '));
var selected = button_properties.selected;
var button_segment = button_properties.segment;
if (!selected) {
$buttons.parent().removeClass('selected-0').removeClass('selected-1').removeClass('selected-2');
$button_container.addClass('selected-' + button_segment);
var sorting_type = determine_sort($controls.eq(1).find('a'));
var sorting_kind = determine_kind($controls.eq(0).find('a'));
if (sorting_kind == 'all') {
var $filtered_data = $data.find('li');
} else {
var $filtered_data = $data.find('li.' + sorting_kind);
}
if (sorting_type == 'size') {
var $sorted_data = $filtered_data.sorted({
by: function(v) {
return parseFloat($(v).find('span').text());
}
});
} else {
var $sorted_data = $filtered_data.sorted({
by: function(v) {
return $(v).find('strong').text().toLowerCase();
}
});
}
$list.quicksand($sorted_data, $preferences, function () { $(this).tooltip (); } );
}
e.preventDefault();
});
});
var high_performance = true;
var $performance_container = $('#performance-toggle');
var $original_html = $performance_container.html();
$performance_container.find('a').live('click', function(e) {
if (high_performance) {
$preferences.useScaling = false;
$performance_container.html('CSS3 scaling turned off. Try the demo again. <a href="#toggle">Reverse</a>.');
high_performance = false;
} else {
$preferences.useScaling = true;
$performance_container.html($original_html);
high_performance = true;
}
e.preventDefault();
});
});
</script>
you can use this:
$list.quicksand($sorted_data, $preferences, function(){
$(this).tooltip ();
$("img").lazyload({
effect : "fadeIn"
});
});