Slider refuses to center photos, forces left justified - javascript

This is a really great slider but it has just one annoying fault. If I have different widths of images, the ones that are too small for the default width, are left justified. I've tried every which way to do it with the html/css but it's somewhere in the js I think. I even loaded the js after the images load and it still put it left justified even though they were centered for that split second before the js loaded. What seems to happen is, the js takes the smaller width image and makes it the full default width and adds whitespace to the right of it, essentially making it a full width image. I am just curious if this is customizable so that the photo is centered and whitespace is added on either side.
Any thoughts are appreciated, thanks for taking a look.
(function ($) {
var params = new Array;
var order = new Array;
var images = new Array;
var links = new Array;
var linksTarget = new Array;
var titles = new Array;
var interval = new Array;
var imagePos = new Array;
var appInterval = new Array;
var squarePos = new Array;
var reverse = new Array;
$.fn.coinslider = $.fn.CoinSlider = function (options) {
init = function (el) {
order[el.id] = new Array();
images[el.id] = new Array();
links[el.id] = new Array();
linksTarget[el.id] = new Array();
titles[el.id] = new Array();
imagePos[el.id] = 0;
squarePos[el.id] = 0;
reverse[el.id] = 1;
params[el.id] = $.extend({}, $.fn.coinslider.defaults, options);
$.each($('#' + el.id + ' img'), function (i, item) {
images[el.id][i] = $(item).attr('src');
links[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('href') : '';
linksTarget[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('target') : '';
titles[el.id][i] = $(item).next().is('span') ? $(item).next().html() : '';
$(item).hide();
$(item).next().hide();
});
$(el).css({
'background-image': 'url(' + images[el.id][0] + ')',
'width': params[el.id].width,
'height': params[el.id].height,
'position': 'relative',
'background-position': 'top left'
}).wrap("<div class='coin-slider' id='coin-slider-" + el.id + "' />");
$('#' + el.id).append("<div class='cs-title' id='cs-title-" + el.id + "' style='position: absolute; bottom:0; left: 0; z-index: 1000;'></div>");
$.setFields(el);
if (params[el.id].navigation) $.setNavigation(el);
$.transition(el, 0);
$.transitionCall(el);
}
$.setFields = function (el) {
tWidth = sWidth = parseInt(params[el.id].width / params[el.id].spw);
tHeight = sHeight = parseInt(params[el.id].height / params[el.id].sph);
counter = sLeft = sTop = 0;
tgapx = gapx = params[el.id].width - params[el.id].spw * sWidth;
tgapy = gapy = params[el.id].height - params[el.id].sph * sHeight;
for (i = 1; i <= params[el.id].sph; i++) {
gapx = tgapx;
if (gapy > 0) {
gapy--;
sHeight = tHeight + 1;
} else {
sHeight = tHeight;
}
for (j = 1; j <= params[el.id].spw; j++) {
if (gapx > 0) {
gapx--;
sWidth = tWidth + 1;
} else {
sWidth = tWidth;
}
order[el.id][counter] = i + '' + j;
counter++;
if (params[el.id].links) $('#' + el.id).append("<a href='" + links[el.id][0] + "' class='cs-" + el.id + "' id='cs-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></a>");
else $('#' + el.id).append("<div class='cs-" + el.id + "' id='cs-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></div>");
$("#cs-" + el.id + i + j).css({
'background-position': -sLeft + 'px ' + (-sTop + 'px'),
'left': sLeft,
'top': sTop
});
sLeft += sWidth;
}
sTop += sHeight;
sLeft = 0;
}
$('.cs-' + el.id).mouseover(function () {
$('#cs-navigation-' + el.id).show();
});
$('.cs-' + el.id).mouseout(function () {
$('#cs-navigation-' + el.id).hide();
});
$('#cs-title-' + el.id).mouseover(function () {
$('#cs-navigation-' + el.id).show();
});
$('#cs-title-' + el.id).mouseout(function () {
$('#cs-navigation-' + el.id).hide();
});
if (params[el.id].hoverPause) {
$('.cs-' + el.id).mouseover(function () {
params[el.id].pause = true;
});
$('.cs-' + el.id).mouseout(function () {
params[el.id].pause = false;
});
$('#cs-title-' + el.id).mouseover(function () {
params[el.id].pause = true;
});
$('#cs-title-' + el.id).mouseout(function () {
params[el.id].pause = false;
});
}
};
$.transitionCall = function (el) {
clearInterval(interval[el.id]);
delay = params[el.id].delay + params[el.id].spw * params[el.id].sph * params[el.id].sDelay;
interval[el.id] = setInterval(function () {
$.transition(el)
}, delay);
}
$.transition = function (el, direction) {
if (params[el.id].pause == true) return;
$.effect(el);
squarePos[el.id] = 0;
appInterval[el.id] = setInterval(function () {
$.appereance(el, order[el.id][squarePos[el.id]])
}, params[el.id].sDelay);
$(el).css({
'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')'
});
if (typeof (direction) == "undefined") imagePos[el.id]++;
else if (direction == 'prev') imagePos[el.id]--;
else imagePos[el.id] = direction;
if (imagePos[el.id] == images[el.id].length) {
imagePos[el.id] = 0;
}
if (imagePos[el.id] == -1) {
imagePos[el.id] = images[el.id].length - 1;
}
$('.cs-button-' + el.id).removeClass('cs-active');
$('#cs-button-' + el.id + "-" + (imagePos[el.id] + 1)).addClass('cs-active');
if (titles[el.id][imagePos[el.id]]) {
$('#cs-title-' + el.id).css({
'opacity': 0
}).animate({
'opacity': params[el.id].opacity
}, params[el.id].titleSpeed);
$('#cs-title-' + el.id).html(titles[el.id][imagePos[el.id]]);
} else {
$('#cs-title-' + el.id).css('opacity', 0);
}
};
$.appereance = function (el, sid) {
$('.cs-' + el.id).attr('href', links[el.id][imagePos[el.id]]).attr('target', linksTarget[el.id][imagePos[el.id]]);
if (squarePos[el.id] == params[el.id].spw * params[el.id].sph) {
clearInterval(appInterval[el.id]);
return;
}
$('#cs-' + el.id + sid).css({
opacity: 0,
'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')',
'background-repeat': 'no-repeat',
'background-color': '#fff',
});
$('#cs-' + el.id + sid).animate({
opacity: 1
}, 300);
squarePos[el.id]++;
};
$.setNavigation = function (el) {
$(el).append("<div id='cs-navigation-" + el.id + "'></div>");
$('#cs-navigation-' + el.id).hide();
$('#cs-navigation-' + el.id).append("<a href='#' id='cs-prev-" + el.id + "' class='cs-prev'></a>");
$('#cs-navigation-' + el.id).append("<a href='#' id='cs-next-" + el.id + "' class='cs-next'></a>");
$('#cs-prev-' + el.id).css({
'position': 'absolute',
'top': 0,
'left': 0,
'z-index': 1001,
'line-height': '30px',
'opacity': params[el.id].opacity
}).click(function (e) {
e.preventDefault();
$.transition(el, 'prev');
$.transitionCall(el);
}).mouseover(function () {
$('#cs-navigation-' + el.id).show()
});
$('#cs-next-' + el.id).css({
'position': 'absolute',
'top': 0,
'right': 0,
'z-index': 1001,
'line-height': '30px',
'opacity': params[el.id].opacity
}).click(function (e) {
e.preventDefault();
$.transition(el);
$.transitionCall(el);
}).mouseover(function () {
$('#cs-navigation-' + el.id).show()
});
$("<div id='cs-buttons-" + el.id + "' class='cs-buttons'></div>").appendTo($('#coin-slider-' + el.id));
for (k = 1; k < images[el.id].length + 1; k++) {
$('#cs-buttons-' + el.id).append("<a href='#' class='cs-button-" + el.id + "' id='cs-button-" + el.id + "-" + k + "'>" + k + "</a>");
}
$.each($('.cs-button-' + el.id), function (i, item) {
$(item).click(function (e) {
$('.cs-button-' + el.id).removeClass('cs-active');
$(this).addClass('cs-active');
e.preventDefault();
$.transition(el, i);
$.transitionCall(el);
})
});
$('#cs-navigation-' + el.id + ' a').mouseout(function () {
$('#cs-navigation-' + el.id).hide();
params[el.id].pause = false;
});
$("#cs-buttons-" + el.id) /*.css({'right':'50%','margin-left':-images[el.id].length*15/2-5,'position':'relative'})*/
;
}
$.effect = function (el) {
effA = ['random', 'swirl', 'rain', 'straight'];
if (params[el.id].effect == '') eff = effA[Math.floor(Math.random() * (effA.length))];
else eff = params[el.id].effect;
order[el.id] = new Array();
if (eff == 'random') {
counter = 0;
for (i = 1; i <= params[el.id].sph; i++) {
for (j = 1; j <= params[el.id].spw; j++) {
order[el.id][counter] = i + '' + j;
counter++;
}
}
$.random(order[el.id]);
}
if (eff == 'rain') {
$.rain(el);
}
if (eff == 'swirl') $.swirl(el);
if (eff == 'straight') $.straight(el);
reverse[el.id] *= -1;
if (reverse[el.id] > 0) {
order[el.id].reverse();
}
}
$.random = function (arr) {
var i = arr.length;
if (i == 0) return false;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var tempi = arr[i];
var tempj = arr[j];
arr[i] = tempj;
arr[j] = tempi;
}
}
$.swirl = function (el) {
var n = params[el.id].sph;
var m = params[el.id].spw;
var x = 1;
var y = 1;
var going = 0;
var num = 0;
var c = 0;
var dowhile = true;
while (dowhile) {
num = (going == 0 || going == 2) ? m : n;
for (i = 1; i <= num; i++) {
order[el.id][c] = x + '' + y;
c++;
if (i != num) {
switch (going) {
case 0:
y++;
break;
case 1:
x++;
break;
case 2:
y--;
break;
case 3:
x--;
break;
}
}
}
going = (going + 1) % 4;
switch (going) {
case 0:
m--;
y++;
break;
case 1:
n--;
x++;
break;
case 2:
m--;
y--;
break;
case 3:
n--;
x--;
break;
}
check = $.max(n, m) - $.min(n, m);
if (m <= check && n <= check) dowhile = false;
}
}
$.rain = function (el) {
var n = params[el.id].sph;
var m = params[el.id].spw;
var c = 0;
var to = to2 = from = 1;
var dowhile = true;
while (dowhile) {
for (i = from; i <= to; i++) {
order[el.id][c] = i + '' + parseInt(to2 - i + 1);
c++;
}
to2++;
if (to < n && to2 < m && n < m) {
to++;
}
if (to < n && n >= m) {
to++;
}
if (to2 > m) {
from++;
}
if (from > to) dowhile = false;
}
}
$.straight = function (el) {
counter = 0;
for (i = 1; i <= params[el.id].sph; i++) {
for (j = 1; j <= params[el.id].spw; j++) {
order[el.id][counter] = i + '' + j;
counter++;
}
}
}
$.min = function (n, m) {
if (n > m) return m;
else return n;
}
$.max = function (n, m) {
if (n < m) return m;
else return n;
}
this.each(function () {
init(this);
});
};
$.fn.coinslider.defaults = {
width: 828,
height: 200,
spw: 1,
sph: 1,
delay: 4000,
sDelay: 30,
opacity: 0.7,
titleSpeed: 500,
effect: '',
navigation: true,
links: false,
hoverPause: true
};
})(jQuery);

It seems to be taking the image source url and putting it into the background of the slider. I would first try changing
'background-position': 'top left'
to:
'background-position': 'center center'
... actually, the entire script seems geared towards tiling the images. I'd imagine that's the technique it uses to generate some of its cool effects. This line is where it's centering the current image within the tile defined by sph and spw.
'background-position': -sLeft + 'px ' + (-sTop + 'px'),
and if you use spw=1 and sph=1 you can center it by changing that to a fixed 'center center'.
I don't really care for this script in terms of general purpose, but it seems to have worked well for the person who wrote it.

this is my hacky solution
<script>
$(window).load(function() {
$('#coin-slider').coinslider({
opacity: 0.6,
effect: "rain",
hoverPause: true,
dely: 3000
});
// center coin slider
setTimeout(function(){
centerCS();
},500);
});
// center coin slider image
function centerCS(){
var w=$(".container").width(); // container of coin slider
var csw=$("#coin-slider").width();
var lpad=(w-csw)/2;
$("#coin-slider").css("margin-left",lpad+"px");
}
</script>

Related

How to process large jquery each loop without crashing browser(mainly firefox)

I made a javascript code to create some html element in parent iframe based on user selection from an iframe in a popup.
My code is given below.
The each loop may contain 50 to 150 iteration. Sometimes when I call function AddProcedures the Mozilla crashes during iteration, Is there any way to fix this issue or to reduce the browser load. I tried to put setTimeout after some code blocks but it didn't help.
I have also changed the for loop to jquery each, just to try if that helps.
var tot_codes = 0;
function doAddProcedure(thisVal,resolve){
var enc_id = $("#cpt_encounter").val();
var rowId = window.parent.$("[data-encounterBilled='"+ enc_id +"']").closest('tr').attr('id'); // table row ID
var recalc = parseInt(rowId.substring(rowId.indexOf('id-')+3));
var countval = $("#last_id").val();
//Load issue Fix
//Old code
//for (i = 0; i < document.cpt.elements.length; i++) {
//if (document.cpt.elements[i].type == "checkbox") {
//if (document.cpt.elements[i].checked == true) {
$('#cpt input:checkbox:checked').each(function(){
setTimeout(function() { }, 100);
var currentCodeMod = $(this).attr("data-codemod");
var currentCodeTypid = $(this).attr("data-codeTypeid");
if (currentCodeMod == null)
return;
tot_codes++;
var nextcntval = parseInt(countval) + 1;
var code_no = $(this).attr("id").replace("cpt_chkbx", "");
var Code = $("#codeVal" + code_no).val();
var just = $("#codeType" + code_no).val();
var categoryId = $("#codeType" + code_no).data("categoryid"); //Added to get category //Bug Fix
var Name = $("#cpttext" + code_no).val();
var codedisp = Code + ':' + Name;
var Modifier = '';
//if($("#modifier_setngs").val() == 1){
var Modifier1 = $("#modcpt1"+code_no).val() != '' ? $("#modcpt1"+code_no).val() + ":" : '';
var Modifier2 = $("#modcpt2"+code_no).val() != '' ? $("#modcpt2"+code_no).val() + ":" : '';
var Modifier3 = $("#modcpt3"+code_no).val() != '' ? $("#modcpt3"+code_no).val() + ":" : '';
var Modifier4 = $("#modcpt4"+code_no).val() != '' ? $("#modcpt4"+code_no).val() + ":" : '';
Modifier = Modifier1 + Modifier2 + Modifier3 + Modifier4;
//}
var codetableid = $("#code_tab_id" + code_no).val();
var j = countval; /* lineitem wise uniqid */
//var encounter = window.parent.$('#codetype-' + j).closest('tr.charge-entry-row').find('.expand-actions').attr('data-encounterid');
var encounter = enc_id;
var codeforarr = encounter + ':' + just + ':' + Code + '::' + Modifier;
window.parent.pushToArray(codeforarr);
var f = 0;
$(window.parent.$("#codetype-" + countval).parents().find('.inner-table .charge-entry-row')).each(function() {
//console.log($(this).find('.inputStringHidden').val() + '/' + codeforarr);
if ($(this).find('.inputStringHidden').val() == codeforarr) {
var exis_row_id = $(this).find('.inputStringHidden').attr('id').split('inputStringHidden-');
j = exis_row_id[1].toString();
f = 1;
$(this).find('.front_pay_codes_display').trigger('click');
}
});
if (f == 0) {
if (window.parent.document.getElementById('inputStringHidden-' + countval).value != '') {
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = parseInt(countval) + 1;
j = countval.toString();
}
window.parent.$("#add-" + countval).trigger("click");
window.parent.$("#codetype-" + (countval)).val(currentCodeTypid);
window.parent.$("#codetype-" + countval).trigger("change");
}
window.parent.document.getElementById('inputString' + j).value = codedisp;
window.parent.document.getElementById('category-' + j).value = categoryId; //Added to set category //Bug Fix
window.parent.document.getElementById('string_id' + j).value = Code;
window.parent.document.getElementById('string_value' + j).value = Name;
window.parent.document.getElementById('inputStringHidden-' + j).value = codeforarr;
window.parent.document.getElementById('codetableid-' + j).value = codetableid;
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.val-change-bit').val(1);
setTimeout(function() {}, 100);
window.parent.$("#suggestions" + j).hide();
window.parent.$("#inputString" + j).focus();
var uniqidHidden = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.uniqid-hidden').val();
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').text(Modifier);
//if($("#modifier_setngs").val() == 1){
if (f == 0) {
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').addClass('area-hide');
}else{
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').removeClass('area-hide');
}
window.parent.$('#modifiers' + uniqidHidden).val(Modifier);
arr = Modifier.split(':');
window.parent.$('#modifier-' + uniqidHidden + '-1').val(arr[0]);
window.parent.$('#modifier-' + uniqidHidden + '-2').val(arr[1]);
window.parent.$('#modifier-' + uniqidHidden + '-3').val(arr[2]);
window.parent.$('#modifier-' + uniqidHidden + '-4').val(arr[3]);
//}
var eclaimPlanActive = window.parent.$('#eclaimPlanActive').val();
var price = $("#cpt_price" + code_no).val();
var price_level = $("#pricelevelhidden" + code_no).val();
if (price == 0 || price == null)
price = 0;
window.parent.$('#price-' + j).val(price);
window.parent.$('#bill-pricelevel-' + j).val(price_level);
/** Charge Total **/
var chargeTotal = window.parent.$('#charge-total').text().replace(/[\s\,]/g, '').trim();
if (chargeTotal == '')
chargeTotal = parseFloat(0);
var tempChargeTotal = parseFloat(chargeTotal) + parseFloat(price);
window.parent.$('#charge-total span').html(tempChargeTotal);
/** End **/
var units = $("#cpt_units" + code_no).val(); //data[0]['units']
if (units == 0 || units == null)
units = 1;
window.parent.$('#qty-' + j).val(units);
var tax = 0;
var disc = 0;
setTimeout(function() { }, 100);
if (window.parent.$('#tax-' + j).length > 0)
tax = window.parent.$('#tax-' + j).val().replace(/[\s\,]/g, '');
if (window.parent.$('#discount-' + j).length > 0)
disc = window.parent.$('#discount-' + j).val().replace(/[\s\,]/g, '');
var amount = price * units;
amount = amount + ((amount * tax) / 100);
if (disc > 0) {
var p = price * units;
var dc = ((p * disc) / 100);
amount = amount - dc;
}
/** Discount Total **/
var disTotal = window.parent.$('#discount-total').text().replace(/[\s\,]/g, '').trim();
if (disTotal == '')
disTotal = parseFloat(0);
var tempDisTotal = parseFloat(disTotal) + parseFloat(dc);
if (isNaN(tempDisTotal) == true) {
tempDisTotal = '0.00';
}
window.parent.$('#discount-total').html(tempDisTotal);
/** End **/
if (!parseFloat(window.parent.$('#lineitempaid-' + j).val()))
window.parent.$('#lineitempaid-' + j).val('0.00');
window.parent.$('#total-' + j).val(amount);
window.parent.$('#remainder-' + j).val(amount);
window.parent.$('#hidremainder-' + j).val(amount);
//insurance and patient_share
if (eclaimPlanActive == '1') {
var codetableid = window.parent.$('#codetableid-' + j).val();
var parentRowVal = parseInt(window.parent.$('#codetableid-' + j).closest('tr').find('.row_value').attr('data-rowvalue')) - 1;
var insData1 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata1');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData1);
if (window.parent.$('#have-benefit').val() == '0') {
var insData2 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata2');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData2);
}
}
var passParams = '';
window.parent.calculate('qty-' + j, passParams);
//Updating the title
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.fi-searchitems').attr('data-original-title', codedisp);
if (f == 0) {
//Display DIv :: Relace with new values
var cloneLabel = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').clone();
//In Edit Mode
if (cloneLabel.find('.displaymode-elem').length > 0) {
var $max_length = 16;
var trucncateCode = Name;
if (trucncateCode.length > $max_length)
trucncateCode = trucncateCode.substring(0, $max_length) + '...';
cloneLabel.find('.front_pay_codetype').text(just + ":");
cloneLabel.find('.front_pay_code').text(trucncateCode);
cloneLabel.find('.displaymode-elem').removeClass('area-hide');
cloneLabel.removeClass('area-hide');
cloneLabel.find("input[name='code_type']").val(just).attr('id', 'code_type-' + j);
cloneLabel.find("input[name='string_id']").val(Code).attr('id', 'string_id-' + j);
cloneLabel.find("input[name='string_value']").val(Name);
var dataType = $("#inputString" + j).closest('tr.charge-entry-row').find('.data_type').val();
if (dataType == "lab") {
var lab = $("select[name='lab_type']").find('option:selected').val();
if (cloneLabel.find("input[name='lab_type']").length > 0) {
cloneLabel.find("input[name='lab_type']").val(lab);
} else {
cloneLabel.append('<input type="hidden" name="lab_type" class="lab_type" value="' + lab + '">');
}
} else {
cloneLabel.find("input[name='lab_type']").remove();
}
setTimeout(function() { }, 100);
//Making the view
cloneLabel.removeClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.front_pay_codes_editelem').removeClass('area-show').addClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').replaceWith(cloneLabel);
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_autosuggest').html('');
}
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = nextcntval.toString();
}
else {
window.parent.$("#suggestions" + j).hide();
countval = countval.toString();
}
setTimeout(function() { }, 150);
});
window.parent.reCalculatePlanEncounterWise(recalc);
resolve("Success!");
}
function doAddPromise(thisVal){
return new Promise(function(resolve){
doAddProcedure(thisVal,resolve);
});
}
function AddProcedures(thisval)
{
$('#procedureSaveButton').text('Processing....');
// $('.fa-spinner').removeClass('hide');
top.ShowAjaxLoader('Loading..');
setTimeout(function(){
}, 2000);
//top.ShowAjaxLoader('Loading..');
setTimeout(function(){
$.when(doAddPromise(thisval)).done(function(){
if (tot_codes > 0) {
window.parent.phFrntpayClosePopup();
top.notification('Successfully added the procedures.');
//top.HideAjaxLoader('Loading..');
top.HideAjaxLoader();
$('body').removeClass('modal-open');
} else {
top.notification('Please select atleast one procedure.');
$('#procedureSaveButton').text('Add Procedures');
//$('.fa-spinner').addClass('hide');
top.HideAjaxLoader();
}
});
}, 10);
}

How to fade out/in content in a slider

Fiddle: https://jsfiddle.net/fLfg7yqn/
JQuery:
$(function () {
$('.dvContentSlide').not(':eq(0)').addClass("dispNone");
$('.dvContentSlide:eq(0)').addClass("slideIsActive");
var g = parseInt($('div.slideIsActive').index()) + 1;
var u = $(".dvContentSlide").length;
$("#spCur").text("Current Index: " + g);
$("#spDVLen").text("SLIDE div length: " + $(".dvContentSlide").length);
for (var i = 0; i < u; i++)
$(".ulContentSliderNav").append('<li><span></span></li>');
$(".ulContentSliderNav :first-child a").addClass("ulContentSliderNavSel");
$(".cSlider").mouseover(function () {
clearInterval(po);
}).mouseout(function () {
po = setInterval(AutoSlide, 4000);
});
$(".ulContentSliderNav a").click(function (e) {
e.preventDefault();
$(this).parent().parent().find(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(this).addClass("ulContentSliderNavSel");
GoToTheSlide($(this).parent().index());
});
function GoToTheSlide(t) {
$('.dvContentSlide').addClass("dispNone");
$('.dvContentSlide').removeClass("slideIsActive");
$('.dvContentSlide:nth-child(' + ++t + ')').addClass("slideIsActive").removeClass("dispNone");
}
$("#aContentSliderNext").click(function () {
var k = $('div.slideIsActive').index() + 1;
if (k >= $(".dvContentSlide").length) {
k = 1;
$('.dvContentSlide').not(':eq(0)').addClass("dispNone").removeClass("slideIsActive");
$('.dvContentSlide:eq(0)').addClass("slideIsActive").removeClass("dispNone");
}
else {
$(".dvContentSlide:nth-child(" + k + ")").removeClass("slideIsActive").addClass("dispNone");
$(".dvContentSlide:nth-child(" + ++k + ")").removeClass("dispNone").addClass("slideIsActive");
}
$("#spCur").text("Current Index: " + k);
$(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(".ulContentSliderNav li:nth-child(" + k + ") a").addClass("ulContentSliderNavSel");
});
$("#aContentSliderPrev").click(function () {
var k = $('div.slideIsActive').index() + 1;
if (k <= 1) {
k = $(".dvContentSlide").length;
$('.dvContentSlide').not(':eq(' + k + ')').addClass("dispNone").removeClass("slideIsActive");
$('.dvContentSlide:nth-child(' + k + ')').addClass("slideIsActive").removeClass("dispNone");
}
else {
$(".dvContentSlide:nth-child(" + k + ")").removeClass("slideIsActive").addClass("dispNone");
$(".dvContentSlide:nth-child(" + --k + ")").removeClass("dispNone").addClass("slideIsActive");
}
$("#spCur").text("Current Index: " + k);
$(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(".ulContentSliderNav li:nth-child(" + k + ") a").addClass("ulContentSliderNavSel");
});
function AutoSlide() {
var k = $('div.slideIsActive').index() + 1;
console.log(k);
if (k >= $(".dvContentSlide").length) {
k = 1;
$('.dvContentSlide').not(':eq(0)').addClass("dispNone").removeClass("slideIsActive");
$('.dvContentSlide:eq(0)').addClass("slideIsActive").removeClass("dispNone");
}
else {
$(".dvContentSlide:nth-child(" + k + ")").removeClass("slideIsActive").addClass("dispNone");
$(".dvContentSlide:nth-child(" + ++k + ")").removeClass("dispNone").addClass("slideIsActive");
}
$("#spCur").text("Current Index: " + k);
$(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(".ulContentSliderNav li:nth-child(" + k + ") a").addClass("ulContentSliderNavSel");
}
var po = setInterval(AutoSlide, 4000);
});
Everything is working fine except how can I update the jquery/css so instead of showing the slide, it fades out the current slide and fades in the next slide with keeping the structure as is.
Have you tried fadeOut() fadeIn()? I didn't see it in your code, follow this link to see if it will meet your need.

Implementing Polymorphism in Javascript - how would this look?

I'm trying to make the jump to a more OOP style javascript approach, but I have just not gotten it right in javascript.
Take the following function as an example.
function positionalCSS(array, cs, lcs){
/* Define css for circle based on number of circles */
//Count array
var arrCount = array.length;
var T = [];
var L = [];
if(arrCount == 3){
T[0] ='15px';
L[0] = '240px';
T[1] = '345px';
L[1] = '440px';
T[2] = '345px';
L[2] = '40px';
}
if(arrCount == 4){
T[0] ='-135px';
L[0] = '90px';
T[1] = '-10px';
L[1] = '290px';
T[2] = '220px';
L[2] = '270px';
T[3] = '315px';
L[3] = '90px';
}
if(arrCount == 6){
T[0] ='-135px';
L[0] = '90px';
T[1] = '-10px';
L[1] = '290px';
T[2] = '220px';
L[2] = '270px';
T[3] = '315px';
L[3] = '90px';
T[4] = '210px';
L[4] = '-100px';
T[5] = '-10px';
L[5] = '-110px';
}
$.each(array, function(i) {
var num = parseInt(i);
// console.log('$("' + lcs + ' ' + cs + '.handle-' + num + '").first().children("div");');
$(lcs + ' ' + cs + '.handle-' + num).first().children('div').css({
'position': 'absolute',
'top': T[num],
'left': L[num]
});
});
}
It's pretty horrendous, I want to pass in an array, and depending on how many there are, organise the positions of the items based on this. SO I guess based on its size I would give it some properties? Where each TL represents a Top and Left position of an object?
I'd create an object where you can lookup premade arrays of objects holding your T/L values.
var counts = {
3: [
{t:'15px', l:'240px'},
{t:'345px', l:'440px'},
{t:'345px', l:'40px'}
],
4: {
// as above
},
5: {
// as above
}
};
And then use it in your function:
function positionalCSS(array, cs, lcs){
$.each(counts[array.length], function(i, obj) {
// console.log('$("' + lcs + ' ' + cs + '.handle-' + i + '").first().children("div");');
$(lcs + ' ' + cs + '.handle-' + i).first().children('div').css({
'position': 'absolute',
'top': obj.t,
'left': obj.l
});
});
}

Remove video navigation flickering from video gallery

i just build a video gallery
Here is the link to the video gallery
http://www.braddockinfotech.com/demo/dvnonline/vod1/
Two issues : :
1) While navigating through the gallery using up and down arrow keys there is kind of video jump or flicker.how to remove that
2)Unequal extra spaces before and after the first and last video in gallery.
Here is the html code
<body onkeydown="HandleKeyDown(event);">
<table cellpadding="0px" cellspacing="0px" border="0px" class="sitewidth">
<tr>
<td align="left" valign="top" style="width:800px;">
<div id='divVideoPlayer'></div>
</td>
<td align="center" style="width:140px;">
<div id="divPlaylistContainer">
<div id="playlistNavPrev">
<a id="imgNavPrev" onclick="MoveToDirection('Up');"><span class="arrow"> </span>
</a>
</div>
<div id="divPlaylist">
<!--playlist-->
<div id="spanSlider" style='top:0px; position:relative;'>
<ul id="ulSlider">
<?php $index=1 ; $firstVideoUrl='' ; $firstImageUrl='' ; $videoDetails=G
etVideoDetails(); echo "<script> var siteUrl = '".$siteUrl.
"' </script>"; while ($row=m ysql_fetch_array($videoDetails)) { echo
"<script>video[".$index. "]='";echo $row[3]. "';</script>"; echo "<script>image[".$index.
"]='";echo $row[2]. "';</script>"; //echo "<script>title[".$index. "]='";echo
$row[1]. "';</script>"; echo "<script>title[".$index. "]='";echo str_replace(
"'", "\'",$row[1]). "';</script>"; // 0 - id , 1 - Title , 2- ImageUrl, 3
- VideoUrl //echo $row[0].$row[1].$row[2].$row[3]. "<br/>"; //echo
"<li id='liButton_".$index. "'><a onclick=\"ShowVideo( '".$index."');\
"><img id='ImageButton_".$index. "' title='".$row[1]. "' alt='".$row[1]. "' src=".$siteUrl.
"timthumb/timthumb.php?src=".$row[2]. "&h=54&w=109&zc=1&a=c></a></li>"; $index++;
} ?>
</ul>
</div>
</div>
<div id="playlistNavNxt">
<a id="imgNavNext" onclick="MoveToDirection('Down');"><span class="arrow"> </span>
</a>
</div>
</div>
</td>
</table>
</body>
Here is the javascript code..
var video = new Array();
var image = new Array();
var title = new Array();
var noOfImagesCanShow = 6;
var selected = 1;
var slideNo = 1;
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, "");
};
function SetPlayList() {
var listHtml = '';
var lastIndex = slideNo * noOfImagesCanShow;
var firstIndex = (slideNo * noOfImagesCanShow) - (noOfImagesCanShow - 1);
var rowNo = 1;
for (var i = firstIndex; i <= lastIndex; i++) {
if (firstIndex >= 1 && lastIndex < title.length) {
listHtml += "<li id='liButton_" + rowNo + "'><a onclick=\"ShowVideo('" + i + "');\"><img id='ImageButton_" + i + "' title=\"" + title[i] + "\" alt='" + title[i] + "' src=" + siteUrl + "timthumb/timthumb.php?src=" + image[(i)] + "&h=54&w=109&zc=1&a=c></a></li>";
rowNo++;
}
}
document.getElementById('ulSlider').innerHTML = listHtml;
document.getElementById('liButton_1').tabIndex = 2;
document.getElementById('liButton_1').focus();
}
function ShowVideo(videoIndex) {
var streamToBeUsed = "";
var provideType = "";
if (video[videoIndex].trim().substring(0, 7) == "http://") {
streamToBeUsed = '';
provideType = "http";
} else {
streamToBeUsed = "rtmp://cp87191.edgefcs.net/ondemand/";
provideType = "rtmp";
}
var autostart = "true";
if (jwplayer("divVideoPlayer") != null) {
jwplayer("divVideoPlayer").stop();
}
jwplayer("divVideoPlayer").setup({
file: streamToBeUsed + video[videoIndex].trim(),
image: image[videoIndex],
icons: "true",
autostart: autostart,
screencolor: "black",
'width': '800',
'height': '510',
streamer: streamToBeUsed,
provider: provideType,
events: {
onBeforePlay: function () {
document.getElementById('liButton_' + videoIndex).tabIndex = '2';
document.getElementById('liButton_' + videoIndex).focus();
}
}
});
// clearing all style
var totalImages = noOfImagesCanShow;
for (var i = 1; i <= totalImages; i++) {
var imageId = (((slideNo * noOfImagesCanShow) - (noOfImagesCanShow)) + i).toString();
if (document.getElementById('liButton_' + i) != null && document.getElementById('ImageButton_' + imageId) != null) {
document.getElementById('liButton_' + i).className = 'inactiveli';
document.getElementById('ImageButton_' + imageId).className = 'inactive';
}
}
document.getElementById('liButton_' + videoIndex).className = 'activeli';
document.getElementById('ImageButton_' + (((slideNo - 1) * noOfImagesCanShow) + parseInt(videoIndex)).toString()).className = 'active';
SetButtonStatus(((slideNo - 1) * noOfImagesCanShow) + parseInt(videoIndex));
document.getElementById('liButton_' + videoIndex).tabIndex = '2';
document.getElementById('liButton_' + videoIndex).focus();
document.getElementById('divVideoPlayer').tabIndex = '-1';
}
function SetButtonStatus(imageIndex) {
if (imageIndex <= noOfImagesCanShow) {
document.getElementById('imgNavPrev').className = 'disable_up';
document.getElementById('imgNavPrev').tabIndex = '-1';
document.getElementById('imgNavNext').tabIndex = '3';
} else {
document.getElementById('imgNavPrev').className = 'enable_up';
document.getElementById('imgNavPrev').tabIndex = '1';
}
if (imageIndex > (image.length - noOfImagesCanShow)) {
document.getElementById('imgNavNext').className = 'disable_down';
document.getElementById('imgNavNext').tabIndex = '-1';
document.getElementById('imgNavPrev').tabIndex = '1';
} else {
document.getElementById('imgNavNext').className = 'enable_down';
document.getElementById('imgNavNext').tabIndex = '3';
}
}
function MoveToDirection(direction) {
if (direction == 'Down') {
if (document.getElementById('imgNavNext').className != 'disable_down') {
slideNo++;
SetButtonStatus(slideNo * noOfImagesCanShow);
SetPlayList();
var topEle = document.getElementById('liButton_1');
var nextSelImgId = topEle.getElementsByTagName("img")[0].getAttribute("id");
document.getElementById(nextSelImgId).className = 'active';
}
} else if (direction == 'Up') {
if (document.getElementById('imgNavPrev').className != 'disable_up') {
slideNo--;
SetButtonStatus(slideNo * noOfImagesCanShow);
SetPlayList();
var topEle = document.getElementById('liButton_6');
var nextSelImgId = topEle.getElementsByTagName("img")[0].getAttribute("id");
document.getElementById(nextSelImgId).className = 'active';
console.log('Setting active element ' + nextSelImgId);
document.getElementById('liButton_6').focus();
console.log('active element ' + document.activeElement.id);
}
}
}
function HandleKeyDown(ev) {
if (document.activeElement != null) {
var element = document.activeElement;
if (ev.keyCode == 13) {
/*User Pressed Enter, Handle If required*/
if (element.id == "imgNavNext" && element.className != "disable_down") {
MoveToDirection('Down');
} else if (element.id == "imgNavPrev" && element.className != "disable_up") {
MoveToDirection('Up');
} else if (element.id.indexOf("liButton_") > -1) {
var nameSections = element.id.split('_');
ShowVideo(nameSections[1]);
}
} else if (ev.keyCode == 40) {
/*User Pressed Down*/
console.log('Pressed Down');
console.log('Element Id is ' + element.id);
if (element.id.indexOf("liButton_") > -1) {
console.log('Entered liButton_ Checking....');
var nameSections = element.id.split('_');
var imgName = element.getElementsByTagName("img")[0].getAttribute("id");
var imgSection = imgName.split('_');
var nextImgToFocus = (parseInt(imgSection[1])) + 1;
var nextIndexToFocus = (parseInt(nameSections[1])) + 1;
if (document.getElementById("liButton_" + nextIndexToFocus) != null) {
document.getElementById("liButton_" + nextIndexToFocus).tabIndex = element.tabIndex;
element.tabIndex = "-1";
document.getElementById("ImageButton_" + nextImgToFocus).className = 'active';
document.getElementById("ImageButton_" + (nextImgToFocus - 1)).className = 'inactive';
document.getElementById("liButton_" + nextIndexToFocus).focus();
} else //need to focus in navNext
{
if (document.getElementById('imgNavNext').className != 'disable_down') {
console.log("Enetred need to focus navNext");
var topEle = document.getElementById('liButton_6');
var nextSelImgId = topEle.getElementsByTagName("img")[0].getAttribute("id");
document.getElementById(nextSelImgId).className = 'inactive';
document.getElementById('imgNavNext').focus();
}
}
} else {
if (element.id.indexOf("imgNavPrev") > -1) {
document.getElementById("liButton_1").focus();
}
}
} else if (ev.keyCode == 38) {
/*User Pressed Up Up*/
if (element.id.indexOf("liButton_") > -1) {
console.log('Up pressed ' + element.id);
var nameSections = element.id.split('_');
var imgName = element.getElementsByTagName("img")[0].getAttribute("id");
var imgSection = imgName.split('_');
var nextImgToFocus = (parseInt(imgSection[1])) - 1;
var nextIndexToFocus = (parseInt(nameSections[1])) - 1;
if (document.getElementById("liButton_" + nextIndexToFocus) != null) {
document.getElementById("liButton_" + nextIndexToFocus).tabIndex = element.tabIndex;
element.tabIndex = "-1";
document.getElementById("ImageButton_" + nextImgToFocus).className = 'active';
document.getElementById("ImageButton_" + (nextImgToFocus + 1)).className = 'inactive';
document.getElementById("liButton_" + nextIndexToFocus).focus();
} else //need to focus in navPrev
{
if (document.getElementById('imgNavPrev').className != 'disable_up') {
var topEle = document.getElementById('liButton_1');
var nextSelImgId = topEle.getElementsByTagName("img")[0].getAttribute("id");
document.getElementById(nextSelImgId).className = 'inactive';
document.getElementById('imgNavPrev').focus();
}
}
} else /* To handle up button from imgNavNext */
{
if (element.id.indexOf("imgNavNext") > -1) {
document.getElementById("liButton_6").focus();
}
}
}
}
}
The reason, I believe, the images flicker is because they aren't loaded until the button is clicked.
for (var i = firstIndex; i <= lastIndex; i++) {
if (firstIndex >= 1 && lastIndex < title.length) {
listHtml += "<li id='liButton_" + rowNo + "'><a onclick=\"ShowVideo('" + i + "');\"><img id='ImageButton_" + i + "' title=\"" + title[i] + "\" alt='" + title[i] + "' src=" + siteUrl + "timthumb/timthumb.php?src=" + image[(i)] + "&h=54&w=109&zc=1&a=c></a></li>";
rowNo++;
}
}
When the view is scrolled up or down, the list regenerates, and the images are loaded.
You can prevent the flicker if you preload the images.
You can do this by preloading all of the images at once or by loading the images while showing a "loading (please wait) graphic." Please see this http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Javascript Hanging UI on IE6/7

Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?

Categories

Resources