Navigating long un-ordered list - javascript

I have this long list with overflow: auto to scroll through it, i set it up for keyboard navigation, the problem is that when using the keyboard it doesn't scroll correctly!
check this jsFiddle
$('ul').keydown(function (e) {
if (e.keyCode == 38) { // up
var selected = $(".selected");
$listItems.removeClass("selected");
if (selected.prev().length == 0) {
selected.siblings().last().addClass("selected");
} else {
selected.prev().addClass("selected");
}
}
if (e.keyCode == 40) { // down
var selected = $(".selected");
$listItems.removeClass("selected");
if (selected.next().length == 0) {
selected.siblings().first().addClass("selected");
} else {
selected.next().addClass("selected");
}
}
})
});
$listItems.click(function () {
if ($(this).is('.selected')) {
return true;
} else {
$('li').removeClass('selected');
$(this).addClass('selected');
}
the behavior i'm looking for is the same behavior of the element when scrolling through a long list of elements using the keyboard this plugin SelectBoxIt show's what i'm looking for.

you can use this code instead, i used animate function to navigate inside the div if the list exceed the width of the ul tag :
http://jsfiddle.net/goldendousa/p6243/13/
$('ul').focus(function() {
if ($('ul li').is('.selected')) {
$('ul li').first().removeClass('selected');
} else {
$('ul li').first().addClass('selected');
}
});
$('ul').keydown(function(e) {
if (e.keyCode == 38) { // up
e.preventDefault();
var selected = $(".selected");
$("ul li").removeClass("selected");
if (selected.prev().length == 0) {
selected.siblings().last().addClass("selected");
var selectedTopOffset = selected.siblings().last().offset().top;
$('div').animate({
scrollTop: selectedTopOffset
}, 200);
} else {
selected.prev().addClass("selected");
var selectedTopOffset = $("div").scrollTop() + selected.position().top - $("div").height()/2 + selected.height()/2;
$('div').animate({
scrollTop: selectedTopOffset
}, 200);
}
}
if (e.keyCode == 40) { // down
e.preventDefault();
var selected = $(".selected");
$("ul li").removeClass("selected");
if (selected.next().length == 0) {
selected.siblings().first().addClass("selected");
if (selected.siblings().first().offset().top < 0) {
$('div').animate({
scrollTop: selected.siblings().first().offset().top
}, 200);
}
} else {
selected.next().addClass("selected");
var selectedTopOffset = $("div").scrollTop() + selected.position().top - $("div").height()/2 + selected.height()/2;
$('div').animate({
scrollTop: selectedTopOffset
}, 200);
}
}
});
$('li').click(function() {
if ($(this).is('.selected')) {
return true;
} else {
$('li').removeClass('selected');
$(this).addClass('selected');
}
});

Related

jQuery change page and show tab on menu entry click

var tab = null;
var menuSelector = null;
jQuery(function ($) {
console.log('test');
//howtos tab
function changeMenuSelector() {
if ($( document ).width() > 967) {
menuSelector = 'top-menu-nav';
} else {
menuSelector = 'mobile_menu';
}
}
changeMenuSelector();
$( window ).resize(function() {
changeMenuSelector();
});
$('#'+menuSelector+' a[href*="howtos"]').on('click', function(event){
var e = event;
var $ = jQuery;
setTimeout(function () {
e.preventDefault();
console.log('pluto');
window.localStorage.setItem('tab', 'et_pb_tab_0');
if(window.location.pathname.indexOf('blog-posts') === -1)
{
window.location.href='http://www.davidepugliese.com/blog-posts/';
} else {
tab = localStorage.getItem('tab');
$("li."+tab+">a")[0].click();
window.localStorage.removeItem('tab');
}
},1000);});
$('#'+menuSelector +' a[href*="projects"]').on('click', function(e){
e.preventDefault();
console.log('pluto');
localStorage.setItem('tab', 'et_pb_tab_1');
if(window.location.pathname.indexOf('blog-posts') === -1)
{
window.location.href='http://www.davidepugliese.com/blog-posts/';
} else {
tab = localStorage.getItem('tab');
$("li."+tab+">a")[0].click();
localStorage.removeItem('tab');
}
});
$('#'+menuSelector +' a[href*="reviews"]').on('click', function(e){
e.preventDefault();
console.log('pluto');
localStorage.setItem('tab', 'et_pb_tab_2');
if(window.location.pathname.indexOf('blog-posts') === -1)
{
window.location.href='http://www.davidepugliese.com/blog-posts/';
} else {
tab = localStorage.getItem('tab');
$("li."+tab+">a")[0].click();
localStorage.removeItem('tab');
}
});
$('#'+menuSelector +' a[href*="elearning"]').on('click', function(e){
e.preventDefault();
console.log('pluto');
localStorage.setItem('tab', 'et_pb_tab_3');
if(window.location.pathname.indexOf('blog-posts') === -1)
{
window.location.href='http://www.davidepugliese.com/blog-posts/';
} else {
tab = localStorage.getItem('tab');
$("li."+tab+">a")[0].click();
localStorage.removeItem('tab');
}
});
$('#'+menuSelector +' a[href*="others"]').on('click', function(e){
e.preventDefault();
console.log('pluto');
localStorage.setItem('tab', 'et_pb_tab_4');
if(window.location.pathname.indexOf('blog-posts') === -1)
{
window.location.href='http://www.davidepugliese.com/blog-posts/';
} else {
tab = localStorage.getItem('tab');
$("li."+tab+">a")[0].click();
localStorage.removeItem('tab');
}
});
if (!!localStorage.getItem('tab')) {
tab = localStorage.getItem('tab');
console.log(tab);
setTimeout(function(){$("li."+tab+">a")[0].click();}, 1)
$("html, body").animate({ scrollTop: $('.et_pb_module.et_pb_tabs.et_pb_tabs_0').offset().top },
1000);
localStorage.removeItem('tab');
}
});
I have created a script to show tabs in Divi when you click on a menu entry. Divi does not use ids and hrefs for this, so I had to use a script.
The problem that I am facing is that this script that I made does not work with Divi's mobile menu.
I checked if menuSelector changed properly and if changeMenuSelector got executed as expected.
Furthermore, $('#'+menuSelector+' a[href*="howtos"]').length returns 1 in console and if I run $('#'+menuSelector+' a[href*="howtos"]')[0] in console I obtain the expected DOM element whehter I have the browser window sized for mobile or for desktop devices.
I also tried using setTimeout in case the issue was that it needed some time to accomplish an earlier action without any luck.
Therefore, is there anyone that could tell me why this does not work when the website is running in mobile mode?
I solved the issue by refactoring the code like this:
jQuery(function ($) {
console.log('test');
var tab = null;
var menuSelector = null;
var guard = false;
function changeMenuSelector() {
if ($(document).width() > 967) {
menuSelector = 'top-menu-nav';
guard = false;
initEventListeners(guard);
} else {
menuSelector = 'mobile_menu';
guard = true;
initEventListeners(guard);
}
}
function initEventListeners(guard) {
var localGuard = null;
if (localGuard != guard) {
var hrefs = ['howtos', 'projects', 'reviews', 'elearning', 'others'];
hrefs.forEach(
function (element, index, array) {
$('#' + menuSelector + ' a[href*="' + element + '"]').off();
console.log(element);
$('#' + menuSelector + ' a[href*="' + element + '"]').on('click', function (e) {
e.preventDefault();
console.log('pluto');
window.localStorage.setItem('tab', 'et_pb_tab_' + index);
if (window.location.pathname.indexOf('blog-posts') === -1) {
window.location.href = 'http://www.davidepugliese.com/blog-posts/';
} else {
tab = localStorage.getItem('tab');
$("li." + tab + ">a")[0].click();
$("html, body").animate({ scrollTop: $('.et_pb_module.et_pb_tabs.et_pb_tabs_0').offset().top },
1000);
window.localStorage.removeItem('tab');
}
});
});
localGuard = guard;
}
}
changeMenuSelector();
initEventListeners();
$(window).resize(function () {
changeMenuSelector();
});
if (!!localStorage.getItem('tab')) {
tab = localStorage.getItem('tab');
console.log(tab);
setTimeout(function(){$("li."+tab+">a")[0].click();}, 1)
$("html, body").animate({ scrollTop: $('.et_pb_module.et_pb_tabs.et_pb_tabs_0').offset().top },
1000);
localStorage.removeItem('tab');
}
});

Create a javascript object

I would say I am fairly decent with javascript and jQuery, well, enough to get the job done and done pretty well.
I do however lack a deep understanding of js.
I have created some functions for highlighting table elements.
ctrl+click toggles selections
shift+click+drag highlights selection
My question does not pertain to whether or not my implementation is the best way or not but ...
How do I abstract this functionality so I can add this functionality to any table. Like if I add more highlighting features and such and put this in its own .js file. How would I attach it to any html table?
Sorry if this has already been answered, but I could not think of what to search for.
Thank you.
****Newest Code****
This code is in its own .js file and is attached to my table.
All the current functionality is there. The only thing I am weary of is the .off() functions. In my case, I am reloading new tables.... as I type this, I realize I should just empty the tr's from the table instead of recreating a new table all the time, then I could get rid of the .off() calls.
$.fn.addEvents = function(obj)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: 0,
mouseleaveindex: 0,
trajectory: null,
tmptrajectory: null
}, obj || {});
$(document)
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
....
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
....
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!properties.ctrling && !properties.shifting)
{
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
properties.mouseenterindex = $(this).index();
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
you can wrap all this in a function since you have some local variables related to individual selection
$.fn.addEvents = function(obj) {
var properties = $.extend(true, {
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
trajectory: null
}, obj || {});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function() {
.....
})
.on('mouseleave', function(e) {
//rename your local variables with `properties.` prefix
properties.mouseleave = e.clientY;
if (properties.shifting && properties.mousing) {
tmptrajectory = properties.mouseenter - properties.mouseleave < 0 ? 1 : -1;
}
if ($(this).hasClass('selected') && properties.shifting && properties.mousing && properties.trajectory != null && properties.trajectory != tmptrajectory) {
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
....
});
}
usage
$('#datatablebody tr').addEvents({ shifting: false, ctrling: true }); //custom settings
$('#someother tr').addEvents(); //default settings
you could add that functionality to a class and add that class to the tables you want to affect...
Here I create the class .myTableBeh and all tables with that class will have the behaviour you programmed.
var shifting = false;
var ctrling = false;
var mousing = false;
var mouseenter = 0;
var mouseleave = 0;
var trajectory = null;
$('.myTableBeh tr')
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!ctrling)
{
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
mousing = true;
multiselectrow($(this));
})
.off('mouseenter')
.on('mouseenter', function(e)
{
mouseenter = e.clientY;
multiselectrow($(this));
})
.off('mouseleave')
.on('mouseleave', function(e)
{
mouseleave = e.clientY;
if(shifting && mousing)
{
tmptrajectory = mouseenter - mouseleave < 0?1:-1;
}
if($(this).hasClass('selected') && shifting && mousing && trajectory != null && trajectory != tmptrajectory)
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
if(shifting && mousing && trajectory == null)
{
trajectory = tmptrajectory;
}
})
.off('mouseup')
.on('mouseup', function(e)
{
mousing = false;
trajectory = null;
multiselectrow($(this));
});
Thanks to the answer from #JAG I was able to create a nice add on to any HTML table that handles highlighting.
Check out the fiddle for the working version and please use it if you find it helpful or useful for your site.
You can even implement keys to move the tr position up or down in the table. I removed my implementation because it was specific to the project I am working on.
I made it so you have to mouse over the table in order to interact with it and mouse leave to un-focus it.
https://jsfiddle.net/kwj74kg0/2/
//Add the events simply by running this
$('#dtable tr').addEvents(0);
/**
* This add on can be applied and customized to any html tr set i.e. $('#tableid tr').addEvents()
* It will add highlighting capability to the table.
*
* Single click highlight tr
* Click -> Shift + click highlight/toggle range
* Shift+MouseDown+Drag highlight/toggle range
* Ctrl+Click toggle item
*
*
* #author Michaela Ervin
*
* #param tabindex
*
* Help from JAG on http://stackoverflow.com/questions/39022116/create-a-javascript-object
*/
$.fn.addEvents = function(tabindex)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: null,
mouseleaveindex: null,
trajectory: null,
tmptrajectory: null
}, {});
/**
* Add events to closest table.
*/
$(this)
.closest('table')
.attr('tabindex', tabindex)
.off('mouseenter')
.on('mouseenter', function()
{
$(this).focus();
})
.off('mouseleave')
.on('mouseleave', function()
{
$(this).blur();
properties.mousing = false;
properties.trajectory = null;
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
properties.mouseintermediateindex = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
//Function to move tr 'up'.
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
//Function to move tr 'down'.
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
/**
* Add tr specific events
*/
return $(this)
.off('click')
.on('click', function()
{
if(!properties.shifting && properties.mouseenterindex != null)
{
properties.mouseenterindex = null;
properties.mousing = false;
}
if(!properties.ctrling && !properties.shifting && properties.mouseenterindex == null)
{
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
if(properties.mouseenterindex == null)
{
properties.mouseenterindex = $(this).index();
}
else if(properties.shifting && properties.mouseenterindex != null)
{
properties.mouseleaveindex = $(this).index();
highlightRange($(this).parent(), properties.mouseenterindex, properties.mouseleaveindex, properties.mouseenterindex);
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
})
.off('contextmenu')
.on('contextmenu', function(ev)
{
ev.preventDefault();
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
//Put your context menu here
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing && properties.mouseenterindex == null)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(!properties.shifting)
{
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
function highlightRange(obj, start, end, mouseenterindex)
{
if(start < end)
{
for(var i=start; i<=end; i+=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
else
{
for(var i=start; i>=end; i-=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
}

Set interval to make auto-slide functionality(Magento Site)

the below-following code is written by freelancer programmer for the silde banner for our Magento website. This is only for slide banner when the customer clicks the pager navigation menu; it slides to next banner. I want to set Interval for this so that It can automatically slide with clicking pager button. Thank you!!!
function initialize_banner_slider(banner_id) {
if ($(banner_id).size() <= 0) return;
var make_center = function(center) {
center.removeClass("on_right").removeClass("on_left").addClass("on_center");
$("body").removeClass("theme-light").removeClass("theme-dark").addClass("theme-"+center.data("theme"));
center.find(".fadeup").each(function() {
$(this).hide().css("top", (parseInt($(this).data("pos-y"))/750*100+100) + "%");
});
$(banner_id + " ul.banner_pager li").removeClass("active");
$($(banner_id + " ul.banner_pager li")[center.index()]).addClass("active");
setTimeout(function() {
center.find(".fadeup").each(function() {
$(this).show().animate({"top": "-=100%"});
/* $(this).css("top", parseInt($(this).data("pos-y"))); */
});
}, 600);
}
var move_full_card_left = function(banner_id) {
if ($(banner_id).find(".on_right").size() > 0) {
$(banner_id).find(".on_center").removeClass("on_center").addClass("on_left");
make_center( $(banner_id).find(".on_right").first() );
if ($(banner_id).find(".on_right").size() == 0) {
// hide arrow
$(banner_id).find(".move_right").hide();
} else {
// show arrow
$(banner_id).find(".move_right").show();
}
$(banner_id).find(".move_left").show();
}
return false;
}
var move_full_card_right = function(banner_id) {
if ($(banner_id).find(".on_left").size() > 0) {
$(banner_id).find(".on_center").removeClass("on_center").addClass("on_right");
make_center( $(banner_id).find(".on_left").last() );
if ($(banner_id).find(".on_left").size() == 0) {
// hide arrow
$(banner_id).find(".move_left").hide();
} else {
// show arrow
$(banner_id).find(".move_left").show();
}
$(banner_id).find(".move_right").show();
}
return false;
}
$(banner_id).find(".move_left").click(function() {
return move_full_card_right(banner_id);
});
$(banner_id).find(".move_right").click(function() {
return move_full_card_left(banner_id);
});
for (var i=0, l=$(banner_id+" > ul.slider > li").size(); i<l; i++) {
var pager = $("<li></li>");
pager.on("click", function() {
var index = $(this).index();
$(banner_id+" > ul.slider > li").each(function(ndx, val) {
if (ndx < index) {
$(this).removeClass("on_center").removeClass("on_right").addClass("on_left");
} else if (ndx > index) {
$(this).removeClass("on_center").removeClass("on_left").addClass("on_right");
} else if (ndx == index) {
make_center($(this));
}
});
});
pager.appendTo($(banner_id + " ul.banner_pager"));
}
var first = true;
$(banner_id+" > ul.slider > li").each(function(elem) {
if (first) {
make_center( $(this) );
first = false;
} else {
$(this).addClass("on_right");
}
$(this).on("swipeleft", function() {
return move_full_card_left(banner_id);
}).on("swiperight", function() {
return move_full_card_right(banner_id);
});
$(this).css("background-image", "url("+$(this).data("background-image")+")");
});
if ($(banner_id+" > ul.slider > li").size() < 2) {
$(banner_id).find(".move_right").hide();
}
$(banner_id).find(".move_left").hide();
}
function initialize_parallax() {
$(".responsive_wrapper").each(function() {
var base_width = $(this).data("width");
var base_height = $(this).data("height");
$(this).css({
"max-width": base_width+"px",
"max-height": base_height+"px"
});
$(this).find(".responsive").each(function() {
$(this).css({
"width": $(this).data("width")/base_width*100 + "%",
"height": $(this).data("height")/base_height*100 + "%",
"left": $(this).data("pos-x")/base_width*100 + "%",
"top": (parseInt($(this).data("pos-y"))/base_height*100) + "%",
});
});
});
}
$(document).ready(function() {
/* parallax positioning */
// $(".verus-cms .parallax").insertAfter( $(".page-header") );
$("#product-list-toolbar2").prependTo(".col-main");
initialize_parallax();
initialize_banner_slider("#top_banner");
initialize_banner_slider("#lific_banner");
You would add something like this:
setInterval(function(){move_full_card_right(banner_id);},5000);
You should be able to throw that in you document ready as long as you can get the banner_id. I don't know how you are setting the banner id, so I can't help you with that.

jQuery/javascript - can't find a way to avoid code adding a class

I'm currently modifying the FlexNav Plugin. Instead of hovering to open the sub-menus, I changed it to open by click.
The problem now is that it takes two clicks to open a submenu.
I understand the problem is the fact that the code adds the class "flexnav-show" to the submenu ul when the menu is opened intitially. A click on the submenu trigger then removes this class, which causes nothing, and a second click add it again opening the submenu.
If anyone can point me to the right place in the code where i can avoid adding the class on all ul's. Or, if someone has a better idea...
$.fn.flexNav = function(options) {
var $nav, $top_nav_items, breakpoint, count, nav_percent, nav_width, resetMenu, resizer, settings, showMenu, toggle_selector, touch_selector;
settings = $.extend({
'animationSpeed': 250,
'transitionOpacity': true,
'buttonSelector': '.menu-button',
'hoverIntent': false,
'hoverIntentTimeout': 150,
'calcItemWidths': false,
'hover': false
}, options);
$nav = $(this);
$nav.addClass('with-js');
if (settings.transitionOpacity === true) {
$nav.addClass('opacity');
}
$nav.find("li").each(function() {
if ($(this).has("ul").length) {
return $(this).addClass("item-with-ul").find("ul").hide();
}
});
if (settings.calcItemWidths === true) {
$top_nav_items = $nav.find('>li');
count = $top_nav_items.length;
nav_width = 100 / count;
nav_percent = nav_width + "%";
}
if ($nav.data('breakpoint')) {
breakpoint = $nav.data('breakpoint');
}
showMenu = function() {
if ($nav.hasClass('lg-screen') === true && settings.hover === true) {
if (settings.transitionOpacity === true) {
return $(this).find('>ul').addClass('flexnav-show').stop(true, true).animate({
height: ["toggle", "swing"],
opacity: "toggle"
}, settings.animationSpeed);
} else {
return $(this).find('>ul').addClass('flexnav-show').stop(true, true).animate({
height: ["toggle", "swing"]
}, settings.animationSpeed);
}
}
};
resetMenu = function() {
if ($nav.hasClass('lg-screen') === true && $(this).find('>ul').hasClass('flexnav-show') === true && settings.hover === true) {
if (settings.transitionOpacity === true) {
return $(this).find('>ul').removeClass('flexnav-show').stop(true, true).animate({
height: ["toggle", "swing"],
opacity: "toggle"
}, settings.animationSpeed);
} else {
return $(this).find('>ul').removeClass('flexnav-show').stop(true, true).animate({
height: ["toggle", "swing"]
}, settings.animationSpeed);
}
}
};
resizer = function() {
var selector;
if ($(window).width() <= breakpoint) {
$nav.removeClass("lg-screen").addClass("sm-screen");
if (settings.calcItemWidths === true) {
$top_nav_items.css('width', '100%');
}
selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button';
$(selector).removeClass('active');
return $('.one-page li a').on('click', function() {
return $nav.removeClass('flexnav-show');
});
} else if ($(window).width() > breakpoint) {
$nav.removeClass("sm-screen").addClass("lg-screen");
if (settings.calcItemWidths === true) {
$top_nav_items.css('width', nav_percent);
}
$nav.removeClass('flexnav-show').find('.item-with-ul').on();
$('.item-with-ul').find('ul').removeClass('flexnav-show');
resetMenu();
if (settings.hoverIntent === true) {
return $('.item-with-ul').hoverIntent({
over: showMenu,
out: resetMenu,
timeout: settings.hoverIntentTimeout
});
} else if (settings.hoverIntent === false) {
return $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu);
}
}
};
$(settings['buttonSelector']).data('navEl', $nav);
touch_selector = '.item-with-ul, ' + settings['buttonSelector'];
$(touch_selector).append('<span class="touch-button"><i class="navicon">▼</i></span>');
toggle_selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button';
$(toggle_selector).on('click', function(e) {
var $btnParent, $thisNav, bs;
$(toggle_selector).toggleClass('active');
e.preventDefault();
e.stopPropagation();
bs = settings['buttonSelector'];
$btnParent = $(this).is(bs) ? $(this) : $(this).parent(bs);
$thisNav = $btnParent.data('navEl');
return $thisNav.toggleClass('flexnav-show');
});
$('.touch-button').on('click', function(e) {
var $sub, $touchButton;
$sub = $(this).parent('.item-with-ul').find('>ul');
$touchButton = $(this).parent('.item-with-ul').find('>span.touch-button');
if ($nav.hasClass('lg-screen') === true) {
$(this).parent('.item-with-ul').siblings().find('ul.flexnav-show').removeClass('flexnav-show').hide();
}
if ($sub.hasClass('flexnav-show') === true) {
$sub.removeClass('flexnav-show').slideUp(settings.animationSpeed);
return $touchButton.removeClass('active');
} else if ($sub.hasClass('flexnav-show') === false) {
$sub.addClass('flexnav-show').slideDown(settings.animationSpeed);
return $touchButton.addClass('active');
}
});
$nav.find('.item-with-ul *').focus(function() {
$(this).parent('.item-with-ul').parent().find(".open").not(this).removeClass("open").hide();
return $(this).parent('.item-with-ul').find('>ul').addClass("open").show();
});
resizer();
return $(window).on('resize', resizer);
};
The code adds the class 'flexnav-show' in line 34 to all child 'ul' nodes.
The code is in action when the function showMenu is called.

jQuery event.stopPropagation() and event issues

I'm creating a jQuery script that add a pin to a map on click event, the problem is that i need that event to work only on the map not his sons too..
This is my code:
$("div#map").click(function (e) {
$('<div class="pin"></div>').css({
left: a_variable,
top: another_variable
}).appendTo(this);
$("div.pin").click(function (e) { e.stopPropagation(); });
})
Another problem is that under this code i have something like this:
$("div.pin").mousedown(function (e) {
if(e.which == 1) {
console.log("down");
moving = true;
$(this).addClass("moving");
} else if(e.which == 3) {
console.log("right");
}
});
Will this work with pins created after the script load too?
JsFiddle: http://jsfiddle.net/vB2Gb/
I made a number of adjustments to your code:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/vB2Gb/1/
$(function () {
var $map = $("div#map");
$map.click(function (e) {
var $pin = $('<div class="pin"></div>').css({
left: (((e.pageX + 3 - $map.position().left) * 100) / $map.width()) + "%",
top: (((e.pageY - 10 - $map.position().top) * 100) / $map.height()) + "%"
});
$pin.appendTo($map);
})
$map.on('click', "div.pin", function (e) {
e.stopPropagation();
});
var moving = false;
var pin_id;
var pin_left;
var pin_top;
$map.on('mousedown', "div.pin", function (e) {
if (e.which == 1) {
console.log("down");
moving = true;
$(this).addClass("moving");
} else if (e.which == 3) {
console.log("right");
}
});
$map.on('contextmenu', "div.pin", function (e) {
return false;
});
$(document).mousemove(function (e) {
if (moving) {
if (e.pageX <= $map.position().left) {
pin_left = 0;
} else if (e.pageY <= $map.position().top) {
pin_top = 0;
} else {
console.log("moving");
pin_id = 1;
pin_left = (((e.pageX + 3 - $map.position().left) * 100) / $map.width());
pin_top = (((e.pageY - 10 - $map.position().top) * 100) / $map.height());
$(".moving").css("left", pin_left + "%");
$(".moving").css("top", pin_top + "%");
}
}
});
$(document).mouseup(function (e) {
if (moving) {
console.log("up");
moving = false;
$(".moving").removeClass("moving");
dbMovePin(pin_id, pin_left, pin_top);
}
});
});
function dbMovePin(pin_id, pin_left, pin_top) {
$.post(
"mapsave.php", {
action: "move_pin",
id: pin_id,
left: pin_left,
top: pin_top
},
function (data, status) {
//alert("Data: " + data + "\nStatus: " + status);
});
}
This includes using delegated events (with on) for both the mouse down events and the pin click. Sharing a single variable for the map etc
Event Delegation does what i need:
I've changed
$("div.pin").mousedown(function (e) { ... });
with
$("div#map").on("mousedown", "div", function (e) {
Since you are dealing with dynamically added elements, you need to use event delegation.
$("#map").click(function (e) {
$('<div class="pin"></div>').css({
left: a_variable,
top: another_variable
}).appendTo(this);
}).on('click', '.pin', function (e) {
//have a single delegated click handler
e.stopPropagation();
}).on('mousedown', '.pin', function (e) {
//use a delegated handler for mousedown also
if (e.which == 1) {
console.log("down");
moving = true;
$(this).addClass("moving");
} else if (e.which == 3) {
console.log("right");
}
})
Also see
Event binding on dynamically created elements?

Categories