jquery auto complete load when type somthing in search box - javascript

I use jquery auto complete on my site I have many keywords in auto complete script so my site load slow please tell me any method to load jquery auto complete when user type something on search box this will help to load page fast.
check my site: www.playorplays.com
$(document).ready(function() {
var availableTags = ["", ""];
var otherTags = [
"Video",
"Song",
"Full",
"Movie",
"HD",
"1080p",
""];
var faux = $("#faux");
var offsets;
var arrayused;
var calcfaux;
var retresult;
var checkspace;
var contents = $('#s')[0];
var carpos;
var fauxpos;
var tier;
var startss;
var endss;
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
function split(val) {
return val.split(/ \s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#s").on("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).click(function(event) {
carpos = getCaret(contents);
fauxpos = faux.text().length;
if (carpos < fauxpos) {
tier = "close";
$(this).autocomplete("close");
startss = this.selectionStart;
endss = this.selectionEnd;
$(this).val($(this).val().replace(/ *$/, ''));
this.setSelectionRange(startss, endss);
} else {
tier = "open";
}
}).on("keyup", function(event) {
calcfaux = faux.text($(this).val());
fauxpos = faux.text().length;
if (/ $/.test(faux.text()) || tier === "close") {
checkspace = "space";
} else {
checkspace = "nospace";
} if (fauxpos <= 1) {
offsets = 0;
tier = "open";
}
carpos = getCaret(contents);
if (carpos < fauxpos) {
tier = "close";
$(this).autocomplete("close");
startss = this.selectionStart;
endss = this.selectionEnd;
$(this).val($(this).val().replace(/ *$/, ''));
this.setSelectionRange(startss, endss);
} else {
tier = "open";
}
}).autocomplete({
minLength: 1,
search: function(event, ui) {
var input = $(event.target);
if (checkspace === "space") {
input.autocomplete("close");
return false;
}
},
source: function(request, response) {
var terme = $.ui.autocomplete.escapeRegex(extractLast(request.term)),
startsWithMatchere = new RegExp("^" + terme, "i"),
startsWithe = $.grep(availableTags, function(value) {
return startsWithMatchere.test(value.label || value.value || value);
}),
containsMatchere = new RegExp(terme, "i"),
containse = $.grep(availableTags, function(value) {
return $.inArray(value, startsWithe) < 0 && containsMatchere.test(value.label || value.value || value);
});
var term = $.ui.autocomplete.escapeRegex(extractLast(request.term)),
startsWithMatcher = new RegExp("^" + term, "i"),
startsWith = $.grep(otherTags, function(value) {
return startsWithMatcher.test(value.label || value.value || value);
}),
containsMatcher = new RegExp(term, "i"),
contains = $.grep(otherTags, function(value) {
return $.inArray(value, startsWith) < 0 && containsMatcher.test(value.label || value.value || value);
});
if (offsets == 0) {
retresult = startsWithe.concat(containse);
arrayused = "availableTags";
response(startsWithe.concat(containse));
}
if (retresult == "" || offsets != 0) {
arrayused = "otherTags";
response(startsWith.concat(contains));
}
},
open: function(event, ui) {
var input = $(event.target),
widget = input.autocomplete("widget"),
style = $.extend(input.css(["font", "border-left", "padding-left"]), {
position: "absolute",
visibility: "hidden",
"padding-right": 0,
"border-right": 0,
"white-space": "pre",
"font-size": "16px",
"font-weight": "bold"
}),
div = $("<div/>"),
pos = {
my: "left top",
collision: "none"
},
offset = 0;
div.text(input.val().replace(/\S*$/, "")).css(style).insertAfter(input);
offset = Math.min(Math.max(offset + div.width(), 0), input.width() - widget.width());
if (arrayused === "otherTags") {
widget.css("width", "");
offset = Math.min(Math.max(offset + div.width(), 0), input.width() - widget.width());
}
div.remove();
pos.at = "left+" + offset + " bottom";
input.autocomplete("option", "position", pos);
widget.position($.extend({
of: input
}, pos));
offsets = offset;
},
focus: function() {
return false;
},
select: function(event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(" ");
calcfaux = faux.text($(this).val());
if (/ $/.test(faux.text())) {
checkspace = "space";
} else {
checkspace = "nospace";
}
carpos = getCaret(contents);
fauxpos = faux.text().length;
return false;
}
});
});

Try to avoid triggering auto completing for the single key entry;Wait at least user enter three key board inputs.
And if your keep your key words in a static array it wont be affect to the speed of the page load.
But the size of your images, .css files, .js files will directly affect to speed of the page load.
try to compress those files and use light weight images.
And try to reduce the round trip time. In order to do that use your basic styling in your html page.
and do research in how to reduce the page load time.
and check your site with google developer page speed insights (https://developers.google.com/speed/pagespeed/insights/)
and read the tips.....

Related

Uncaught TypeError: window.getWidth is not a function . what is this error? how to fix? [duplicate]

This question already has answers here:
Get the size of the screen, current web page and browser window
(20 answers)
Closed 6 days ago.
I see following error for my website (via google Inspect). I need your help to understand the problem and how to fix it?
script.js:137 Uncaught TypeError: window.getWidth is not a function
at Object.check (script.js:137:23)
at Object.initialize (script.js:58:14)
at HTMLDocument.<anonymous> (script.js:442:14)
at n (jquery-1.7.1.min.js:2:14784)
at Object.fireWith (jquery-1.7.1.min.js:2:15553)
at Function.ready (jquery-1.7.1.min.js:2:9773)
at HTMLDocument.B (jquery-1.7.1.min.js:2:14348)
and following is script.js file content:
var TouchMask = {
handlers: [],
isbind: 0,
ontouch: function(){
var result = 1;
TouchMask.handlers.each(function(fn){
result = fn() && result;
});
if(result){
document.removeEvent('touchstart', TouchMask.ontouch);
TouchMask.isbind = 0;
}
},
show: function(){
if(this.isbind){
return false;
}
document.addEvent('touchstart', TouchMask.ontouch);
this.isbind = 1;
},
register: function(handler){
if(typeOf (handler) == 'function' && this.handlers.indexOf(handler) == -1){
this.handlers.push(handler);
}
},
unregister: function(handler){
this.handlers.erase(handler);
}
};
var JawallMenu = {
initialize: function(){
JawallMenu.isAndroidTable = navigator.userAgent.toLowerCase().indexOf('android') > -1 && navigator.userAgent.toLowerCase().indexOf('mobile') == -1;
JawallMenu.isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
JawallMenu.enableTouch();
JawallMenu.check();
window.addEvent('resize', JawallMenu.check);
},
enableTouch: function(){
if (JawallMenu.isTouch){
var jmainnav = $('mainnav');
if(!jmainnav){
return false;
}
var jmenu = jmainnav.getElement('.menu');
if(!jmenu){
return false;
}
var jitems = jmenu.getElements('li.deeper'),
onTouch = function(e){
var i, len, noclick = !this.retrieve('noclick');
e.stopPropagation();
// reset all
for (i = 0, len = jitems.length; i < len; ++i) {
jitems[i].store('noclick', 0);
}
if(noclick){
var jshow = this.addClass('hover').getParents('li.parent').addClass('hover');
jshow = jshow.append([this]);
jitems.each(function (jitem) {
if(!jshow.contains(jitem)){
jitem.removeClass('hover');
}
});
}
this.store('noclick', noclick);
this.focus();
},
onClick = function(e){
e.stopPropagation();
if(this.retrieve('noclick')){
e.preventDefault();
jitems.removeClass('hover');
this.addClass('hover').getParents('li.parent').addClass('hover');
TouchMask.hidetoggle();
TouchMask.show();
} else {
var href = this.getElement('a').get('href');
if(href){
window.location.href = href;
}
}
};
jitems.each(function(jitem){
jitem.addEvent('touchstart', onTouch)
.addEvent('click', onClick)
.store('noclick', 0);
});
JawallMenu.resetmenu = function(){
jitems.store('noclick', 0).removeClass('hover');
return true;
};
TouchMask.register(JawallMenu.resetmenu);
}
},
oldWidth: 0,
check: function(){
var wwidth = window.getWidth();
if(wwidth == JawallMenu.oldWidth){
return;
}
JawallMenu.oldWidth = wwidth;
var jmainnav = $('mainnav');
if(!jmainnav){
return;
}
var jmenuinner = jmainnav.getElement('.menu-inner'),
jmenu = jmainnav.getElement('.menu');
if(!jmenuinner || !jmenu){
return;
}
//check if we have to implement scroll
if (jmenu.offsetWidth > jmenuinner.offsetWidth) {
jmenu.setStyle('float', 'left');
if(!window.menuIScroll){
var jprev = jmainnav.getChildren('.navprev')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navprev'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('prev');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
jnext = jmainnav.getChildren('.navnext')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navnext'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('next');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
checkNav = function (){
if(window.menuIScroll){
jprev.setStyle('display', window.menuIScroll.x >= 0 ? 'none' : 'block');
jnext.setStyle('display', (window.menuIScroll.x <= window.menuIScroll.maxScrollX) ? 'none' : 'block');
}
};
window.menuIScroll = new iScroll(jmenuinner, {
snap: '.menu > li',
hScrollbar: false,
vScrollbar: false,
onRefresh: checkNav,
onScrollEnd: checkNav,
useTransform: false,
onScrollStart: function(){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
},
overflow: ''
});
checkNav();
var jactive = jmenu.getChildren('.active')[0];
if(jactive){
window.menuIScroll.scrollToElement(jactive);
}
}
if (window.menuIScroll) {
window.menuIScroll.refresh();
}
} else {
if (window.menuIScroll) {
window.menuIScroll.scrollTo(0, 0, 0);
}
jmenu.setStyle('float', '');
}
//check if the mobile layout, we change html structure
if(wwidth < 720){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
jmenuinner.setStyle('overflow', 'hidden');
jmenu.getChildren('.deeper > ul').each(function(jsub){
var jitem = jsub.getParent(),
sid = null;
jsub.store('parent', jitem).addClass('jsub').inject(jmainnav).setStyle('position', 'absolute');
if(!JawallMenu.isTouch){
//add mouse event to show/hide sub on desktop
jitem.addEvent('mouseenter', function(e){
clearTimeout(sid);
if(jsub.getStyle('display') != 'none'){
return false;
} else {
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
}
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
jsub.addEvent('mouseenter', function(){
clearTimeout(sid);
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
} else {
//add touch event for touch device
jitem.addEvent('touchstart', function(e){
if(jsub.getStyle('display') == 'none'){
e.stop();
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
TouchMask.hidetoggle();
TouchMask.show();
}
});
}
jitem.addEvent('shide', function(){
clearTimeout(sid);
jsub.setStyle('display', 'none');
jitem.removeClass('over');
JawallMenu.jcitem = null;
}).fireEvent('shide');
});
//only init once
if(!JawallMenu.initTouch && JawallMenu.isTouch){
jmainnav.addEvent('touchstart', function(){
if(JawallMenu.jcitem){
this.store('touchInside', 1);
}
});
TouchMask.hidesub = function(){
if(jmainnav.retrieve('touchInside')){
jmainnav.store('touchInside', 0);
return false;
} else {
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidesub);
TouchMask.hidesub();
JawallMenu.initTouch = 1;
}
} else {
JawallMenu.jcitem = null;
jmainnav.getChildren('.jsub').each(function(jsub){
var jitem = jsub.retrieve('parent');
jitem.removeEvents('mouseenter').removeEvents('mouseleave').removeEvents('touchstart').removeEvents('shide');
jsub.removeProperty('style').removeEvents('mouseenter').removeEvents('mouseleave').removeClass('jsub').inject(jitem);
});
jmenuinner.setStyle('overflow', '');
}
}
};
window.addEventListener('load', function(event) {
if(window.menuIScroll){
window.menuIScroll.refresh();
}
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
});
(function($){
var groups = {
},
handler = function (group, value) {
// ignore user setting for page with fixed option
if ($(document.body).hasClass ('fixed-' + group)){
return;
}
if (value) {
if (groups[group]['type'] == 'toggle') {
var cvalue = $.cookie ('ja-'+group);
if (new RegExp ('(^|\\s)' + value+'(?:\\s|$)').test(cvalue)) {
$(document.body).removeClass (group + '-' + value);
cvalue = cvalue.replace (new RegExp ('(^|\\s)' + value+'(?:\\s|$)', 'g'), '$1');
} else {
$(document.body).addClass (group + '-' + value);
cvalue += ' ' + value;
}
groups[group]['val'] = cvalue;
// update cookie
$.cookie ('ja-'+group, cvalue, {duration: 365, path: '/'});
} else {
// update value & cookie
groups[group]['val'] = value;
$.cookie ('ja-'+group, value, {duration: 365, path: '/'});
// remove current
document.body.className = document.body.className.replace (new RegExp ('(^|\\s)' + group+'-[^\\s]*', 'g'), '$1');
$(document.body).addClass (group + '-' + value);
}
}
// Make the UI reload by trigger resize event for window
$(window).trigger('resize');
};
$.fn.toolbar = function(options){
var defaults = {
group: 'basegrid',
type: 'single',
val: 'm'
},
opt = $.extend(defaults, options);
groups[opt.group] = groups[opt.group] || {};
$.extend(groups[opt.group], {type: opt.type, val: opt.val});
if (!$(document.body).hasClass ('fixed-' + opt.group)){
var value = $.cookie('ja-'+opt.group);
if (value) {
groups[opt.group]['val'] = value; // setting exists, replace the default
// add active class
$(document.body).addClass (groups[opt.group]['val'].replace (/(^|\s)([^\s]+)/g, '$1' + opt.group + '-$2'));
} else if(opt.val) {
handler (opt.group, opt.val);
}
}
// bind event for toolbar
return this.bind('click', function () { handler (opt.group, this.id.replace ('toolbar-' + opt.group + '-', '')); return false; });
};
})(window.$wall || window.jQuery);
(window.$wall || window.jQuery)(document).ready(function ($) {
// enable menu responsive check
if(!($.browser.msie && parseFloat($.browser.version) < 9)){
JawallMenu.initialize();
}
var bindevent = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion) ? 'touchstart' : 'click',
jtoggles = $('.btn-toggle'),
jsidebar = $('#sidebar'),
jtoggleactive = null;
// toggle handle
jtoggles.bind(bindevent, function (event) {
var jactive = $(this),
jparent = jactive.parent();
if (jparent.hasClass('active')) {
jparent.removeClass ('active');
// remove btn-toggle-active
jtoggleactive = null
} else {
// remove other active
jtoggles.parent().removeClass ('active');
// add active for this toggle
jparent.addClass ('active');
// store
jtoggleactive = jactive;
}
if(typeOf (TouchMask.hidesub) == 'function'){
TouchMask.hidesub();
}
TouchMask.show();
return false;
});
jtoggles.parent().bind(bindevent, function(){
if(jtoggleactive){
$('body').data('touchInside', 1);
}
});
TouchMask.hidetoggle = function(){
if (jtoggleactive) {
if($('body').data('touchInside')){
$('body').data('touchInside', 0);
return false;
} else {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidetoggle);
var rfpage = $('#josForm').hasClass('wform') && $('#k2Container').hasClass('k2AccountPage'),
wmobile = false, //normal by default
wmeditor = function(){
if(!wmobile){
var jmce = $('.mceLayout:first');
if(jmce.width() > jmce.closest('.wcontrols').width()){
wmobile = true;
$('table.mceToolbar').each(function(){
$(this).find('> tbody > tr').css('white-space', 'normal').find('td').css({
position: '',
float: 'left',
display: 'inline-block'
});
});
$('.toggle-editor a').trigger('click').delay(300).trigger('click');
}
}
},
sidrfp = setTimeout(wmeditor, 350);
// tracking status of btn-toggle
$(window).resize (function() {
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
if (jtoggleactive) {
if (jtoggleactive.css('display') == 'none') {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
}
}
if (jsidebar.length) {
if(JawallMenu.isTablet){
jsidebar.css({
position: 'fixed',
top: ''
});
}
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
}
if(rfpage){
clearTimeout(sidrfp);
sidrfp = setTimeout(wmeditor, 350);
}
});
// scrollbar for sidebar if exist
if (jsidebar.length) {
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
window.sidebarIScroll = new iScroll(jsidebar.find('.sidebar-inner')[0], {vScrollbar: true, scrollbarClass: 'sidebarTracker', useTransform: false});
if(JawallMenu.isTouch){
var jsbtoggle = jsidebar.find('.btn-toggle:first');
$('<div id="dummy-toggle"></div>').css({
position: 'absolute',
top: 0,
left: 0,
width: jsbtoggle.width(),
height: jsbtoggle.height(),
}).appendTo(document.body).bind(bindevent, function(e){
e.preventDefault();
e.stopPropagation();
jsbtoggle.trigger(bindevent);
});
var lastScroll = 0,
scrollid = null;
$(window).scroll(function(){
lastScroll = $(window).scrollTop();
$('#dummy-toggle').css('top', lastScroll);
if(JawallMenu.isTablet){
clearTimeout(scrollid);
scrollid = setTimeout(function(){
lastScroll = $(window).scrollTop();
scrollid = setTimeout(function(){
if(lastScroll == $(window).scrollTop()){
jsidebar
.css('top', lastScroll + parseFloat(jsidebar.css('top', '').css('top')))
.css('position', 'absolute');
$(document).one('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
}
}, 100);
}, 100);
}
});
}
if(JawallMenu.isTablet && !JawallMenu.isBindTablet){
$(document).on('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
JawallMenu.isBindTablet = 1;
}
}
// check and load typography assert files if nessesary
window.jtypo = jQuery('.item-pagetypography .item-content');
if(!window.jtypo.length){
window.jtypo = jQuery('.typography .itemBody');
}
if(window.jtypo.length){
var css = document.createElement('link');
css.type = 'text/css';
css.rel= 'stylesheet';
css.href= JADef.tplurl + 'css/jtypo.css';
document.getElementsByTagName('head')[0].appendChild(css);
$.getScript(JADef.tplurl + 'js/jtypo.js');
}
});
to understand it better please see the error directly via google inspect at following page:
http://test6.harfrooz.com/117-more/18376-top-20-ufo-sightings
This error made my menus disabled and more issues. I would appreciate for any help to solve this error.
I am fairly certain this has been answered before here.
For normal javascript you can use:
window.innerHeight - the inner height of the browser window (in
pixels)
window.innerWidth - the inner width of the browser window (in
pixels)

How to implement ipad-like password field behaviour in a text input field using jquery

Is there any plugin similar to the iPad-like password field behaviour. We need to show only the focus number that the customer enters when they enter their credit card number, and then switch to a bullet once the customer types the next number.
For numbers that have been entered prior to the number being entered, they all need to be changed to the bullet style.
Not sure about Jquery plugin. tried this out. Hope this works for you - http://jsfiddle.net/Lhw7xcy6/12/
(function () {
var config = {},
bulletsInProgress = false,
bulletTimeout = null,
defaultOpts = {
className: 'input-long',
maxLength: '16',
type: 'tel',
autoComplete: 'off'
};
var generateBullets = function (n) {
var bullets = '';
for (var i = 0; i < n; i++) {
bullets += "\u25CF";
}
return bullets;
},
getCursorPosition = function (elem) {
var el = $(elem).get(0);
var pos = 0;
var posEnd = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
posEnd = Sel.text.length;
}
return [pos, posEnd];
},
keyInputHandler = function (e, elem, $inpField) {
var keyCode = e.which || e.keyCode,
timeOut = 0,
$bulletField = $(elem),
tempInp = $bulletField.data('tempInp'),
numBullets = $bulletField.data('numBullets');
var position = getCursorPosition(elem);
if (keyCode >= 48 && keyCode <= 57) {
e.preventDefault();
clearTimeout(bulletTimeout);
$bulletField.val(generateBullets(numBullets) + String.fromCharCode(keyCode));
tempInp += String.fromCharCode(keyCode);
numBullets += 1;
bulletsInProgress = true;
timeOut = 3000;
} else if (keyCode == 8) {
clearTimeout(bulletTimeout);
tempInp = (position[0] == position[1]) ? tempInp.substring(0, position[0] - 1) + tempInp.substring(position[1]) : tempInp.substring(0, position[0]) + tempInp.substring(position[1]);
numBullets = (position[0] == position[1]) ? numBullets - 1 : numBullets - (position[1] - position[0]);
tempInp = ($.trim($bulletField.val()) === '') ? '' : tempInp;
numBullets = ($.trim($bulletField.val()) === '') ? 0 : numBullets;
timeOut = 0;
} else {
e.preventDefault();
return false;
}
$bulletField.data('numBullets', numBullets);
$bulletField.data('tempInp', tempInp);
$inpField.val(tempInp);
$('#output').val(tempInp); // testing purpose
bulletTimeout = setTimeout(function () {
$bulletField.val(generateBullets(numBullets));
bulletsInProgress = false;
}, timeOut);
};
$.fn.bulletField = function (options) {
var opts = $.extend({}, defaultOpts, options);
//console.log(opts);
this.each(function () {
var $inpField = $(this),
id = $inpField.attr('id');
$inpField.after('<input id="bullet_' + id + '" type=' + opts.type + ' maxlength=' + opts.maxLength + ' autocomplete=' + opts.autoComplete + ' class=' + opts.className + '>');
$inpField.hide();
var bulletFieldId = 'bullet_' + id;
var $bulletField = $('#' + bulletFieldId);
$bulletField.data('numBullets', 0);
$bulletField.data('tempInp', '');
$('#' + bulletFieldId).on('keydown', function (e) {
keyInputHandler(e, this, $inpField);
});
$('#' + bulletFieldId).on('blur', function () {
//$inpField.trigger('blur');
});
});
return this;
};
}());
$(function () {
/*USAGE - invoke the plugin appropriately whenever needed. example -onclick,onfocus,mousedown etc.*/
//$('body').on('mousedown', '#bulletField', function () {
$('#bulletField').bulletField();
//$('body').off('mousedown');
// });
/* ---OR ----
$('#bulletField').bulletField({
className: 'input-short',
maxLength : '4'
});*/
});

Infovis not Iterating over Root Node

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.

Up/Down/Left/Right keyboard navigation with jQuery?

I have a list of div's all with a set and equal height/width that are float:left so they sit next to each other and fold under if that parent is smaller than the combined with of the items.
Pretty standard.
This is to create a list of the twitter bootstrap icons, it gives something like this:
I have added next/previous keyboard navigation using the code below, however you will notice that the up/down arrow keys are mapped to call the left/right functions. What I have no idea how to do is to actually do the up/down navigation?
JsFiddle
(function ($) {
$.widget("ui.iconSelect", {
// default options
options: {
},
$select: null,
$wrapper: null,
$list: null,
$filter: null,
$active: null,
icons: {},
keys: {
left: 37,
up: 38,
right: 39,
down: 40
},
//initialization function
_create: function () {
var that = this;
that.$select = that.element;
that.$wrapper = $('<div class="select-icon" tabindex="0"></div>');
that.$filter = $('<input class="span12" tabindex="-1" placeholder="Filter by class name..."/>').appendTo(that.$wrapper);
that.$list = $('<div class="select-icon-list"></div>').appendTo(that.$wrapper);
//build the list of icons
that.element.find('option').each(function () {
var $option = $(this);
var icon = $option.val();
that.icons[icon] = $('<a data-class="' + icon + '"><i class="icon ' + icon + '"></i></a>');
if ($option.is(':selected')) {
that.icons[icon].addClass('selected active');
}
that.$list.append(that.icons[icon]);
});
that.$wrapper.insertBefore(that.$select);
that.$select.addClass('hide');
that._setupArrowKeysHandler();
that._setupClickHandler();
that._setupFilter();
that.focus('selected');
},
focus: function (type) {
var that = this;
if (that.$active === null || that.$active.length == 0) {
if (type == 'first') {
that.$active = that.$list.find('a:visible:first');
} else if (type == 'last') {
that.$active = that.$list.find('a:visible:last');
} else if (type == 'selected') {
that.$active = that.$list.find('a.selected:visible:first');
that.focus('first');
}
}
that.$active.addClass('active');
var toScroll = ((that.$list.scrollTop() + that.$active.position().top)-that.$list.height()/2)+that.$active.height()/2;
//that.$list.scrollTop((that.$list.scrollTop() + top)-that.$list.height()/2);
that.$list.stop(true).animate({
scrollTop: toScroll,
queue: false,
easing: 'linear'
}, 200);
if (type === 'selected') {
return false;
}
that.$select.val(that.$active.data('class'));
that.$select.trigger('change');
},
_setupArrowKeysHandler: function () {
var that = this;
that.$wrapper.on('keydown', function (e) {
switch (e.which) {
case that.keys.left:
that.moveLeft();
break;
case that.keys.up:
that.moveUp();
break;
case that.keys.right:
that.moveRight();
break;
case that.keys.down:
that.moveDown();
break;
case 16:
return true;
case 9:
return true;
break;
default:
that.$filter.focus();
return true;
}
return false;
});
},
_setupFilter: function(){
var that = this;
that.$filter.on('keydown keyup keypress paste cut change', function(e){
that.filter(that.$filter.val());
});
},
_setupClickHandler: function () {
var that = this;
that.$list.on('click', 'a', function () {
that.$wrapper.focus();
that.$active.removeClass('active');
that.$active = $(this);
that.focus('first');
});
},
moveUp: function () {
var that = this;
return that.moveLeft();
},
moveDown: function () {
var that = this;
return that.moveRight();
},
moveLeft: function () {
var that = this;
that.$active.removeClass('active');
that.$active = that.$active.prevAll(':visible:first');
that.focus('last');
return false;
},
moveRight: function () {
var that = this;
that.$active.removeClass('active');
that.$active = that.$active.nextAll(':visible:first');
that.focus('first');
return false;
},
filter: function(word){
var that = this;
var regexp = new RegExp(word.toLowerCase());
var found = false;
$.each(that.icons, function(i, $v){
found = regexp.test(i);
if(found && !$v.is(':visible')){
$v.show();
} else if(!found && $v.is(':visible')){
$v.hide();
}
});
}
});
})(jQuery);
Perhaps something like this: http://jsfiddle.net/QFzCY/
var blocksPerRow = 4;
$("body").on("keydown", function(e){
var thisIndex = $(".selected").index();
var newIndex = null;
if(e.keyCode === 38) {
// up
newIndex = thisIndex - blocksPerRow;
}
else if(e.keyCode === 40) {
// down
newIndex = thisIndex + blocksPerRow;
}
if(newIndex !== null) {
$(".test").eq(newIndex).addClass("selected").siblings().removeClass("selected");
}
});
Basically, you set how many items there are in a row and then find the current index and subtract or add that amount to select the next element via the new index.
If you need to know how many blocks per row there are, you could do this:
var offset = null;
var blocksPerRow = 0;
$(".test").each(function(){
if(offset === null) {
offset = $(this).offset().top;
}
else if($(this).offset().top !== offset) {
return false;
}
blocksPerRow++;
});
To deal with your 'edge' cases, you could do:
if(newIndex >= $(".test").length) {
newIndex = $(".test").length - newIndex;
}
moveUp: function () {
var that = this;
var index = $(this).index();
var containerWidth = parseInt( $('.select-icon-list').innerWidth(), 10);
var iconWidth = parseInt( $('.select-icon-list > a').width(), 10);
var noOfCols = Math.floor( containerWidth / iconWidth );
var newIndex = ( (index - noOfCols) < 0 ) ? index : (index - noOfCols);
var elem = $('.select-icon-list > a')[index];
},
Cache what ever remains static.

jQuery preload only works with ie on refresh

I`m having a problem with ie9 not always loading preloaded images.
Sometimes I haft to refresh the page and then it works.
$jQuery.fn.img_preloader = function(options){
var defaults = {
repeatedCheck: 550,
fadeInSpeed: 1100,
delay: 200,
callback: ''
};
var options = jQuery.extend(defaults, options);
return this.each(function(){
var imageContainer = jQuery(this),
images = imageContainer.find('img').css({opacity:0, visibility:'hidden'}),
imagesToLoad = images.length;
imageContainer.operations = {
preload: function(){
var stopPreloading = true;
images.each(function(i, event){
var image = jQuery(this);
if(event.complete == true){
imageContainer.operations.showImage(image);
}else{
image.bind('error load',{currentImage: image}, imageContainer.operations.showImage);
}
});
return this;
},showImage: function(image){
imagesToLoad --;
if(image.data.currentImage != undefined) { image = image.data.currentImage;}
if (options.delay <= 0) image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
if(imagesToLoad == 0){
if(options.delay > 0){
images.each(function(i, event){
var image = jQuery(this);
setTimeout(function(){
image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
},
options.delay*(i+1));
});
if(options.callback != ''){
setTimeout(options.callback, options.delay*images.length);
}
}else if(options.callback != ''){
(options.callback)();
}
}
}
};
imageContainer.operations.preload();
});
}
Try commenting the event.complete validation and going directly to the showImage event. It's not the best solution, but worked for me.
$jQuery.fn.img_preloader = function(options)
{
var defaults = {
repeatedCheck: 550,
fadeInSpeed: 1100,
delay: 200,
callback: ''
};
var options = jQuery.extend(defaults, options);
return this.each(function()
{
var imageContainer = jQuery(this),
images = imageContainer.find('img').css({opacity:0, visibility:'hidden'}),
imagesToLoad = images.length;
imageContainer.operations = {
preload: function(){
var stopPreloading = true;
images.each(function(i, event){
var image = jQuery(this);
imageContainer.operations.showImage(image);
/*if(event.complete == true){
imageContainer.operations.showImage(image);
}else{
image.bind('error load',{currentImage: image}, imageContainer.operations.showImage);
}*/
});
return this;
},showImage: function(image){
imagesToLoad --;
if(image.data.currentImage != undefined) { image = image.data.currentImage;}
if (options.delay <= 0) image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
if(imagesToLoad == 0){
if(options.delay > 0){
images.each(function(i, event){
var image = jQuery(this);
setTimeout(function(){
image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
},
options.delay*(i+1));
});
if(options.callback != ''){
setTimeout(options.callback, options.delay*images.length);
}
}else if(options.callback != ''){
(options.callback)();
}
}
}
};
imageContainer.operations.preload();
});
}
Replace this showimage function..
showImage: function (g) {
d--;
if (g.data.currentImage != undefined) {
g = g.data.currentImage;
}
if (b.delay <= 0) {
g.css("visibility", "visible").animate({
opacity: 1
}, b.fadeInSpeed);
}
if (d != 0) {
if (b.delay != 0) {
e.each(function (k, j) {
var h = a(this);
setTimeout(function () {
h.css("visibility", "visible").animate({
opacity: 1
}, b.fadeInSpeed)
}, b.delay * (k + 1))
});
if (b.callback != "") {
setTimeout(b.callback, b.delay * e.length)
}
} else {
if (b.callback != "") {
b.callback()
}
}
}
}

Categories