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

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.

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)

Multi-level Accordion Menu: Its possible to open each level with an anchor?

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);

How to set different home page of website for mobile and pc?

I am creating my website, it is working completely fine on desktop version but when I am trying to open it on android mobile the problems occurring are:
The menu does not appear to the user.(the black section below header section)
In categories section the drop-down list is not opening (I have used JQuery in this section).
here is my (demo) website url: Link.
JQuery
/*
* EASYDROPDOWN - A Drop-down Builder for Styleable Inputs and Menus
* Version: 2.1.4
* License: Creative Commons Attribution 3.0 Unported - CC BY 3.0
* http://creativecommons.org/licenses/by/3.0/
* This software may be used freely on commercial and non-commercial projects with attribution to the author/copyright holder.
* Author: Patrick Kunka
* Copyright 2013 Patrick Kunka, All Rights Reserved
*/
(function($){
function EasyDropDown(){
this.isField = true,
this.down = false,
this.inFocus = false,
this.disabled = false,
this.cutOff = false,
this.hasLabel = false,
this.keyboardMode = false,
this.nativeTouch = true,
this.wrapperClass = 'dropdown',
this.onChange = null;
};
EasyDropDown.prototype = {
constructor: EasyDropDown,
instances: {},
init: function(domNode, settings){
var self = this;
$.extend(self, settings);
self.$select = $(domNode);
self.id = domNode.id;
self.options = [];
self.$options = self.$select.find('option');
self.isTouch = 'ontouchend' in document;
self.$select.removeClass(self.wrapperClass+' dropdown');
if(self.$select.is(':disabled')){
self.disabled = true;
};
if(self.$options.length){
self.$options.each(function(i){
var $option = $(this);
if($option.is(':selected')){
self.selected = {
index: i,
title: $option.text()
}
self.focusIndex = i;
};
if($option.hasClass('label') && i == 0){
self.hasLabel = true;
self.label = $option.text();
$option.attr('value','');
} else {
self.options.push({
domNode: $option[0],
title: $option.text(),
value: $option.val(),
selected: $option.is(':selected')
});
};
});
if(!self.selected){
self.selected = {
index: 0,
title: self.$options.eq(0).text()
}
self.focusIndex = 0;
};
self.render();
};
},
render: function(){
var self = this,
touchClass = self.isTouch && self.nativeTouch ? ' touch' : '',
disabledClass = self.disabled ? ' disabled' : '';
self.$container = self.$select.wrap('<div class="'+self.wrapperClass+touchClass+disabledClass+'"><span class="old"/></div>').parent().parent();
self.$active = $('<span class="selected">'+self.selected.title+'</span>').appendTo(self.$container);
self.$carat = $('<span class="carat"/>').appendTo(self.$container);
self.$scrollWrapper = $('<div><ul/></div>').appendTo(self.$container);
self.$dropDown = self.$scrollWrapper.find('ul');
self.$form = self.$container.closest('form');
$.each(self.options, function(){
var option = this,
active = option.selected ? ' class="active"':'';
self.$dropDown.append('<li'+active+'>'+option.title+'</li>');
});
self.$items = self.$dropDown.find('li');
if(self.cutOff && self.$items.length > self.cutOff)self.$container.addClass('scrollable');
self.getMaxHeight();
if(self.isTouch && self.nativeTouch){
self.bindTouchHandlers();
} else {
self.bindHandlers();
};
},
getMaxHeight: function(){
var self = this;
self.maxHeight = 0;
for(i = 0; i < self.$items.length; i++){
var $item = self.$items.eq(i);
self.maxHeight += $item.outerHeight();
if(self.cutOff == i+1){
break;
};
};
},
bindTouchHandlers: function(){
var self = this;
self.$container.on('click.easyDropDown',function(){
self.$select.focus();
});
self.$select.on({
change: function(){
var $selected = $(this).find('option:selected'),
title = $selected.text(),
value = $selected.val();
self.$active.text(title);
if(typeof self.onChange === 'function'){
self.onChange.call(self.$select[0],{
title: title,
value: value
});
};
},
focus: function(){
self.$container.addClass('focus');
},
blur: function(){
self.$container.removeClass('focus');
}
});
},
bindHandlers: function(){
var self = this;
self.query = '';
self.$container.on({
'click.easyDropDown': function(){
if(!self.down && !self.disabled){
self.open();
} else {
self.close();
};
},
'mousemove.easyDropDown': function(){
if(self.keyboardMode){
self.keyboardMode = false;
};
}
});
$('body').on('click.easyDropDown.'+self.id,function(e){
var $target = $(e.target),
classNames = self.wrapperClass.split(' ').join('.');
if(!$target.closest('.'+classNames).length && self.down){
self.close();
};
});
self.$items.on({
'click.easyDropDown': function(){
var index = $(this).index();
self.select(index);
self.$select.focus();
},
'mouseover.easyDropDown': function(){
if(!self.keyboardMode){
var $t = $(this);
$t.addClass('focus').siblings().removeClass('focus');
self.focusIndex = $t.index();
};
},
'mouseout.easyDropDown': function(){
if(!self.keyboardMode){
$(this).removeClass('focus');
};
}
});
self.$select.on({
'focus.easyDropDown': function(){
self.$container.addClass('focus');
self.inFocus = true;
},
'blur.easyDropDown': function(){
self.$container.removeClass('focus');
self.inFocus = false;
},
'keydown.easyDropDown': function(e){
if(self.inFocus){
self.keyboardMode = true;
var key = e.keyCode;
if(key == 38 || key == 40 || key == 32){
e.preventDefault();
if(key == 38){
self.focusIndex--
self.focusIndex = self.focusIndex < 0 ? self.$items.length - 1 : self.focusIndex;
} else if(key == 40){
self.focusIndex++
self.focusIndex = self.focusIndex > self.$items.length - 1 ? 0 : self.focusIndex;
};
if(!self.down){
self.open();
};
self.$items.removeClass('focus').eq(self.focusIndex).addClass('focus');
if(self.cutOff){
self.scrollToView();
};
self.query = '';
};
if(self.down){
if(key == 9 || key == 27){
self.close();
} else if(key == 13){
e.preventDefault();
self.select(self.focusIndex);
self.close();
return false;
} else if(key == 8){
e.preventDefault();
self.query = self.query.slice(0,-1);
self.search();
clearTimeout(self.resetQuery);
return false;
} else if(key != 38 && key != 40){
var letter = String.fromCharCode(key);
self.query += letter;
self.search();
clearTimeout(self.resetQuery);
};
};
};
},
'keyup.easyDropDown': function(){
self.resetQuery = setTimeout(function(){
self.query = '';
},1200);
}
});
self.$dropDown.on('scroll.easyDropDown',function(e){
if(self.$dropDown[0].scrollTop >= self.$dropDown[0].scrollHeight - self.maxHeight){
self.$container.addClass('bottom');
} else {
self.$container.removeClass('bottom');
};
});
if(self.$form.length){
self.$form.on('reset.easyDropDown', function(){
var active = self.hasLabel ? self.label : self.options[0].title;
self.$active.text(active);
});
};
},
unbindHandlers: function(){
var self = this;
self.$container
.add(self.$select)
.add(self.$items)
.add(self.$form)
.add(self.$dropDown)
.off('.easyDropDown');
$('body').off('.'+self.id);
},
open: function(){
var self = this,
scrollTop = window.scrollY || document.documentElement.scrollTop,
scrollLeft = window.scrollX || document.documentElement.scrollLeft,
scrollOffset = self.notInViewport(scrollTop);
self.closeAll();
self.getMaxHeight();
self.$select.focus();
window.scrollTo(scrollLeft, scrollTop+scrollOffset);
self.$container.addClass('open');
self.$scrollWrapper.css('height',self.maxHeight+'px');
self.down = true;
},
close: function(){
var self = this;
self.$container.removeClass('open');
self.$scrollWrapper.css('height','0px');
self.focusIndex = self.selected.index;
self.query = '';
self.down = false;
},
closeAll: function(){
var self = this,
instances = Object.getPrototypeOf(self).instances;
for(var key in instances){
var instance = instances[key];
instance.close();
};
},
select: function(index){
var self = this;
if(typeof index === 'string'){
index = self.$select.find('option[value='+index+']').index() - 1;
};
var option = self.options[index],
selectIndex = self.hasLabel ? index + 1 : index;
self.$items.removeClass('active').eq(index).addClass('active');
self.$active.text(option.title);
self.$select
.find('option')
.removeAttr('selected')
.eq(selectIndex)
.prop('selected',true)
.parent()
.trigger('change');
self.selected = {
index: index,
title: option.title
};
self.focusIndex = i;
if(typeof self.onChange === 'function'){
self.onChange.call(self.$select[0],{
title: option.title,
value: option.value
});
};
},
search: function(){
var self = this,
lock = function(i){
self.focusIndex = i;
self.$items.removeClass('focus').eq(self.focusIndex).addClass('focus');
self.scrollToView();
},
getTitle = function(i){
return self.options[i].title.toUpperCase();
};
for(i = 0; i < self.options.length; i++){
var title = getTitle(i);
if(title.indexOf(self.query) == 0){
lock(i);
return;
};
};
for(i = 0; i < self.options.length; i++){
var title = getTitle(i);
if(title.indexOf(self.query) > -1){
lock(i);
break;
};
};
},
scrollToView: function(){
var self = this;
if(self.focusIndex >= self.cutOff){
var $focusItem = self.$items.eq(self.focusIndex),
scroll = ($focusItem.outerHeight() * (self.focusIndex + 1)) - self.maxHeight;
self.$dropDown.scrollTop(scroll);
};
},
notInViewport: function(scrollTop){
var self = this,
range = {
min: scrollTop,
max: scrollTop + (window.innerHeight || document.documentElement.clientHeight)
},
menuBottom = self.$dropDown.offset().top + self.maxHeight;
if(menuBottom >= range.min && menuBottom <= range.max){
return 0;
} else {
return (menuBottom - range.max) + 5;
};
},
destroy: function(){
var self = this;
self.unbindHandlers();
self.$select.unwrap().siblings().remove();
self.$select.unwrap();
delete Object.getPrototypeOf(self).instances[self.$select[0].id];
},
disable: function(){
var self = this;
self.disabled = true;
self.$container.addClass('disabled');
self.$select.attr('disabled',true);
if(!self.down)self.close();
},
enable: function(){
var self = this;
self.disabled = false;
self.$container.removeClass('disabled');
self.$select.attr('disabled',false);
}
};
var instantiate = function(domNode, settings){
domNode.id = !domNode.id ? 'EasyDropDown'+rand() : domNode.id;
var instance = new EasyDropDown();
if(!instance.instances[domNode.id]){
instance.instances[domNode.id] = instance;
instance.init(domNode, settings);
};
},
rand = function(){
return ('00000'+(Math.random()*16777216<<0).toString(16)).substr(-6).toUpperCase();
};
$.fn.easyDropDown = function(){
var args = arguments,
dataReturn = [],
eachReturn;
eachReturn = this.each(function(){
if(args && typeof args[0] === 'string'){
var data = EasyDropDown.prototype.instances[this.id][args[0]](args[1], args[2]);
if(data)dataReturn.push(data);
} else {
instantiate(this, args[0]);
};
});
if(dataReturn.length){
return dataReturn.length > 1 ? dataReturn : dataReturn[0];
} else {
return eachReturn;
};
};
$(function(){
if(typeof Object.getPrototypeOf !== 'function'){
if(typeof 'test'.__proto__ === 'object'){
Object.getPrototypeOf = function(object){
return object.__proto__;
};
} else {
Object.getPrototypeOf = function(object){
return object.constructor.prototype;
};
};
};
$('select.dropdown').each(function(){
var json = $(this).attr('data-settings');
settings = json ? $.parseJSON(json) : {};
instantiate(this, settings);
});
});
})(jQuery);
Use #media rule.
#media screen and (max-width: 300px) {
body {
background-color: lightblue;
}
//add your rest of the css code for mobile
}
If your question is to set different home pages for mobile and PC version use this
<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://m.domain.com";
}
//-->
</script>

submit button not working due to js file in php

I created autocomplete listbox from js.I download this js.
but due to this js implementation in my code...
my save and search button not working....
but when I comment this js file...submit button works properly..
but this js is also necessary for me to make listbox as autocomplete textbox...
plz suggest me what to change in this js..to make both button and listbox works.
my save button code
<?php
if($_POST && isset($_POST['submit']))
{}
?>
below is my listbox
<select class="special-flexselect" id="society" name="society" tabindex="5" >
<option value="" ></option>
<?php foreach ($society as $soc){ ?>
<option value="<?php echo $soc["society"]; ?>"><?php echo $soc["society"]; ?></option>
<?php }?>
</select>
below is my js code
/**
* flexselect: a jQuery plugin, version: 0.6.0 (2014-08-05)
* #requires jQuery v1.3 or later
*
* FlexSelect is a jQuery plugin that makes it easy to convert a select box into
* a Quicksilver-style, autocompleting, flex matching selection tool.
*
* For usage and examples, visit:
* http://rmm5t.github.io/jquery-flexselect/
*
* Licensed under the MIT:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright (c) 2009-2012, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
*/
(function($) {
$.flexselect = function(select, options) { this.init(select, options); };
$.extend($.flexselect.prototype, {
settings: {
allowMismatch: false,
allowMismatchBlank: true, // If "true" a user can backspace such that the value is nothing (even if no blank value was provided in the original criteria)
sortBy: 'score', // 'score' || 'name'
preSelection: true,
hideDropdownOnEmptyInput: false,
selectedClass: "flexselect_selected",
dropdownClass: "flexselect_dropdown",
showDisabledOptions: false,
inputIdTransform: function(id) { return id + "_flexselect"; },
inputNameTransform: function(name) { return; },
dropdownIdTransform: function(id) { return id + "_flexselect_dropdown"; }
},
select: null,
input: null,
dropdown: null,
dropdownList: null,
cache: [],
results: [],
lastAbbreviation: null,
abbreviationBeforeFocus: null,
selectedIndex: 0,
picked: false,
allowMouseMove: true,
dropdownMouseover: false, // Workaround for poor IE behaviors
indexOptgroupLabels: false,
init: function(select, options) {
this.settings = $.extend({}, this.settings, options);
this.select = $(select);
this.preloadCache();
this.renderControls();
this.wire();
},
preloadCache: function() {
var name, group, text, disabled;
var indexGroup = this.settings.indexOptgroupLabels;
this.cache = this.select.find("option").map(function() {
name = $(this).text();
group = $(this).parent("optgroup").attr("label");
text = indexGroup ? [name, group].join(" ") : name;
disabled = $(this).parent("optgroup").attr("disabled") || $(this).attr('disabled');
return { text: $.trim(text), name: $.trim(name), value: $(this).val(), disabled: disabled, score: 0.0 };
});
},
renderControls: function() {
var selected = this.settings.preSelection ? this.select.find("option:selected") : null;
this.input = $("<input type='text' autocomplete='off' />").attr({
id: this.settings.inputIdTransform(this.select.attr("id")),
name: this.settings.inputNameTransform(this.select.attr("name")),
accesskey: this.select.attr("accesskey"),
tabindex: this.select.attr("tabindex"),
style: this.select.attr("style"),
placeholder: this.select.attr("data-placeholder")
}).addClass(this.select.attr("class")).val($.trim(selected ? selected.text(): '')).css({
visibility: 'visible'
});
this.dropdown = $("<div></div>").attr({
id: this.settings.dropdownIdTransform(this.select.attr("id"))
}).addClass(this.settings.dropdownClass);
this.dropdownList = $("<ul></ul>");
this.dropdown.append(this.dropdownList);
this.select.after(this.input).hide();
$("body").append(this.dropdown);
},
wire: function() {
var self = this;
this.input.click(function() {
self.lastAbbreviation = null;
self.focus();
});
this.input.mouseup(function(event) {
// This is so Safari selection actually occurs.
event.preventDefault();
});
this.input.focus(function() {
self.abbreviationBeforeFocus = self.input.val();
self.input.select();
if (!self.picked) self.filterResults();
});
this.input.blur(function() {
if (!self.dropdownMouseover) {
self.hide();
if (self.settings.allowMismatchBlank && $.trim($(this).val()) == '')
self.setValue('');
if (!self.settings.allowMismatch && !self.picked)
self.reset();
}
if (self.settings.hideDropdownOnEmptyInput)
self.dropdownList.show();
});
this.dropdownList.mouseover(function(event) {
if (!self.allowMouseMove) {
self.allowMouseMove = true;
return;
}
if (event.target.tagName == "LI") {
var rows = self.dropdown.find("li");
self.markSelected(rows.index($(event.target)));
}
});
this.dropdownList.mouseleave(function() {
self.markSelected(-1);
});
this.dropdownList.mouseup(function(event) {
self.pickSelected();
self.focusAndHide();
});
this.dropdown.mouseover(function(event) {
self.dropdownMouseover = true;
});
this.dropdown.mouseleave(function(event) {
self.dropdownMouseover = false;
});
this.dropdown.mousedown(function(event) {
event.preventDefault();
});
this.input.keyup(function(event) {
switch (event.keyCode) {
case 13: // return
event.preventDefault();
self.pickSelected();
self.focusAndHide();
break;
case 27: // esc
event.preventDefault();
self.reset();
self.focusAndHide();
break;
default:
self.filterResults();
break;
}
if (self.settings.hideDropdownOnEmptyInput){
if(self.input.val() == "")
self.dropdownList.hide();
else
self.dropdownList.show();
}
});
this.input.keydown(function(event) {
switch (event.keyCode) {
case 9: // tab
self.pickSelected();
self.hide();
break;
case 33: // pgup
event.preventDefault();
self.markFirst();
break;
case 34: // pgedown
event.preventDefault();
self.markLast();
break;
case 38: // up
event.preventDefault();
self.moveSelected(-1);
break;
case 40: // down
event.preventDefault();
self.moveSelected(1);
break;
case 13: // return
case 27: // esc
event.preventDefault();
event.stopPropagation();
break;
}
});
var input = this.input;
this.select.change(function () {
input.val($.trim($(this).find('option:selected').text()));
});
},
filterResults: function() {
var showDisabled = this.settings.showDisabledOptions;
var abbreviation = this.input.val();
if (abbreviation == this.lastAbbreviation) return;
var results = [];
$.each(this.cache, function() {
if (this.disabled && !showDisabled) return;
this.score = LiquidMetal.score(this.text, abbreviation);
if (this.score > 0.0) results.push(this);
});
this.results = results;
if (this.settings.sortBy == 'score')
this.sortResultsByScore();
else if (this.settings.sortBy == 'name')
this.sortResultsByName();
this.renderDropdown();
this.markFirst();
this.lastAbbreviation = abbreviation;
this.picked = false;
this.allowMouseMove = false;
},
sortResultsByScore: function() {
this.results.sort(function(a, b) { return b.score - a.score; });
},
sortResultsByName: function() {
this.results.sort(function(a, b) { return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0); });
},
renderDropdown: function() {
var showDisabled = this.settings.showDisabledOptions;
var dropdownBorderWidth = this.dropdown.outerWidth() - this.dropdown.innerWidth();
var inputOffset = this.input.offset();
this.dropdown.css({
width: (this.input.outerWidth() - dropdownBorderWidth) + "px",
top: (inputOffset.top + this.input.outerHeight()) + "px",
left: inputOffset.left + "px",
maxHeight: ''
});
var html = '';
var disabledAttribute = '';
$.each(this.results, function() {
if (this.disabled && !showDisabled) return;
disabledAttribute = this.disabled ? ' class="disabled"' : '';
html += '<li' + disabledAttribute + '>' + this.name + '</li>';
});
this.dropdownList.html(html);
this.adjustMaxHeight();
this.dropdown.show();
},
adjustMaxHeight: function() {
var maxTop = $(window).height() + $(window).scrollTop() - this.dropdown.outerHeight();
var top = parseInt(this.dropdown.css('top'), 10);
this.dropdown.css('max-height', top > maxTop ? (Math.max(0, maxTop - top + this.dropdown.innerHeight()) + 'px') : '');
},
markSelected: function(n) {
if (n < 0 || n >= this.results.length) return;
var rows = this.dropdown.find("li");
rows.removeClass(this.settings.selectedClass);
var row = $(rows[n]);
if (row.hasClass('disabled')) {
this.selectedIndex = null;
return;
}
this.selectedIndex = n;
row.addClass(this.settings.selectedClass);
var top = row.position().top;
var delta = top + row.outerHeight() - this.dropdown.height();
if (delta > 0) {
this.allowMouseMove = false;
this.dropdown.scrollTop(this.dropdown.scrollTop() + delta);
} else if (top < 0) {
this.allowMouseMove = false;
this.dropdown.scrollTop(Math.max(0, this.dropdown.scrollTop() + top));
}
},
pickSelected: function() {
var selected = this.results[this.selectedIndex];
if (selected && !selected.disabled) {
this.input.val(selected.name);
this.setValue(selected.value);
this.picked = true;
} else if (this.settings.allowMismatch) {
this.setValue.val("");
} else {
this.reset();
}
},
setValue: function(val) {
if (this.select.val() === val) return;
this.select.val(val).change();
},
hide: function() {
this.dropdown.hide();
this.lastAbbreviation = null;
},
moveSelected: function(n) { this.markSelected(this.selectedIndex+n); },
markFirst: function() { this.markSelected(0); },
markLast: function() { this.markSelected(this.results.length - 1); },
reset: function() { this.input.val(this.abbreviationBeforeFocus); },
focus: function() { this.input.focus(); },
focusAndHide: function() { this.focus(); this.hide(); }
});
$.fn.flexselect = function(options) {
this.each(function() {
if (this.tagName == "SELECT") new $.flexselect(this, options);
});
return this;
};
})(jQuery);
find this in your js page and Remove this from js file,bcoz this shoud stop user to submit form data
$("form").submit(function() {
alert($(this).serialize());
return false;
});

jquery auto complete load when type somthing in search box

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.....

Categories