I don't have all that much experience with Prototype and I've been working with jQuery to get things working properly on our site found here. Today I've added a jQuery based script for session handling. The problem I'm having is that even though I've gotten so far today in terms of functionality, I can't seem to get the change event fired via jQuery.
I'm using the following code currently, but it isn't working properly (you can test it on the site.. as soon as you change the year using your mouse, the AJAX is triggered and a Make can be selected)...
var yearSelected = jQuery.jStorage.get("yearSelected");
console.log(yearSelected);
// Set the vars...
if ((jQuery("div.amfinder-horizontal td:nth-child(1) select").val() == "0")) {
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
jQuery("div.amfinder-horizontal td:nth-child(1) select").trigger('change');
console.log('Set the year!');
}
The following code is the Prototype script controlling this and I need to fire off the change event, and would love to do it via jQuery if at all possible.
var amFinder = new Class.create();
amFinder.prototype = {
initialize: function(containerId, ajaxUrl, loadingText, isNeedLast, autoSubmit)
{
this.containerId = containerId;
this.ajaxUrl = ajaxUrl;
this.autoSubmit = Number(autoSubmit);
this.loadingText = loadingText;
this.isNeedLast = Number(isNeedLast);
this.selects = new Array();
//possible bug if select order in the HTML will be different
$$('#' + this.containerId + ' select').each(function(select){
select.observe('change', this.onChange.bindAsEventListener(this));
this.selects[this.selects.length] = select;
}.bind(this));
},
onChange: function(event)
{
var select = Event.element(event);
var parentId = select.value;
var dropdownId = 0;
/* should load next element's options only if current is not the last one */
for (var i = 0; i < this.selects.length; i++){
if (this.selects[i].id == select.id && i != this.selects.length-1){
var selectToReload = this.selects[i + 1];
if (selectToReload){
dropdownId = selectToReload.id.substr(selectToReload.id.search('--') + 2);
}
break;
}
}
this.clearAllBelow(select);
if (0 != parentId && dropdownId){
var postData = 'dropdown_id=' + dropdownId + '&parent_id=' + parentId;
new Ajax.Request(this.ajaxUrl, {
method: 'post',
postBody : postData,
evalJSON : 'force',
onLoading: function(){
this.showLoading(selectToReload);
}.bind(this),
onSuccess: function(transport) {
if (transport.responseJSON){
this.clearSelectOptions(selectToReload);
var itemsFound = false;
transport.responseJSON.each(function(item){
itemsFound = true;
var option = document.createElement('option');
option.value = item.value;
option.text = item.label;
option.label = item.label;
$(selectToReload).appendChild(option);
});
if (itemsFound){
$(selectToReload).disabled = false;
}
}
}.bind(this)
});
}
},
isLast: function(select)
{
return (this.selects[this.selects.length-1].id == select.id);
},
isFirst: function(select)
{
return (this.selects[0].id == select.id);
},
clearSelectOptions: function(select)
{
$(select).descendants().each(function(option){
option.remove();
});
},
clearAllBelow: function(select)
{
var startClearing = false;
for (var i = 0; i < this.selects.length; i++){
if (startClearing){
this.clearSelectOptions(this.selects[i]);
$(this.selects[i]).disabled = true;
}
if (this.selects[i].id == select.id){
startClearing = true;
}
}
var type = (((this.isLast(select) && !this.isNeedLast) && select.value > 0) || ((this.isNeedLast) && ((select.value > 0) || (!this.isFirst(select))))) ? 'block' : 'none';
if ('block' == type && this.autoSubmit && this.isLast(select))
{
$$('#' + this.containerId + ' .amfinder-buttons button')[0].form.submit();
} else {
$$('#' + this.containerId + ' .amfinder-buttons')[0].style.display = type;
}
},
showLoading: function(selectToReload)
{
var option = document.createElement('option');
option.value = 0;
option.text = this.loadingText;
option.label = this.loadingText;
$(selectToReload).appendChild(option);
},
};
I had the same problem. Here is solution. When you create : amfinder-horizontal the html goes something like this
<div class="amfinder-horizontal" id="amfinder_5333ffb212b09Container">
...
</div>
Look at id element : amfinder_5333ffb212b09 Container, bold part is also the name of variable that is amfinder object (created from prototype). It's a random name. This is from the extension source :
<?php $finderId = 'amfinder_' . uniqid(); ?>
...
<script type="text/javascript">
var <?php echo $finderId ?> = new amFinder(
'<?php echo $finderId ?>Container',
'<?php echo $this->getAjaxUrl() ?>',
'<?php echo $this->__('Loading...')?>',
'<?php echo Mage::getStoreConfig('amfinder/general/partial_search')?>',
<?php echo intval(Mage::getStoreConfig('amfinder/general/auto_submit')) ?>
);
</script>
So on every page refresh there is different name. var <?php echo $finderId ?>
Steps :
// Find the name for amfinder object.
var objName = jQuery("div.amfinder-horizontal").attr('id').replace('Container','');
// set Value to that select - copied from your code
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
// call the change event of that object
var targetObj = {
target : jQuery("div.amfinder-horizontal td:nth-child(1) select")[0]
};
window[objName].onChange(targetObj);
Related
I'm trying to add an "onclick" event with their respective function from js JQuery to an interactive table td I'm doing in another .php file, the problem is not executed in the place where I want to do it but if the same instruction is executed correctly within an AJAX request a few lines below, will show you the code:
This instruction is giving me the problem:
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
And this, the function I want to run with the "onclick"
function agregar_pensum_etapa2(td,subject,level,stage){
$(document).ready(function(){
// Capture variables.
var id_periodo = $("#id_periodo").val();
var id_asignatura = subject;
var id_nivel = level;
var id_etapa = stage;
var id_mencion = null;
if (level> 3) {
id_mencion = 0;
}
// Modifiable column.
var tr = $(td).parent();
var index_td = $(td).index();
// First field
var valor_anterior = $(td).text();
$(td).html("<img src =" images / save_64.png 'width = '16' height = '16 '> & nbsp; & nbsp; & nbsp;' + '<input value = "' + valor_anterior + '" type = "text" style = "width: 40px; border: 1px solid #aaa;" onkeypress = "return soloNumeros (event);" maxlength = "2"> ');
$(td).removeAttr("onclick");
$(td).find("input").focus();
// Second field
var valor_anterior_cs = $(tr).find("td:eq("+(index_td+1)+")").text();
var checked_cs = "";
if (valor_anterior_cs === "X"){checked_cs = "checked"}
$ (tr) .find ("td: eq (" + (index_td + 1) + ")") html ("<input type = 'checkbox'" + checked_cs + ">").
// Third field
var valor_anterior_hum = $(tr).find("td:eq("+(index_td+2)+")").text();
var checked_hum = "";
if(valor_anterior_hum === "X") {checked_hum = "checked"}
$(tr).find("td:eq("+(index_td+2)+")").html("<input type = 'checkbox'"+checked_hum+">");
/ ************************************************* *********** /
$(td).find("img").click(function(){
var hora_asignatura = $(td).find("input").val();
var mencion_cs = "NO";
if($(tr).find("td:eq("+(index_td+1)+")").find("input").is ("checked")){mencion_cs = "YES";}
var mencion_hum = "NO";
if($(tr).find("td:eq("+(index_td+2)+")").find("input").is("checked")){mencion_hum = "YES";}
if(hora_asignatura === ""){
if(valor_anterior != ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+index_td+1)+")").text(valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text(valor_anterior_hum);
}else{
$(td).html("");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject +"','"+level+"','"+stage+"');");
}else if(hora_asignatura == "0"){
if(valor_anterior! = ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+(index_td+1)+")").text (valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text (valor_anterior_hum);
}else{
$(td).html("<img src =" images / diagonal.png 'height = '16' style = 'width: 15px ">");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject+"','"+level+ "','"+stage+"');");
}else{
$.ajax({
async: true,
cache: false,
dataType: "html"
type: 'POST'
url: "../Controlador/CtrlPensum.php"
data: {
id_periodo: id_periodo,
id_asignatura: id_asignatura,
id_nivel: id_nivel,
id_etapa: id_etapa,
hora_asignatura: hora_asignatura,
mencion_cs: mencion_cs,
mencion_hum: mencion_hum,
id_mencion: id_mencion,
record: "register"
},
success: function (response) {
//alert (response);
if($.trim(answer) === "1") {
$(td).html(hora_asignatura);
var marcar_cs_x = "";
if(mencion_cs === "SI"){marcar_cs_x = "X";}
var marcar_hum_x = "";
if(mencion_hum === "SI"){marcar_hum_x = "X";}
$(tr).find("td:eq("+(index_td+1)+")").html (marcar_cs_x).
$(tr).find("td:eq("+(index_td+2)+")").html (marcar_hum_x).
\\// --> HERE IT WORKS <-- \\//
$(td).attr("onclick", "agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
cargarTablaResumen ();
} Else {
alert ("Error SQL statement is not executed." + response);
}
//tr.fadeOut(500).fadeIn(500);
},
beforeSend: function () {}
Error: function (objXMLHttpRequest) {}
});
}
});
});
}
I try this:
$(td).click(function(){
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+ "','"+stage+"');");
});
And in the html it prints correctly but does not work, like he was not the "onclick" there. And the function if it works, I put the onclick to that function when I load the page and if it works, but when I click the td and give back to click to restore does not restore the onclick.
Instead of setting the onclick attribute, why not do use .click() again with closures? So your code would be something like...
$(td).click(function(){
var td = this;
$(td).click(function () {
agregar_pensum_etapa2(td,subject,level,stage);
});
});
Do you write
$(Document)
Instead of $(document) with small letter "d".
I use prettyPhoto version: 3.1.6 to display simple lightbox with thumbnail.
Normally title attribute appear inside the lightbox for the active/selected image.
My client ask for this change
http://i.stack.imgur.com/7932x.jpg
How I can accomplish this?
Here is a part of my code
<a rel="prettyPhoto[pp_gal]"href="1.jpg" title="Staring at the sun"><img src="2.jpg"></a>
try this jquery function. You may have to style it a little.
(function($)
{
$.fn.avia_activate_lightbox = function(variables)
{
var defaults =
{
autolinkElements: 'a[rel^="prettyPhoto"], a[rel^="lightbox"], a[href$=jpg], a[href$=png], a[href$=gif], a[href$=jpeg], a[href$=".mov"] , a[href$=".swf"], a[href$=".flv"] , a[href*="vimeo.com"] , a[href*="youtube.com"]'
};
var options = $.extend(defaults, variables);
var imagedefaults =
{
autolinkImages: 'img[title!=""]'
};
return this.each(function()
{
var elements = $(options.autolinkElements, this),
lastParent = "",
counter = 0;
var images = $(imagedefaults.autolinkImages, this),
imgcounter = 0;
var alltitlesalt = new Array();
var alltitles = new Array();
images.each(function()
{
if($(this).attr('alt') != undefined && $(this).attr('alt') !="")
{
alltitlesalt.push($(this).attr('alt'));
}
else
{
alltitlesalt.push("");
};
alltitles.push($(this).attr('title'));
});
elements.each(function()
{
var el = $(this),
parentPost = el.parents('.post-entry:eq(0)'),
group = 'auto_group';
if(parentPost.get(0) != lastParent)
{
lastParent = parentPost.get(0);
counter ++;
}
if((el.attr('rel') == undefined || el.attr('rel') == '') && !el.hasClass('noLightbox'))
{
el.attr('rel','lightbox');
el.attr('title',alltitles[imgcounter]);
el.attr('alt',alltitlesalt[imgcounter]);
imgcounter ++;
}
});
if($.fn.prettyPhoto)
elements.prettyPhoto({ "theme": 'premium_photo', 'slideshow': 5000 }); /* facebook /light_rounded / dark_rounded / light_square / dark_square */
});
};
})(jQuery);
Reference
Is there anyway i can unload a page that has been loaded inside an iframe? it likely removing the
windows and loading content from other pages into the div?
I am using iframe on my main screen to call a file left_nav.php
<iframe src='left_nav.php' name='left_nav' class="daemon" scrolling="auto" frameborder='0' height='100%' width="100%"></iframe>
In left_nav functions and methods to load content from other pages like main_title.php
Function created in left_nav.php file below
setEncounter(edate, eid, frname) {
if (eid == active_encounter) return;
if (!eid) edate = '<?php xl('None','e'); ?>';
var str = '<b>' + edate + '</b>';
setDivContent('current_encounter', str);
active_encounter = eid;
encounter_locked=isEncounterLocked(active_encounter);
reloadEncounter(frname);
syncRadios();
var encounter_block = $(parent.Title.document.getElementById('current_encounter_block'));
var encounter = $(parent.Title.document.getElementById('current_encounter'));
var estr = ' <b>' + edate + ' (' + eid + ')</b>';
encounter.html( estr );
encounter_block.show();
}
function loadCurrentEncounterFromTitle() {
top.restoreSession();
top.frames[ parent.left_nav.getEncounterTargetFrame('enc') ].location='../patient_file/encounter/encounter_top.php';
}
function getEncounterTargetFrame( name ) {
var bias = <?php echo $primary_docs[ 'enc' ][ 1 ]?>;
var f = document.forms[0];
var r = 'RTop';
if (f.cb_top.checked) {
if ( bias == 2 ) {
r = 'RTop';
}
}
return r;
}
This is a js script in left_nav to load loadFrame2
function loadFrame2(fname, frame, url) {
var usage = fname.substring(3);
if (active_pid == 0 && usage > '0') {
alert('<?php xl('You must first select or add a visitor.','e') ?>');
return false;
}
if (active_encounter == 0 && usage > '1') {
alert('<?php xl('You must first select or create an encounter.','e') ?>');
return false;
}
if (encounter_locked && usage > '1') {
alert('<?php echo xls('This encounter is locked. No new forms can be added.') ?>');
return false;
}
var f = document.forms[0];
top.restoreSession();
var i = url.indexOf('{PID}');
if (i >= 0) url = url.substring(0,i) + active_pid + url.substring(i+5);
if(f.sel_frame) {
var fi = f.sel_frame.selectedIndex;
if (fi == 1) frame = 'RTop'; else if (fi == 2) frame = 'RBot';
}
if (!f.cb_bot.checked) frame = 'RTop';
top.frames[frame].location = '<?php echo "$web_root/interface/" ?>' + url;
if (frame == 'RTop') topName = fname;
return false;
}
Funtions created in main_title.php file.
function toencounter(rawdata) {
document.getElementById('EncounterHistory').selectedIndex=0;
if(rawdata=='') {
return false;
} else if (rawdata=='New Encounter') {
top.window.parent.left_nav.loadFrame2('nen1','RBot','forms/newpatient/new.php? autoloaded=1&calenc=')
return true;
} else if (rawdata=='Past Encounter List') {
top.window.parent.left_nav.loadFrame2('pel1','RBot','patient_file/history/encounters.php')
return true;
}
var parts = rawdata.split("~");
var enc = parts[0];
var datestr = parts[1];
var f = top.window.parent.left_nav.document.forms[0];
frame = 'RBot';
if (!f.cb_bot.checked) {
frame = 'RTop';
}
parent.left_nav.setEncounter(datestr, enc, frame);
top.frames[frame].location.href = '../patient_file/encounter/encounter_top.php?set_encounter=' + enc;
}
In the last line of code where the new iframe source is set, you're using the href attribute instead of the src. Since iframe does not have an href attribute, that would explain the lack of results.
top.frames[frame].src = '../patient_file/encounter/encounter_top.php?set_encounter=' + enc;
Try changing to that and see if it works.
Thanks for checking this out. I've got this dynamic ddl that populates after I put a value (ie. "51") into the specific page's javascript. So different pages pull different lists based on the number value. Everything is working great, except IE 8 (rhyme +1). When I open in IE8, I just get a single drop down item that reads "Choose A Program First".
I did some research and noticed there was an article on here talking about .empty not being reliable with IE8, but I don't use it. Here's my working code:
Local code:
<script type="text/javascript" language="javascript">
<!--
$(document).ready(function () {
$('#ballform_program').val(51);
loadCampuses();
});
//-->
</script>
Referenced DDL functionality js:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- Populate Campus DDL -->
<script type="text/javascript" language="javascript">
<!--
$(document).ready(function () {
if (firstField("#ballform_campuslocation", "#ballform_program") == "#ballform_campuslocation") {
loadCampuses();
$('#ballform_campuslocation').change(loadPrograms);
} else if (firstField("#ballform_campuslocation", "#ballform_program") == "#ballform_program") {
loadPrograms();
$('#ballform_program').change(loadCampuses);
}
$('#ballform_searchterm').val(getSearch());
$('#ballform_url').val(location.href);
$('#ballform_referrer').val(document.referrer);
$('#ballform_useragent').val(navigator.userAgent);
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data) {
$('#ballform_ipaddress').val(data.ip);
});
});
function loadCampuses() {
var host = location.host;
var data;
if (firstField("#ballform_campuslocation", "#ballform_program") == "#ballform_campuslocation") {
data = liveballScriptlet(6, "json", "url=" + host + "&program=0");
clearProgram();
} else {
var programID = $('#ballform_program').val();
data = liveballScriptlet(6, "json", "url=" + host + "&program=" + programID);
}
var options = "<option value=''>Choose...</option>";
var optGroup = "";
var jsonString = $.parseJSON(data);
$.each(jsonString, function () {
var value = this['ID'];
var text = this['Name'];
var school = this['School'];
if (optGroup != school) {
if (optGroup != "") {
options += "</optgroup>";
}
optGroup = school;
options += "<optgroup label='" + optGroup + "'>";
}
options += "<option value='" + value + "'>" + text + "</option>";
});
$('#ballform_campuslocation').html(options);
}
function clearCampus() {
if ($('#ballform_campuslocation').length > 0) {
$('#ballform_campuslocation')
.find('option')
.remove()
.end()
.append('<option value="">Choose a Program First</option>');
$('#ballform_campuslocation')
.find('optgroup')
.remove()
.end();
}
}
function loadPrograms() {
var host = location.host;
var data;
if (firstField("#ballform_campuslocation", "#ballform_program") == "#ballform_program") {
data = liveballScriptlet(7, "json", "url=" + host + "&campus=0");
clearCampus();
} else {
var campusID = $('#ballform_campuslocation').val();
data = liveballScriptlet(7, "json", "url=" + host + "&campus=" + campusID);
}
var options = "<option value=''>Choose...</option>";
var optGroup = "";
var jsonString = $.parseJSON(data);
$.each(jsonString, function () {
var value = this['ID'];
var text = this['Name'];
var degree = this['Degree'];
if (optGroup != degree) {
if (optGroup != "") {
options += "</optgroup>";
}
optGroup = degree;
options += "<optgroup label='" + optGroup + "'>";
}
options += "<option value='" + value + "'>" + text + "</option>";
});
$('#ballform_program').html(options);
}
function clearProgram() {
if ($('#ballform_program').length > 0) {
$('#ballform_program')
.find('option')
.remove()
.end()
.append('<option value="">Choose a Campus First</option>');
$('#ballform_program')
.find('optgroup')
.remove()
.end();
}
}
function getSearch() {
var work = "", output = "";
var start = 0, length = 0;
work = document.referrer;
start = work.indexOf("q=") + 2;
work = work.substring(start);
length = work.indexOf("&");
if (length == -1) {
output = work;
} else {
output = work.substring(0, length);
}
return output;
}
function firstField(object1, object2) {
var o1Exists, o1, o1Pos;
var o2Exists, o2, o2Pos;
var value = "";
//check for existence
o1Exists = ($(object1).length);
o2Exists = ($(object2).length);
if (!o1Exists && !o2Exists) {
value = "";
} else if (o1Exists && !o2Exists) {
value = object1;
} else if (!o1Exists && o2Exists) {
value = object2;
} else {
try {
o1 = $(object1);
o2 = $(object2);
o1Pos = o1.position();
o2Pos = o2.position();
if (o1Pos.top < o2Pos.top) {
value = object1;
} else {
value = object2;
}
} catch (err) {
value = object1;
alert(err);
}
}
return value;
}
//-->
</script>
Anyone have a fix possibility here that doesn't involve rewriting the entire "working" script? Thank you so much!
#epascarello pointed out in the comments that I could try swapping:
$('#ballform_campuslocation').html(options);
with:
$('#ballform_campuslocation').append(options);
and, for this scenario, it worked! Thanks again.
I was using the code from Kejun's Blog .
I want to parse a .lrc (which is basically a lyrics file) so as to get the time variable as well as the string(read lyrics) . I tried out this code and could not seem to get the output .
<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "a.txt",
dataType: "text",
success: function (data) {
parseLyric(data);
}
});
});
var _current_lyric = new Array();
function convertLRCLyric(inf) {
inf += "n";
var lyric = inf.match(/([(d{2}:d{2}(.d{1,2}){0,1})]){1,}W*n|([(d{2}:d{2}:d{2}(.d{1,2}){0,1})]){1,}W*n/ig);
var l_s = '',
l_tt, l_ww, l_i, l_ii;
if (!lyric || !lyric.length) {
return;
}
for (l_i = 0; l_i < lyric.length; l_i++) {
l_tt = lyric[l_i].match(/([d{2}:d{2}(.d{1,2}){0,1}])|([d{2}:d{2}:d{2}(.d{1,2}){0,1}])/ig);
l_ww = lyric[l_i].replace(/[S+]/ig, '').replace(/n{1,}/ig, '');
for (l_ii = 0; l_ii < l_tt.length; l_ii++) {
l_tt[l_ii] = l_tt[l_ii].replace(/[/,'').replace(/]/, '');
if (l_tt[l_ii].search(/d{2}:d{2}:d{2}.d{2}/g) >= 0) {
_current_lyric[l_tt[l_ii].substring(0, l_tt[l_ii].length - 1)] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}:d{2}.d{1}/g) >= 0) {
_current_lyric[l_tt[l_ii]] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}:d{2}/g) >= 0) {
_current_lyric[l_tt[l_ii] + ".0"] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}.d{2}/g) >= 0) {
_current_lyric["00:" + l_tt[l_ii].substring(0, l_tt[l_ii].length - 1)] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}.d{1}/g) >= 0) {
_current_lyric["00:" + l_tt[l_ii]] = l_ww;
} else if (l_tt[l_ii].search(/d{2}:d{2}/g) >= 0) {
_current_lyric["00:" + l_tt[l_ii] + ".0"] = l_ww;
}
}
}
}
function parseLyric(allText) {
_current_lyric = [];
convertLRCLyric(allText);
var ly = "";
for (var time in _current_lyric) {
ly += time + "--" + _current_lyric[time] + "n";
}
alert(ly);
}
</script>
</head>
<body>
</body>
</html>
But i keep getting a blank alert . Any help would be great . Thanks in advance .
Answer :
Ok so i built my own parser ,Here is the code
var contents = " " ;
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i = 0, f; f = files[i]; i++) {
var r = new FileReader();
r.onload = (function (f) {
return function (e) {
contents = e.target.result;
processData(contents);
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
var allTextLines = " ";
var lyrics = [];
var tim = [] ;
var line = " ";
// parsing the Lyrics
function processData(allText) { // This will only divide with respect to new lines
allTextLines = allText.split(/\r\n|\n/);
next();
}
function next()
{
for (i=0;i<allTextLines.length;i++)
{
if (allTextLines[i].search(/^(\[)(\d*)(:)(.*)(\])(.*)/i)>=0 )// any line without the prescribed format wont enter this loop
{
line = allTextLines[i].match(/^(\[)(\d*)(:)(.*)(\])(.*)/i);
tim[i] = (parseInt(line[2])*60)+ parseInt(line[4]); // will give seconds
lyrics[i]= line[6] ;//will give lyrics
}
}
}
Code php : with format
public function get_lrc_song($song) {
$lyrics_file = $song ['lyrics_file'];
$json = curlClass::getInstance ( true )->fetchURL ( $lyrics_file );
$content = explode ( "\n", $json );
$regix = "$\][^>]+$";
$result = "";
foreach ( $content as $item ) {
$isHas = preg_match ( $regix, $item, $data );
$dt = str_replace ( "]", "", $data[0] );
if ($dt != ""){
$result .= $dt . "\n";
}
}
echo $result;
}
I've made an plugin related to this which you can find here
There is an tutorial on how to use this and also i think this is most probably the simplest one I've seen while researching about this topic.
there is another lrc-parser for this purpose, I've tried it but, it lack some features like playing on command and other necessary features.
So i made them all
the code looks like this:
//view the tutorial of this usage on https://multimentality.000webhostapp.com/others
var lyricPlayer = {
"set_divval":function(){var all_lyrics = "";var mose;if(lyricPlayer.Mode=="Long"){mose="block"}else if(lyricPlayer.Mode=="Line"){mose="none"}else{alert("mode property: undefined value. lyricPlayer.Mode has two values 'Long' and 'Line'");mose="block"}for(let y=lyricPlayer.countt;y<lyricPlayer.lyrics.length;y++){all_lyrics+=`<span id='lyricsItem_${lyricPlayer.tim[y]}' class='lyricsItem_class' style='display:${mose};'>${lyricPlayer.lyrics[y]}</span>`;lyricPlayer.tmp_count=lyricPlayer.countt;lyricPlayer.main_dict[lyricPlayer.tim[y]]=lyricPlayer.tmp_count;lyricPlayer.tmp_count++;}document.getElementById('lyrics_playerMain').innerHTML=all_lyrics;},
"processData":function(allText){lyricPlayer.allTextLines = allText.split(/\r\n|\n/);lyricPlayer.next();},
"next":function()
{for (i=0;i<lyricPlayer.allTextLines.length;i++){if (lyricPlayer.allTextLines[i].search(/^(\[)(\d*)(:)(.*)(\])(.*)/i)>=0 ){lyricPlayer.line = lyricPlayer.allTextLines[i].match(/^(\[)(\d*)(:)(.*)(\])(.*)/i);lyricPlayer.tim[i] = (parseInt(lyricPlayer.line[2])*60)+ parseInt(lyricPlayer.line[4]);lyricPlayer.lyrics[i]= lyricPlayer.line[6] ;}else{lyricPlayer.countt++;}}lyricPlayer.set_divval();},
"set_scview":function(id){if(lyricPlayer.Mode=="Long"){var classes = document.getElementsByClassName("lyricsItem_class");for(let u=0;u<classes.length;u++){classes[u].style.color=lyricPlayer.Tcolor;}document.getElementById(`lyricsItem_${id}`).style.color=lyricPlayer.Scolor;var element = document.getElementById(`lyricsItem_${id}`);element.scrollIntoView({behavior: 'smooth',block: 'start'});}if(lyricPlayer.Mode=="Line"){var classes = document.getElementsByClassName("lyricsItem_class");
for(let u=0;u<classes.length;u++){
classes[u].style.display="none";
classes[u].style.color=lyricPlayer.Tcolor;}document.getElementById(`lyricsItem_${id}`).style.color=lyricPlayer.Scolor;document.getElementById(`lyricsItem_${id}`).style.display="block";}},
"change_lrc":function(elem){var time = parseInt(elem.currentTime);if(lyricPlayer.main_dict[time]!=undefined){lyricPlayer.set_scview(time)}},
"allTextLines":"",
"lyrics":[],
"tim":[],
"main_dict":{},
"h_lyrics":"",
"countt":0,
"Scolor":"white",
"line":"",
"tmp_count":0,
"Mode":"Long",
"Tcolor":document.getElementById("lyrics_playerMain").style.color,
"setLyrics":function(val){lyricPlayer.h_lyrics=val;lyricPlayer.main_dict={};lyricPlayer.countt=0;lyricPlayer.tim=[];lyricPlayer.lyrics=[];lyricPlayer.allTextLines="";lyricPlayer.processData(lyricPlayer.h_lyrics);lyricPlayer.tmp_count=lyricPlayer.countt;}
}
this works totally fine and perfect