I have a JS function - triggered with onclick -, that is dynamically changing 4 pics in the current page. But where i have troubles, is the displayed set of picture is clickable too, and should display the picture in lightbox.
So 2 buttons, corresponding to 2 sets of pictures, a click call a function which changes the innerHTML of the table where the set of pictures is displayed.
Sadly, the lightbox is not processed.
Any idea what's wrong and how i can do this ?
javascript:
my_onclick(){ document.getElementByID("content").innerHTML = '<a rel="lightbox" href="pic/1.jpg"><img src="pic/1.jpg" style="width:100px; height:100px;" /></a>';
html:
<table><tr><td id="content"></td></tr></table>
Lightbox (slimbox.js)
var Lightbox = {
init: function(options){
this.options = $extend({
resizeDuration: 400,
resizeTransition: false, // default transition
initialWidth: 250,
initialHeight: 250,
animateCaption: true,
showCounter: true
}, options || {});
this.anchors = [];
$each(document.links, function(el){
if (el.rel && el.rel.test(/^lightbox/i)){
el.onclick = this.click.pass(el, this);
this.anchors.push(el);
}
}, this);
this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
this.eventPosition = this.position.bind(this);
this.overlay = new Element('div', {'id': 'lbOverlay'}).injectInside(document.body);
this.center = new Element('div', {'id': 'lbCenter', 'styles': {'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2), 'display': 'none'}}).injectInside(document.body);
this.image = new Element('div', {'id': 'lbImage'}).injectInside(this.center);
this.prevLink = new Element('a', {'id': 'lbPrevLink', 'href': '#', 'styles': {'display': 'none'}}).injectInside(this.image);
this.nextLink = this.prevLink.clone().setProperty('id', 'lbNextLink').injectInside(this.image);
this.prevLink.onclick = this.previous.bind(this);
this.nextLink.onclick = this.next.bind(this);
this.bottomContainer = new Element('div', {'id': 'lbBottomContainer', 'styles': {'display': 'none'}}).injectInside(document.body);
this.bottom = new Element('div', {'id': 'lbBottom'}).injectInside(this.bottomContainer);
new Element('a', {'id': 'lbCloseLink', 'href': '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
this.caption = new Element('div', {'id': 'lbCaption'}).injectInside(this.bottom);
this.number = new Element('div', {'id': 'lbNumber'}).injectInside(this.bottom);
new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.bottom);
var nextEffect = this.nextEffect.bind(this);
this.fx = {
overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
image: this.image.effect('opacity', {duration: 500, onComplete: nextEffect}),
bottom: this.bottom.effect('margin-top', {duration: 400, onComplete: nextEffect})
};
this.preloadPrev = new Image();
this.preloadNext = new Image();
},
click: function(link){
if (link.rel.length == 8) return this.show(link.href, link.title);
var j, imageNum, images = [];
this.anchors.each(function(el){
if (el.rel == link.rel){
for (j = 0; j < images.length; j++) if(images[j][0] == el.href) break;
if (j == images.length){
images.push([el.href, el.title]);
if (el.href == link.href) imageNum = j;
}
}
}, this);
return this.open(images, imageNum);
},
show: function(url, title){
return this.open([[url, title]], 0);
},
open: function(images, imageNum){
this.images = images;
this.position();
this.setup(true);
this.top = window.getScrollTop() + (window.getHeight() / 15);
this.center.setStyles({top: this.top, display: ''});
this.fx.overlay.start(0.8);
return this.changeImage(imageNum);
},
position: function(){
this.overlay.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
},
setup: function(open){
var elements = $A(document.getElementsByTagName('object'));
elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
elements.each(function(el){
if (open) el.lbBackupStyle = el.style.visibility;
el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
});
var fn = open ? 'addEvent' : 'removeEvent';
window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
document[fn]('keydown', this.eventKeyDown);
this.step = 0;
},
keyboardListener: function(event){
switch (event.keyCode){
case 27: case 88: case 67: this.close(); break;
case 37: case 80: this.previous(); break;
case 39: case 78: this.next();
}
},
previous: function(){
return this.changeImage(this.activeImage-1);
},
next: function(){
return this.changeImage(this.activeImage+1);
},
changeImage: function(imageNum){
if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
this.step = 1;
this.activeImage = imageNum;
this.bottomContainer.style.display = this.prevLink.style.display = this.nextLink.style.display = 'none';
this.fx.image.hide();
this.center.className = 'lbLoading';
this.preload = new Image();
this.preload.onload = this.nextEffect.bind(this);
this.preload.src = this.images[imageNum][0];
return false;
},
nextEffect: function(){
switch (this.step++){
case 1:
this.center.className = '';
this.image.style.backgroundImage = 'url('+this.images[this.activeImage][0]+')';
this.image.style.width = this.bottom.style.width = this.preload.width+'px';
this.image.style.height = this.prevLink.style.height = this.nextLink.style.height = this.preload.height+'px';
this.caption.setHTML(this.images[this.activeImage][1] || '');
this.number.setHTML((!this.options.showCounter || (this.images.length == 1)) ? '' : 'Image '+(this.activeImage+1)+' of '+this.images.length);
if (this.activeImage) this.preloadPrev.src = this.images[this.activeImage-1][0];
if (this.activeImage != (this.images.length - 1)) this.preloadNext.src = this.images[this.activeImage+1][0];
if (this.center.clientHeight != this.image.offsetHeight){
this.fx.resize.start({height: this.image.offsetHeight});
break;
}
this.step++;
case 2:
if (this.center.clientWidth != this.image.offsetWidth){
this.fx.resize.start({width: this.image.offsetWidth, marginLeft: -this.image.offsetWidth/2});
break;
}
this.step++;
case 3:
this.bottomContainer.setStyles({top: this.top + this.center.clientHeight, height: 0, marginLeft: this.center.style.marginLeft, display: ''});
this.fx.image.start(1);
break;
case 4:
if (this.options.animateCaption){
this.fx.bottom.set(-this.bottom.offsetHeight);
this.bottomContainer.style.height = '';
this.fx.bottom.start(0);
break;
}
this.bottomContainer.style.height = '';
case 5:
if (this.activeImage) this.prevLink.style.display = '';
if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';
this.step = 0;
}
},
close: function(){
if (this.step < 0) return;
this.step = -1;
if (this.preload){
this.preload.onload = Class.empty;
this.preload = null;
}
for (var f in this.fx) this.fx[f].stop();
this.center.style.display = this.bottomContainer.style.display = 'none';
this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
return false;
}
};
window.addEvent('domready', Lightbox.init.bind(Lightbox));
The lightbox script processes all the images at page load, so any images that you dynamically insert after page load will not be lightboxed. Look at the lightbox script and call whatever function processes images on page load after you have inserted the new images.
Related
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)
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>
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;
});
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.
I'm trying to automate the slideshow on my site: Test Site
I found this awesome jquery template online: http://tympanus.net/codrops/2011/08/...ge-navigation/. I modified the html/css and got it to look the way I want but now need JavaScript help!
The slideshow currently progresses when you click on the arrows but I was wondering if there was a way to automate the clicking function so that the slideshow animation automatically starts when the webpage is loaded. I still want the user to be able to control the slideshow with the arrows. I also wanted the slideshow to go back to the first image when it's reaches the last image.
(function($){
$.fn.portfolio = function(options) {
var d = {
image: {
width: 760,
height: 507,
margin: 10
},
path: {
width: 10,
height: 10,
marginTop: 5,
marginLeft: 5
},
animationSpeed: 400
}; // default settings
var s = $.extend({}, d, options);
return this.each(function(){
var $t = $(this),
plugin = {
init: function(){
this.set.position();
this.paths.draw();
this.paths.go();
this.animate.item();
},
set: {
position: function(){
$t.find('.item').each(function(i){
var t = $(this);
t.css({ left: (s.image.width+s.image.margin)*i+'px' });
t.find('div').each(function(j){
var t = $(this);
t.css({ top: (s.image.height+s.image.margin)*j+'px' });
});
});
}
},
paths: {
draw: function(){
$t.append($('<div />').addClass('paths'));
var path = $t.find('.paths'),
items = $t.find('.item');
items.each(function(i){
var t = $(this), div = t.find('div');
path.append($('<div />').addClass('path'+i).css({
width: s.path.width+'px',
left: (s.path.width+s.path.marginLeft)*i+'px'
})
);
div.each(function(j){
$('<a />').attr({ href: '#', rel: j }).css({
width: s.path.width+'px',
height: s.path.height+'px',
top: (s.path.height+s.path.marginTop)*j+'px'
}).appendTo(path.find('.path'+i))
});
});
path.find('.path0').find('a').eq(0).addClass('active');
},
go: function(){
$t.find('.paths').find('a').click(function(){
var t = $(this), all = $t.find('.paths').find('a'), column = t.parent('div').attr('class').split('path')[1], row = t.attr('rel'),
inside = $t.find('.inside'),
top = row*(s.image.height+s.image.margin),
left = column*(s.image.width+s.image.margin);
inside.animate({
top: -top+'px',
left: -left+'px'
}, s.animationSpeed, function(){
plugin.position.get(inside);
});
return false;
});
},
classes: function(column, row){
var anchors = $t.find('.paths').find('a'), anchor = anchors.filter(function(){
var t = $(this),
col = t.parent('div').attr('class').split('path')[1],
r = t.attr('rel');
return col == column && r == row;
});
anchors.removeClass('active');
anchor.addClass('active');
}
},
animate: {
item: function(){
var down = { top: '-='+(s.image.height+s.image.margin)+'px' },
up = { top: '+='+(s.image.height+s.image.margin)+'px' },
next = { top: 0, left: '-='+(s.image.width+s.image.margin)+'px' },
prev = { top: 0, left: '+='+(s.image.width+s.image.margin)+'px' }
plugin.animate.img('.down', down, 40);
plugin.animate.img('.up', up, 38);
plugin.animate.img('.next', next, 39);
plugin.animate.img('.prev', prev, 37);
},
img: function(element, object, key){
var inside = $t.find('.inside'), type = $.browser.mozilla ? 'keypress' : 'keydown';
$(element).click(function(){
var t = $(this);
if (!t.hasClass('active')){
inside.animate(object, s.animationSpeed, function(){
plugin.position.get(inside);
t.removeClass('active');
});
}
t.addClass('active');
return false;
});
$(document).bind(type, function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if(code == key && $(element).is(':visible')) {
if (!inside.is(':animated')) {
inside.animate(object, s.animationSpeed, function(){
plugin.position.get(inside);
});
}
}
return false;
});
}
},
position: {
get: function(element){
var top = element.position().top,
left = element.position().left;
plugin.position.check(top, left);
},
check: function(top, left){
top = ($.browser.msie && parseInt($.browser.version) == 8 && top != 0) ? top-1 : top;
var items = $t.find('.item'),
size_left = items.length-1,
max_left = -size_left*(s.image.width+s.image.margin),
column = left*size_left/max_left,
current = items.filter(function(){
return parseInt($(this).css('left')) == -left;
}),
size_top = current.find('div').length-1,
max_top = -size_top*(s.image.height+s.image.margin),
row = top*size_top/max_top,
arrows = $t.find('.arrows'),
up = arrows.find('.up'), down = arrows.find('.down'),
next = arrows.find('.next'), prev = arrows.find('.prev');
if (left==max_left){ next.hide(); } else { next.show(); }
if (left<0) { prev.show(); } else { prev.hide(); }
if (top==max_top){ down.hide(); } else { down.show(); }
if (top<0) { up.show(); } else { up.hide(); }
plugin.paths.classes(column, row);
}
}
}
plugin.init();
});
};}(jQuery));
Just make a timer that calls $(".next").click(); to make the slides go forward.