Shift an array and rendering it in a html list - javascript

Using the following script I am not able to swift and set the focus for an array back in the list when clicking PREV.
It should work as this example:
http://jsfiddle.net/QAsQj/2/
my code here
http://jsfiddle.net/Eq4js/
Could you point me out what am I doing wrong here, I would appreciate a sample of code on
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.focus { color: red; }
</style>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.1.min.js"></script>
<script>
$(document).ready(function() {
var snippet = {
index: 0,
indexNew: 0,
start: 0,
$el: 'div.snippet-categories',
config: {
itemsVisible: 4
},
data: {
items: {
models: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
},
navigate: function(direction) {
if (direction === 'right') {
if (this.index < this.config.itemsVisible - 1) {
if (this.index < this.config.itemsVisible - 1) {
this.index++;
var result = '#' + this.index + '';
$('li.focus').removeClass('focus');
$(result).addClass('focus');
} else {
this.start++;
}
} else {
if (this.start < this.data.items.models.length - this.config.itemsVisible) {
this.start++;
this.renderItems();
var result = '#' + (this.config.itemsVisible - 1 + this.start) + '';
$('li.focus').removeClass('focus');
$(result).addClass('focus');
}
}
}
else if (direction === 'left') {
if (this.index > this.config.itemsVisible - 1) {
if (this.index > this.config.itemsVisible - 1) {
this.index--;
(Focus.to(this.getFocusable(-1, true)));
} else {
this.start++;
}
} else {
if (this.start > this.data.items.models.length - this.config.itemsVisible) {
this.index--;
this.renderItems();
} else {
}
}
}
},
render: function() {
this.renderItems();
},
renderItems: function(reverse) {
var reverse = reverse || false;
var html = '', result = '', subset = null;
var range = this.data.items.models;
var limit = range.length - this.config.itemsVisible;
if (this.indexNew !== null) {
if (reverse === false) {
} else {
}
subset = range.slice(this.start, this.start + this.config.itemsVisible);
var i = 0;
while (i < subset.length) {
var x = subset[i];
result += '<li id="' + this.data.items.models[x] + '" data-idx="' + this.data.items.models[x] + '" class="focusable">' + this.data.items.models[x] + '</li>';
i++;
}
html = result + '</ul>';
var el = $(this.$el);
el.empty();
el.append(html);
} else {
console.log('limit STOP');
}
},
};
snippet.render();
$('#next').click(function() {
snippet.navigate("right");
});
$('#prev').click(function() {
snippet.navigate("left");
});
});
</script>
</head>
<body>
<div class="snippet-categories"></div>
<div id="prev">prev</div>
<div id="next">next</div>
</body>
</html>
This question is related to
Are you able to solve it? JavaScript carousel implementation using an array

Finally I solved it
Algo example here
http://jsfiddle.net/QwATR/
Snippet_Categories = (function(Snippet) {
var Snippet_Categories = function() {
this.config = {
curPos: 0, // index for selected element
itemVisible: 4, // number of items visible
minIndex: 0, // define visible area start
maxIndex: 4 - 1, // define visible area end = "itemVisible -1"
outItems: 0 // number of element out of visible area
};
this.data = {
items: arguments[1].items
};
this.construct.apply(this, arguments);
};
$.extend(true, Snippet_Categories.prototype, Snippet.prototype, {
init: function() {
this.index = 0; // set default index
this.indexNew = 0; // set next index
this.start = 0;
this.render();
},
create: function() {
return this.parent.$el.find('.snippet-categories');
},
removeFocus: function() {
var test = $('li.focus');
Focus.blur(test);
//$('li.focus').removeClass('focus');
},
focus: function() {
//$('ul > li:eq(' + this.config.curPos + ')').addClass('focus');
var test = $('ul > li:eq(' + this.config.curPos + ')');
return Focus.to(test, true);
},
render: function() {
//debugger
this.renderItems();
this.focus();
},
renderItems: function() {
var html = '<ul>';
for (var i = 0; i < this.config.itemVisible; i++) {
html += '<li data-idx="' + this.data.items.at(i + this.config.outItems).get('id') + '" class="">' + this.data.items.at(i + this.config.outItems).get('label') + '</li>';
}
html += '</ul>';
$('.snippet-categories').empty();
$('.snippet-categories').html(html);
},
navigate: function(direction) {
if (direction === 'right') {
if (this.config.curPos < this.config.maxIndex)
{
this.removeFocus();
if (this.config.curPos < this.config.maxIndex)
this.config.curPos++;
else
{
this.config.outItems++;
}
} else {
if (this.config.outItems < this.data.items.length - this.config.itemVisible)
this.config.outItems++;
}
this.renderItems();
this.focus();
}
else if (direction === 'left') {
if (this.config.curPos > this.config.minIndex)
{
this.removeFocus();
if (this.config.curPos > this.config.minIndex)
this.config.curPos--;
else
{
this.config.clicks--;
}
} else {
if (this.config.outItems > 0)
this.config.outItems--;
}
this.renderItems();
this.focus();
}
},
onFocus: function() {
//this.index = parseInt(Focus.focused[0].dataset.idx, 10);
console.log('element in focus ' + this.index);
}
});
return Snippet_Categories;
})(Snippet);

Related

Links doesn't work on mobile / touch devices

I use XSwitch.js at my project and everything is perfect in Desktop view. But when I try to open the link from mobile / touch device seems like nothing happens. It's at 100% not a problem of z-index and positioning. As you can see if you try to click on the Example link on any section you'll can't open the link from mobile. / touch. I tested the issue with iPhone X, Galaxy Tab and Chrome Dev tools. I broke my head of trying to solve this bug and would much appreciate any help. Thanks!
(function($) {
$.fn.XSwitch = function(options) {
return this.each(function() {
var _this = $(this),
instance = _this.data('XSwitch');
if (!instance) {
instance = new XSwitch(_this, options);
_this.data('XSwitch', instance);
}
if ($.type(options) === 'string') {
return instance[options]();
}
});
}
$.fn.XSwitch.defaults = {
selectors: {
sections: '.sections',
section: '.section',
page: '.pages',
active: '.active'
},
index: 0,
easing: 'ease',
duration: 500,
loop: true,
pagination: true,
keyboard: true,
direction: 'vertical',
callback: ''
}
var _prefix = (function(temp) {
var aPrefix = ['webkit', 'moz', 'o', 'ms'],
props = '';
for (var i = 0, len = aPrefix.length; i < len; i++) {
props = aPrefix[i] + 'Transition';
if (temp.style[props] !== undefined) {
return '-' + aPrefix[i].toLowerCase() + '-';
}
return false;
}
})(document.createElement('div'));
var XSwitch = (function() {
function XSwitch(element, options) {
this.settings = $.extend(true, $.fn.XSwitch.defaults, options);
this.element = element;
this.init();
}
XSwitch.prototype = {
init: function() {
var _this = this;
this.selectors = this.settings.selectors;
this.sections = this.element.find(this.selectors.sections);
this.section = this.sections.find(this.selectors.section);
this.direction = this.settings.direction === 'vertical' ? true : false;
this.pagesCount = this.pagesCount();
this.index = (this.settings.index >= 0 && this.settings.index < this.pagesCount) ? this.settings.index : 0;
this.canScroll = true;
if (!this.direction) {
_initLayout(_this);
}
if (this.settings.pagination) {
_initPaging(_this);
}
_initEvent(_this);
},
pagesCount: function() {
return this.section.size();
},
switchLength: function() {
return this.duration ? this.element.height() : this.element.width();
},
prve: function() {
var _this = this;
if (this.index > 0) {
this.index--;
} else if (this.settings.loop) {
this.index = this.pagesCount - 1;
}
_scrollPage(_this);
},
next: function() {
var _this = this;
if (this.index < this.pagesCount) {
this.index++;
} else if (this.settings.loop) {
this.index = 0;
}
_scrollPage(_this);
}
};
function _initLayout(_this) {
var width = (_this.pagesCount * 100) + '%',
cellWidth = (100 / _this.pagesCount).toFixed(2) + '%';
_this.sections.width(width);
_this.section.width(cellWidth).css('float', 'left');
}
function _initPaging(_this) {
var pagesClass = _this.selectors.page.substring(1),
pageHtml = '<ul class="' + pagesClass + '">';
_this.activeClass = _this.selectors.active.substring(1);
for (var i = 0, len = _this.pagesCount; i < len; i++) {
pageHtml += '<li></li>';
}
pageHtml += '</ul>';
_this.element.append(pageHtml);
var pages = _this.element.find(_this.selectors.page);
_this.pageItem = pages.find('li');
_this.pageItem.eq(_this.index).addClass(_this.activeClass);
if (_this.direction) {
pages.addClass('vertical');
} else {
pages.addClass('horizontal');
}
}
function _initEvent(_this) {
_this.element.on('click touchstart', _this.selectors.page + ' li', function() {
_this.index = $(this).index();
_scrollPage(_this);
});
_this.element.on('mousewheel DOMMouseScroll', function(e) {
if (!_this.canScroll) {
return;
}
var delta = -e.originalEvent.detail || -e.originalEvent.deltaY || e.originalEvent.wheelDelta;
if (delta > 0 && (_this.index && !_this.settings.loop || _this.settings.loop)) {
_this.prve();
} else if (delta < 0 && (_this.index < (_this.pagesCount - 1) && !_this.settings.loop || _this.settings.loop)) {
_this.next();
}
});
_this.element.on('touchstart', function(e) {
var startX = e.originalEvent.changedTouches[0].pageX,
startY = e.originalEvent.changedTouches[0].pageY;
_this.element.one('touchend', function(e) {
if (!_this.canScroll) {
return;
}
var endX = e.originalEvent.changedTouches[0].pageX,
endY = e.originalEvent.changedTouches[0].pageY,
changeY = endY - startY;
if (changeY > 50) {
_this.prve();
} else if (changeY < -50) {
_this.next();
}
});
e.preventDefault();
});
if (_this.settings.keyboard) {
$(window).on('keydown', function(e) {
var keyCode = e.keyCode;
if (keyCode === 37 || keyCode === 38) {
_this.prve();
} else if (keyCode === 39 || keyCode === 40) {
_this.next();
}
});
}
$(window).resize(function() {
var currentLength = _this.switchLength(),
offset = _this.settings.direction ? _this.section.eq(_this.index).offset().top : _this.section.eq(_this.index).offset().left;
if (Math.abs(offset) > currentLength / 2 && _this.index < (_this.pagesCount - 1)) {
_this.index++;
}
if (_this.index) {
_scrollPage(_this);
}
});
_this.sections.on('transitionend webkitTransitionEnd oTransitionEnd otransitionend', function() {
_this.canScroll = true;
if (_this.settings.callback && type(_this.settings.callback) === 'function') {
_this.settings.callback();
}
});
}
function _scrollPage(_this) {
var dest = _this.section.eq(_this.index).position();
if (!dest) {
return;
}
_this.canScroll = false;
if (_prefix) {
_this.sections.css(_prefix + 'transition', 'all ' + _this.settings.duration + 'ms ' + _this.settings.easing);
var translate = _this.direction ? 'translateY(-' + dest.top + 'px)' : 'translateX(-' + dest.left + 'px)';
_this.sections.css(_prefix + 'transform', translate);
} else {
var animateCss = _this.direction ? {
top: -dest.top
} : {
left: -dest.left
};
_this.sections.animate(animateCss, _this.settings.duration, function() {
_this.canScroll = true;
if (_this.settings.callback && type(_this.settings.callback) === 'function') {
_this.settings.callback();
}
});
}
if (_this.settings.pagination) {
_this.pageItem.eq(_this.index).addClass(_this.activeClass).siblings('li').removeClass(_this.activeClass);
}
}
return XSwitch;
})();
})(jQuery);
$(function() {
$('[data-XSwitch]').XSwitch();
})
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
overflow: hidden;
}
#container,
.sections,
.section {
position: relative;
height: 100%;
}
.section {
background-color: #000;
background-size: cover;
background-position: 50% 50%;
}
#section0 {
background-color: grey;
}
#section1 {
background-color: red;
}
#section2 {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div id="container" data-XSwitch>
<div class="sections">
<div class="section" id="section0">
Example Link
</div>
<div class="section" id="section1">
Example Link
</div>
<div class="section" id="section2">
Example Link
</div>
<div class="section" id="section3">
Example Link
</div>
</div>
</div>
So I've found an issue - just commented this code:
_this.element.on('touchstart', function (e) {
var startX = e.originalEvent.changedTouches[0].pageX,
startY = e.originalEvent.changedTouches[0].pageY;
_this.element.one('touchend', function (e) {
if (!_this.canScroll) {
return;
}
var endX = e.originalEvent.changedTouches[0].pageX,
endY = e.originalEvent.changedTouches[0].pageY,
changeY = endY - startY;
if (changeY > 50) {
_this.prve();
} else if (changeY < -50) {
_this.next();
}
});
/* e.preventDefault(); */
});

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.

oPaging is undefined with datatables and twitter-bootstrap

On a project, I use datatables 1.10.2 with, to have pagination with bootstrap style, this script :
$.extend($.fn.dataTableExt.oPagination, {
bootstrap: {
fnInit: function(oSettings, nPaging, fnDraw) {
var els, fnClickHandler, oLang;
oLang = oSettings.oLanguage.oPaginate;
fnClickHandler = function(e) {
e.preventDefault();
if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
return fnDraw(oSettings);
}
};
$(nPaging).addClass("pagination").append("<ul>" + "<li class=\"prev disabled\">← " + oLang.sPrevious + "</li>" + "<li class=\"next disabled\">" + oLang.sNext + " → </li>" + "</ul>");
els = $("a", nPaging);
$(els[0]).bind("click.DT", {
action: "previous"
}, fnClickHandler);
return $(els[1]).bind("click.DT", {
action: "next"
}, fnClickHandler);
},
fnUpdate: function(oSettings, fnDraw) {
var an, i, iEnd, iHalf, iListLength, iStart, ien, j, oPaging, sClass, _results;
oPaging = oSettings.oInstance.fnPagingInfo();
iListLength = 5;
an = oSettings.aanFeatures.p;
i = void 0;
ien = void 0;
j = void 0;
sClass = void 0;
iStart = void 0;
iEnd = void 0;
iHalf = Math.floor(iListLength / 2);
if (oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
} else if (oPaging.iPage <= iHalf) {
iStart = 1;
iEnd = iListLength;
} else if (oPaging.iPage >= (oPaging.iTotalPages - iHalf)) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
i = 0;
ien = an.length;
_results = [];
while (i < ien) {
$("li:gt(0)", an[i]).filter(":not(:last)").remove();
j = iStart;
while (j <= iEnd) {
sClass = (j === oPaging.iPage + 1 ? "class=\"active\"" : "");
$("<li " + sClass + ">" + j + "</li>").insertBefore($("li:last", an[i])[0]).bind("click", function(e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($("a", this).text(), 10) - 1) * oPaging.iLength;
return fnDraw(oSettings);
});
j++;
}
if (oPaging.iPage === 0) {
$("li:first", an[i]).addClass("disabled");
} else {
$("li:first", an[i]).removeClass("disabled");
}
if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) {
$("li:last", an[i]).addClass("disabled");
} else {
$("li:last", an[i]).removeClass("disabled");
}
_results.push(i++);
}
return _results;
}
}
});
if ($.fn.DataTable.TableTools) {
$.extend(true, $.fn.DataTable.TableTools.classes, {
container: "DTTT btn-group",
buttons: {
normal: "btn",
disabled: "disabled"
},
collection: {
container: "DTTT_dropdown dropdown-menu",
buttons: {
normal: "",
disabled: "disabled"
}
},
print: {
info: "DTTT_print_info modal"
},
select: {
row: "active"
}
});
$.extend(true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
collection: {
container: "ul",
button: "li",
liner: "a"
}
});
}
}).call(this);
It works when I have a single datatable but when I have multiple datatables it break at the line if (oPaging.iTotalPages < iListLength) {. I seen than oSettings.oInstance is null for all datatables expect the last one.
What can I do to make it working?
add the plugin below
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};

Where to place Mouse Enter and Mouse Leave in Javascript

I have the following script and am trying to add mouse enter and leave events on a slideshow such that when the mouse is over the image it won't switch to the next one, and once removed it continues.
I can get the slide to stop when the mouse is over but once the mouse is out the slideshow won't proceed.
I am unsure if these 2 lines are in the right place:
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
jQuery(function () {
jQuery('a').focus(function () {
this.blur();
});
SI.Files.stylizeAll();
slider.init();
});
---> var MOUSE_IN = false;
var slider = {
num: -1,
cur: 0,
cr: [],
al: null,
at: 10 * 1000, /* change 1000 to control speed*/
ar: true,
anim:'slide',
fade_speed:600,
init: function () {
if (!slider.data || !slider.data.length) return false;
var d = slider.data;
slider.num = d.length;
var pos = Math.floor(Math.random() * 1);
for (var i = 0; i < slider.num; i++) {
if(slider.anim == 'fade')
{
jQuery('#' + d[i].id).hide();
}
else{
jQuery('#' + d[i].id).css({
left: ((i - pos) * 1000)
});
}
jQuery('#slide-nav').append('<a id="slide-link-' + i + '" href="#" onclick="slider.slide(' + i + ');return false;" onfocus="this.blur();">' + (i + 1) + '</a>');
}
jQuery('img,div#slide-controls', jQuery('div#slide-holder')).fadeIn();
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
slider.text(d[pos]);
slider.on(pos);
if(slider.anim == 'fade')
{
slider.cur = -1;
slider.slide(0);
}
else{
slider.cur = pos;
window.setTimeout('slider.auto();', slider.at);
}
},
auto: function () {
if (!slider.ar) return false;
if(MOUSE_IN) return false;
var next = slider.cur + 1;
if (next >= slider.num) next = 0;
slider.slide(next);
},
slide: function (pos) {
if (pos < 0 || pos >= slider.num || pos == slider.cur) return;
window.clearTimeout(slider.al);
slider.al = window.setTimeout('slider.auto();', slider.at);
var d = slider.data;
if(slider.anim == 'fade')
{
for (var i = 0; i < slider.num; i++) {
if(i == slider.cur || i == pos) continue;
jQuery('#' + d[i].id).hide();
}
if(slider.cur != -1){
jQuery('#' + d[slider.cur].id).stop(false,true);
jQuery('#' + d[slider.cur].id).fadeOut(slider.fade_speed);
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
else
{
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
}
else
{
for (var i = 0; i < slider.num; i++)
jQuery('#' + d[i].id).stop().animate({
left: ((i - pos) * 1000)
},
1000, 'swing');
}
slider.on(pos);
slider.text(d[pos]);
slider.cur = pos;
},
on: function (pos) {
jQuery('#slide-nav a').removeClass('on');
jQuery('#slide-nav a#slide-link-' + pos).addClass('on');
},
text: function (di) {
slider.cr['a'] = di.client;
slider.cr['b'] = di.desc;
slider.ticker('#slide-client span', di.client, 0, 'a');
slider.ticker('#slide-desc', di.desc, 0, 'b');
},
ticker: function (el, text, pos, unique) {
if (slider.cr[unique] != text) return false;
ctext = text.substring(0, pos) + (pos % 2 ? '-' : '_');
jQuery(el).html(ctext);
if (pos == text.length) jQuery(el).html(text);
else window.setTimeout('slider.ticker("' + el + '","' + text + '",' + (pos + 1) + ',"' + unique + '");', 30);
}
};
if (!window.SI) {
var SI = {};
};
SI.Files = {
htmlClass: 'SI-FILES-STYLIZED',
fileClass: 'file',
wrapClass: 'cabinet',
fini: false,
able: false,
init: function () {
this.fini = true;
var ie = 0
if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) {
return;
}
this.able = true;
var html = document.getElementsByTagName('html')[0];
html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
},
stylize: function (elem) {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
elem.parentNode.file = elem;
elem.parentNode.onmousemove = function (e) {
if (typeof e == 'undefined') e = window.event;
if (typeof e.pageY == 'undefined' && typeof e.clientX == 'number' && document.documentElement) {
e.pageX = e.clientX + document.documentElement.scrollLeft;
e.pageY = e.clientY + document.documentElement.scrollTop;
};
var ox = oy = 0;
var elem = this;
if (elem.offsetParent) {
ox = elem.offsetLeft;
oy = elem.offsetTop;
while (elem = elem.offsetParent) {
ox += elem.offsetLeft;
oy += elem.offsetTop;
};
};
var x = e.pageX - ox;
var y = e.pageY - oy;
var w = this.file.offsetWidth;
var h = this.file.offsetHeight;
this.file.style.top = y - (h / 2) + 'px';
this.file.style.left = x - (w - 30) + 'px';
};
},
stylizeById: function (id) {
this.stylize(document.getElementById(id));
},
stylizeAll: function () {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1) this.stylize(input);
};
}
};
(function (jQuery) {
jQuery.fn.pngFix = function (settings) {
settings = jQuery.extend({
blankgif: 'blank.gif'
},
settings);
var ie55 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 5.5') != -1);
var ie6 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 6.0') != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
jQuery(this).each(function () {
var bgIMG = jQuery(this).css('background-image');
if (bgIMG.indexOf(".png") != -1) {
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='" + settings.sizingMethod + "')";
}
});
}
return jQuery;
};
})(jQuery);
jQuery(function () {
if (jQuery.browser.msie && jQuery.browser.version < 7) {
}
});
The position of both lines is fine, they just add an event handler to the mouse in/out event. The problem you experience is actually in tha auto function, if you note, at the end of the init function you have:
window.setTimeout('slider.auto();', slider.at)
This line makes a call to the auto function after a slider.at time (which is 10 seconds in your example), the auto function checks if MOUSE_IN is set to true, if it's not, then calls the slide function, then in the slide function you have another call to the auto function:
slider.al = window.setTimeout('slider.auto();', slider.at);
But once you set the MOUSE_IN variable to true the auto function simply returns and it stop the execution of further slide functions, to solve this, you may want to either handle the MOUSE_IN logic in the slide function, or before returning false in the auto function, call with a time out the auto function again.
Thought this would work but it doesnt, the mouseleave eventdoesnt seem to fire.
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
while(MOUSE_IN==true)
{
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
}

jQuery: How can I put two of these elements on the same page?

I am using the following script, but if I put more than 1 occurrence on the same page, it breaks. I am trying to get it to where I can put multiple carousels on the same page.
HTML:
<div class="carousel_outer">
<div class="portfolio-carousel horizontal">
<div class="carousel" id="carousel1">
<div class="carousel_container carousel1">
<ul class="portfolio-wrap carousel1">
<li><a class="gall_thumb" href="#" title="First Pic"><img src="#" alt="First Pic" /></a></li>
<li><a class="gall_thumb" href="#" title="Second Pic"><img src="#" alt="Second Pic" /></a></li>
</ul>
</div>
<a class="carousel_prev" href="#">Previous</a>
<a class="carousel_next" href="#">Next</a>
</div>
</div>
</div>
Javascript on the page:
$('.carousel').mycarousel({
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false
});
And the actual carousel javascript:
(function ($) {
$.fn.extend({
mycarousel: function (options) {
var defaults = {
delay: 150,
fade: 300,
slide: 500,
effect: "fade",
orientation: "horizontal",
captionFade: 150,
loop: false,
autoplay: true,
time: 3000
};
var options = $.extend(defaults, options);
return this.each(function () {
var o = options;
var carousel = this;
$carousel_container = $(carousel).find(".carousel_container");
$li = $(carousel).find(".carousel_container ul li");
var visible_width = parseInt($carousel_container.css("width"), 10);
var visible_height = parseInt($carousel_container.css("height"), 10);
var number_items = $li.size();
var item_width = parseInt($li.css("width"), 10);
var item_height = parseInt($li.css("height"), 10);
var item_marginRight = parseInt($li.css("marginRight"), 10);
var item_marginLeft = parseInt($li.css("marginLeft"), 10);
var item_marginTop = parseInt($li.css("marginTop"), 10);
var item_marginBottom = parseInt($li.css("marginBottom"), 10);
if (o.orientation == "horizontal") {
var visible_items = Math.ceil(visible_width / (item_width + item_marginRight + item_marginLeft));
} else {
var visible_items = Math.ceil(visible_height / (item_height + item_marginTop + item_marginBottom));
}
var slides = Math.ceil(number_items / visible_items);
$float_easing = "easeInOutQuart";
function set_item_classes_visibility() {
$li.each(function (index) {
var class_number = Math.floor((index + visible_items) / visible_items);
$(this).addClass("visible_" + class_number);
if (class_number == "1") {
$(this).css("display", "block");
$(this).find(".inner").css("display", "block");
} else {
$(this).css("display", "none");
$(this).find(".inner").css("display", "none");
}
});
}
set_item_classes_visibility();
function set_next_prev_classes() {
var visible_item_class = $(carousel).find(".carousel_container ul li:visible").attr("class");
var visible_id = visible_item_class.split("_");
if (!o.loop) {
if (visible_id[1] == "1") {
$(".carousel_prev").addClass("disable");
} else {
$(".carousel_prev").removeClass("disable");
}
if (visible_id[1] == slides) {
$(".carousel_next").addClass("disable");
} else {
$(".carousel_next").removeClass("disable");
}
}
}
set_next_prev_classes();
function set_item_position() {
$li.each(function () {
$(this).css("display", "none");
$(this).css("position", "absolute");
if (o.orientation == "horizontal") {
$(this).css("top", "0");
$(this).css("left", visible_width + parseInt($carousel_container.css("paddingLeft")) + parseInt($carousel_container.css("paddingRight")), 10);
} else {
if (o.orientation == "vertical") {
$(this).css("left", "0");
$(this).css("top", visible_height + parseInt($carousel_container.css("paddingTop")) + parseInt($carousel_container.css("paddingBottom")), 10);
}
}
});
$carousel_container.find("li.visible_1").each(function (index) {
$(this).css("display", "block");
if (o.orientation == "horizontal") {
var left_position = (index * (item_width + item_marginRight + item_marginLeft)) + parseInt($carousel_container.css("paddingLeft"), 10);
$(this).css("left", left_position);
} else {
if (o.orientation == "vertical") {
var top_position = (index * (item_height + item_marginTop + item_marginBottom)) + parseInt($carousel_container.css("paddingTop"), 10);
$(this).css("top", top_position);
}
}
});
}
if (o.effect == "slide") {
set_item_position();
}
function show_next_prev(method) {
function show_items_fade(id) {
var next_class_name = "visible_" + id;
$carousel_container.find("li." + next_class_name).css("display", "block");
$carousel_container.find("li." + next_class_name).each(function (index) {
var delay = (index) * o.delay;
if (method == "prev") {
var delay = ((visible_items - 1) - index) * o.delay;
}
var index_item = (index + 1);
$(this).find(".inner").delay(delay).fadeIn(o.fade, function () {
if (index_item == visible_items || id == slides) {
set_next_prev_classes();
}
});
});
}
function show_items_slide(id) {
var next_class_name = "visible_" + id;
$carousel_container.find("li." + next_class_name + " .inner").css("display", "block");
$carousel_container.find("li." + next_class_name).each(function (index) {
$(this).css("display", "block");
var delay = (index) * o.delay;
if (method == "prev") {
var delay = ((visible_items - 1) - index) * o.delay;
}
var index_item = (index + 1);
if (o.orientation == "horizontal") {
var left_position = (index * (item_width + item_marginRight + item_marginLeft)) + parseInt($carousel_container.css("paddingLeft"), 10);
$(this).delay(delay).animate({
left: left_position
}, o.slide, $float_easing, function () {
if (index_item == visible_items || id == slides) {
set_next_prev_classes();
}
});
} else {
if (o.orientation == "vertical") {
var top_position = (index * (item_height + item_marginTop + item_marginBottom)) + parseInt($carousel_container.css("paddingTop"), 10);
$(this).delay(delay).animate({
top: top_position
}, o.slide, $float_easing, function () {
if (index_item == visible_items || id == slides) {
set_next_prev_classes();
}
});
}
}
});
}
var visible_item_class = $carousel_container.find("li:visible").attr("class");
visible_id = visible_item_class.split("_");
var next_id = parseInt(visible_id[1], 10) + 1;
var prev_id = parseInt(visible_id[1], 10) - 1;
if (visible_id[1] == 1) {
prev_id = slides;
}
if (visible_id[1] == slides) {
next_id = 1;
}
switch (o.effect) {
case "fade":
$carousel_container.find("li:visible").each(function (index) {
var delay = (index) * o.delay;
var index_item = (index + 1);
var last_item = $carousel_container.find("li." + visible_item_class).size();
if (method == "prev") {
delay = ((visible_items - 1) - index) * o.delay;
last_item = 1;
}
$(this).find(".inner").delay(delay).fadeOut(o.fade, function () {
if (index_item == last_item) {
$("li." + visible_item_class).css("display", "none");
if (method == "next") {
show_items_fade(next_id);
} else {
if (method == "prev") {
show_items_fade(prev_id);
}
}
}
});
});
break;
case "slide":
$carousel_container.find("li.visible_" + prev_id).each(function (index) {
if (o.orientation == "horizontal") {
if (method == "next") {
var left_position = visible_width + parseInt($carousel_container.css("paddingLeft"), 10) + parseInt($carousel_container.css("paddingRight"), 10);
} else {
if (method == "prev") {
var left_position = "-" + item_width + "px";
}
}
$(this).css("left", left_position);
} else {
if (o.orientation == "vertical") {
if (method == "next") {
var top_position = visible_height + parseInt($carousel_container.css("paddingTop"), 10) + parseInt($carousel_container.css("paddingBottom"), 10);
} else {
if (method == "prev") {
var top_position = "-" + item_height + "px";
}
}
$(this).css("top", top_position);
}
}
});
$carousel_container.find("li." + visible_item_class).each(function (index) {
var delay = (index) * o.delay;
var zindex = index + 10;
var index_item = (index + 1);
var last_item = $carousel_container.find("li." + visible_item_class).size();
if (method == "prev") {
delay = ((visible_items - 1) - index) * o.delay;
zindex = ((visible_items - 1) - index) + 10;
last_item = 1;
}
$(this).css("z-index", zindex);
if (o.orientation == "horizontal") {
if (method == "next") {
var left_position = "-" + item_width;
} else {
if (method == "prev") {
var left_position = visible_width + parseInt($carousel_container.css("paddingLeft"), 10) + parseInt($carousel_container.css("paddingRight"), 10);
}
}
$(this).delay(delay).animate({
left: left_position
}, o.slide, $float_easing, function () {
if (index_item == last_item) {
$("li." + visible_item_class).css("display", "none");
if (method == "next") {
show_items_slide(next_id);
} else {
if (method == "prev") {
show_items_slide(prev_id);
}
}
}
});
} else {
if (o.orientation == "vertical") {
if (method == "next") {
var top_position = "-" + item_height;
} else {
if (method == "prev") {
var top_position = visible_height + parseInt($carousel_container.css("paddingTop"), 10) + parseInt($carousel_container.css("paddingBottom"), 10);
}
}
$(this).delay(delay).animate({
top: top_position
}, o.slide, $float_easing, function () {
if (index_item == last_item) {
$("li." + visible_item_class).css("display", "none");
if (method == "next") {
show_items_slide(next_id);
} else {
if (method == "prev") {
show_items_slide(prev_id);
}
}
}
});
}
}
});
break;
}
}
if (o.autoplay) {
var interval = setInterval(function () {
var visible_item_class = $(carousel).find(".carousel_container ul li:visible").attr("class");
var visible_id = visible_item_class.split("_");
if (!o.loop) {
if (visible_id[1] == slides) {
clearInterval(interval);
} else {
show_next_prev("next");
}
} else {
show_next_prev("next");
}
}, o.time);
}
$(carousel).find(".carousel_next").click(function () {
clearInterval(interval);
show_next_prev("next");
return (false);
});
$(carousel).find(".carousel_prev").click(function () {
clearInterval(interval);
show_next_prev("prev");
return (false);
});
$li.hover(function () {
clearInterval(interval);
$(this).find(".caption").fadeIn(o.captionFade);
}, function () {
$(this).find(".caption").fadeOut(o.captionFade);
});
});
}
});
})(jQuery);
I'm thinking if there is some way I can identify each carousel with an ID and the script only executes things within each ID it would work, but I can't figure out how to get it done.
EDIT: I am getting the following js console error when I click a next/prev button: visible_item_class is undefined
Give them each an unique ID and call them by that.
$('#carousel1').mycarousel({
theid: $(this).attr('id'),
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false
});
$('#carousel2').mycarousel({
theid: $(this).attr('id'),
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false
});
On a side note is the following line necessary:
theid: $(this).attr('id')
I don't see it used anywhere in the carousel code.
Based on the function set_next_prev_classes in the plugin, the problem is probably that your 'next' and 'previous' buttons share a common class. (The plugin shouldn't do things this way, but there it is anyway.)
The solution should be as simple as giving each carousel DISTINCT class names for their 'next' and 'previous' buttons -- this can be as simple as appending the numbers 1 and 2 to each. (And then tell the plugin author that this approach is causing problems.)
Two ways to fix the problem.
Change the carousel code to take id of the div used as carousel , and carousel controls.
Copy the carousel code two times.Replace ".carousel" with "#Id1" in first and "#Id2" in second.Then the controls will be "#Id1_next", "#Id1_prev".
This is kind of hacky but cant help it.

Categories