How do get the name and size OF image Javascript - javascript

How do get the name and size OF images? (Javascript) After stored in array Using FileReader object ?
In the example required size and the name of the image files only .
Thank you so much
$(document).ready(function() {
var storedFiles = [];
var srcc = "";
$('#file_input').on('change', function(e) {
storedFiles = [];
for (var i = 0; i < $(this).get(0).files.length; ++i) {
storedFiles.push($(this).get(0).files[i]);
}
});
function readFile(file, callback) {
var reader = new FileReader();
reader.onload = callback;
reader.readAsDataURL(file);
}
$(document).on('click', '#btn', function(e) {
$("#div_upload").empty();
var fLen = storedFiles.length;
$("#spaneaddfile").html(" count: " + storedFiles.length);
for (var i = 0; i < fLen; i++) {
var filnameonarry = storedFiles[i].name;
var filsizeonarry = Math.round((Math.abs(parseInt(storedFiles[i].size)) * 0.000000954) * 1000) / 1000;
filnameonarry = filnameonarry.toString().trim();
filnameonarry = filnameonarry.toLowerCase();
var chkename2 = parseInt(filnameonarry.length);
var chkename3 = parseInt(filnameonarry.length - 4);
var chkename4 = filnameonarry.substring(chkename3);
if (chkename4 == '.png' || chkename4 == '.gif' || chkename4 == '.jpg' || chkename4 == '.bmp' || chkename4 == 'jpeg') {
if (window.File && window.FileReader && window.FileList && window.Blob) {
readFile(storedFiles[i], function(e) {
var html = "<div><img class='selFile' src=\"" + e.target.result + "\" data-file='" + "name" + "' title='Click to remove'>" + "get name and size" + "<br clear=\"left\"/></div>";
$("#div_upload").append(html);
});
} else {
srcc = '../background_site/close.png';
handleFileSelect3(storedFiles[i], i);
}
} else if (chkename4 == '.zip') {
srcc = '../background_site/zip.png';
handleFileSelect3(storedFiles[i], i);
} else if (chkename4 == '.rar') {
srcc = '../background_site/rar.png';
handleFileSelect3(storedFiles[i], i);
} else if (chkename4 == '.pdf') {
srcc = '../background_site/pdf.png';
handleFileSelect3(storedFiles[i], i);
} else {
srcc = '../background_site/wring.png';
handleFileSelect3(storedFiles[i], i);
}
};
});
function handleFileSelect3(evt, nmber) {
var f = evt;
var i = nmber;
var filnameonarry2 = f.name;
var filsizeonarry2 = Math.round((Math.abs(parseInt(f.size)) * 0.000000954) * 1000) / 1000;
var html = "<div> <img class='selFile' id='img_" + i + "' src='" + srcc + "' alt=''> " + filnameonarry2 + " " + filsizeonarry2 + "<br clear=\"left\"/></div>";
$("#div_upload").append(html);
}
});
.selFile {
width: 200px;
height: 200px;
float: left;
margin-bottom: 10px;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input id="btn" name="btn" type="button" value="get view">
<input type="file" id="file_input" name="files[]" multiple />
<div id="div_upload"></div>
<div id="spaneaddfile" class="foo"></div>

Related

Javascript: How I make fileupload (not only image)?

I made a file uploader that handles images, but it doesn't work well with files.
For example: if I upload 3 xlsx/word or any files, these will have the same name for each.
My code is here:
<form>
<input id="files" type="file" multiple="multiple">
<div id="result"></div>
</form>
function handleFileSelect(event) {
if (window.File && window.FileList && window.FileReader) {
var files = Array.from(event.target.files);
var output = document.getElementById("result");
output.innerHTML = '';
console.log(files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
if(file.type.match('.php')){
alert('ERROR');
continue;
}
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.className = "col-6 col-sm-4 p-1";
if (file.type.match('image')) {
div.innerHTML = "<img src='" + picFile.result + "'" + "title='" + file.name + "'/>";
}else{
div.innerHTML = "<div class='upload-thumb'>" + file.name + "</div>";
}
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
} else {
console.log("Your browser does not support File API");
}
}
Link:
https://jsfiddle.net/laszlooo/7c1Lv5x2/
Thank You!
Problem you have is you have the infamous for loop bug. Where the reference to i updates as your loop executes. You can either use let instead of var or break out the part you read the file into a function so you do not have the issue.
function readFile(file, output) {
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.className = "col-6 col-sm-4 p-1";
if (file.type.match('image')) {
div.innerHTML = "<img src='" + picFile.result + "'" + "title='" + file.name + "'/>";
} else {
div.innerHTML = "<div class='upload-thumb'>" + file.name + "</div>";
}
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
function handleFileSelect(event) {
if (window.File && window.FileList && window.FileReader) {
var files = Array.from(event.target.files);
var output = document.getElementById("result");
output.innerHTML = '';
console.log(files);
for (var i = 0; i < files.length; i++) { // <-- where the problem begins
var file = files[i]; // <-- this is your problem with the reference
if (file.type.match('.php')) {
alert('ERROR');
continue;
}
readFile(file, output) // <-- using a function gets around the reference issue
}
} else {
console.log("Your browser does not support File API");
}
}
document.querySelector("input").addEventListener("change", handleFileSelect)
<form>
<input id="files" type="file" multiple="multiple">
<div id="result"></div>
</form>

How to get Image width and height from Multiples Files input?

I want to get each of images width and height from multiple input files in Javascript or JQuery. I search in google and tried many ways, but I can't found the way to do it.
Here is my code:
<input id="uploadBtn" type="file" class="upload" multiple="multiple" name="browsefile" style="display: none !important;" />
<input type="button" class="btn submit-btn" value="ファイル追加" onclick="document.getElementById('uploadBtn').click();" style="float: right;"/>
<input id="filename" type="hidden" />
Here is my Javascript:
<script>
document.getElementById("uploadBtn").onchange = function() {
document.getElementById("uploadFile").value = this.value;
};
document.getElementById('uploadBtn').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var files = $('#uploadBtn')[0].files;
for (var i = 0; i < files.length; i++) {
(function(i) {
var extension = filename.split('.').pop();
if (extension == 'pdf')
{
$("#upload_prev").append('<div><span><br><div class="col-md-10"><span class="uploadFiles">' + '' + files[i].name + '' + '</span><br><label class="filelink"></label></div><div class="col-md-2"><p class="close" style="font-size: 13pt;">削除</p><br></div></span></div>');
}
else if (extension == 'jpg' || extension == 'jpeg' || extension == 'png' || extension == 'gif')
{
$("#upload_prev").append('<div><span><br><div class="col-md-10"><span class="uploadFiles">' + '' + files[i].name + '' + '</span><br><label class="filelink"></label></div><div class="col-md-2"><p class="close" style="font-size: 13pt;">削除</p><br></div></span></div>');
}
else
{
$("#upload_prev").append('<div><span><br><div class="col-md-10"><span class="uploadFiles">' + files[i].name + '</a>' + '</span><br><label class="filelink"></label></div><div class="col-md-2"><p class="close" style="font-size: 13pt;">削除</p><br></div></span></div>');
}
$("#upload_prev a:contains(" + files[i].name + ")")
.on("click", function(e) {
e.preventDefault();
var extension = filename.split('.').pop();
if (!/(pdf)$/ig.test(extension))
{
$('#imgPreview').modal('show');
$("#imgPreviewLabel").text(files[i].name)
var close = $('#imgPreview').closest("div")
.find(".filelink");
close.append(
$('<img>', {
src: URL.createObjectURL(files[i])
}).width('100%').height('100%')
)
}
else if (extension == 'pdf')
{
$('#pdfPreview').modal('show');
$("#pdfPreviewLabel").text(files[i].name)
var close = $('#pdfPreview').closest("div")
.find(".filelink");
close.append(
$('<iframe>', {
src: URL.createObjectURL(files[i])
}).width('565px').height('400px')
)
}
})
$(".modal_close").on("click", function(e){
$("#filelink img").remove();
$("#filelink iframe").remove();
})
$('#imgPreview').on('hidden.bs.modal', function () {
$("#filelink img").remove();
$("#filelink iframe").remove();
})
$('#pdfPreview').on('hidden.bs.modal', function () {
$("#filelink img").remove();
$("#filelink iframe").remove();
})
})(i);
}
document.getElementById('filename').value = filename;
}
You can try to get image width and height for multiple uploaded image files with this:
var _URL = window.URL || window.webkitURL;
$("#uploadBtn").change(function(e) {
var file, img;
for(var i=0; i<this.files.length; i++){
if ((file = this.files[i])) {
img = new Image();
img.onload = function() {
alert("width:"+this.width + " " + "height:" + this.height);
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
}
});

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

remove specific file form multiple file input

I implemented a following HTML <input> multiple Attribute
<input type="file" name="R" id="someattachId" multiple="multiple" style='display:none' />
I'm trying to remove specific item in it using following code
$('#someattachId')[0].files[fileId].remove();
but it can't remove it.
No, We can make it removable.
I implemented this and it works definitely.
First you need to initialize this variables
var newImageObj = [];
var ImageNo = 0;
Then write this code on file input's change
$("#exampleInputFileProduct").change(function () {
var fileUpload = document.getElementById("exampleInputFileProduct");
//$("#mainImages").html('');
//$("#subImages").html('');
if (typeof (FileReader) != "undefined") {
//Here Check File Extension
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var j = 0;
var file = fileUpload.files[i];
var NewFile = fileUpload.files[i];
//Here Check File Size 1MB = 1000000 Bytes
if (file.size < 2048000) {
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
if ($("#mainImages").find(".item").attr("id") == "FirstSlider") {
$("#mainImages").html('');
$("#subImages").html('');
$("#subImages").append("<div class='item active'></div>");
}
if ($("#mainImages").find(".item").hasClass("active")) {
$("#mainImages").append("<div class='item " + ImageNo + "_CClass\'><i class='fa fa-times customIcon' onclick='RemoveImage(\"" + ImageNo + "_CClass\",\"" + fileUpload.files[j].name.toLowerCase() + "\")'></i><img class='CImage' src='" + e.target.result + "' alt='' /></div>");
} else {
$("#mainImages").append("<div class='item active " + ImageNo + "_CClass'><i class='fa fa-times customIcon' onclick='RemoveImage(\"" + ImageNo + "_CClass\",\"" + fileUpload.files[j].name.toLowerCase() + "\")'></i><img class='CImage' src='" + e.target.result + "' alt='' /></div>");
}
//if ($("#subImages").find(".item").length == 0) {
// $("#subImages").append("<div class='item active'></div>");
//} else {
if (($("#subImages").find(".item").find("div").length / 5) >= $("#subImages").find(".item").length) {
$("#subImages").append("<div class='item'></div>");
}
//}
var append = 0;
$.each($("#subImages").find(".item"), function (p, pelement) {
if (append == 0) {
if ($(pelement).find("div").length != 5) {
var newID = $(pelement).find("div").length;
newID = newID;
$(pelement).append("<div onclick='LoadImage(\"" + ImageNo + "_CClass\")' data-slide-to='" + newID + "' class='thumb " + ImageNo + "_CClass'> <img src='" + e.target.result + "' alt=''></div>");
append = append + 1;
}
}
})
j = j + 1;
ImageNo = ImageNo + 1;
}
newImageObj.push(file);
reader.readAsDataURL(file);
}
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
Then at last this 2 functions will help to do the rest
function LoadImage(objclass) {
$("#mainImages").find(".item").removeClass("active");
$("#mainImages").find("." + objclass + "").addClass("active");
}
function RemoveImage(objclass, ImageName) {
$.each(newImageObj, function (e, element) {
if ($(this)[0].name.toLowerCase().trim() == ImageName.trim()) {
newImageObj.pop(this);
}
});
$("#mainImages").find("." + objclass + "").remove();
$("#subImages").find(".item").find("." + objclass + "").remove();
if ($("#mainImages").find(".item").length == 0) {
$("#mainImages").append("<div class='item active'><i class='fa fa-times customIcon'></i><img class='CImage' src='/Content/img/DefaultProduct.gif' alt='' /></div>");
$("#subImages").append("<div class='item active'><div data-target='#carousel' data-slide-to='0' class='thumb'> <img src='/Content/img/DefaultProduct.gif' alt=''></div></div></div>");
} else {
$("#mainImages").find(".item").removeClass("active");
$("#mainImages").find(".item:first-child").addClass("active");
$("#subImages").find(".item").removeClass("active");
$("#subImages").find(".item:first-child").addClass("active");
}
}
At last when you submit your form than take the files from the array

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/

Categories

Resources