Code not accessing nextElementSibling correctly - javascript

I have a <div> in my HTML:
<div id="attempt_history"></div>
In my JavaScript I have code to dynamically create new elements (a <button> and a <pre>)and add to the <div>:
for(let i = 0; i < resultAtpmtList.length; i++) {
var attmptHistoryBut = document.createElement('button');
attmptHistoryBut.id = 'attmptHistoryBut' + i;
attmptHistoryBut.className = 'attmptHistoryBut_C';
attempt_history.appendChild(attmptHistoryBut);
if (resultAtpmtList[i][1] == 0) {
var success_output = "Failed Attempt";
document.getElementById('attmptHistoryBut' + i).style.background = "white";
document.getElementById('attmptHistoryBut' + i).style.width = "100%";
document.getElementById('attmptHistoryBut' + i).style.textAlign = "left";
document.getElementById('attmptHistoryBut' + i).style.color = "red";
} else {
var success_output = "Successful Attempt";
document.getElementById('attmptHistoryBut' + i).style.background = "white";
document.getElementById('attmptHistoryBut' + i).style.width = "100%";
document.getElementById('attmptHistoryBut' + i).style.textAlign = "left";
document.getElementById('attmptHistoryBut' + i).style.color = "green";
successful = 1;
}
var attmptHistoryPre = document.createElement('pre');
attmptHistoryPre.id = 'attmptHistoryPre' + i;
attmptHistoryPre.className = 'attmptHistoryPre_C';
attempt_history.appendChild(attmptHistoryPre);
document.getElementById('attmptHistoryBut' + i).style.fontSize = "20px";
document.getElementById('attmptHistoryBut' + i).innerHTML = "Attempt " + (i+1) + ": " + resultAtpmtList[i][2] + " " + success_output;
document.getElementById('attmptHistoryPre' + i).innerHTML = resultAtpmtList[i][0];
}
Then I also have the following JS code to make the 'next' <pre> collapsible (show/hide) when the preceding <button> element is clicked:
var coll = document.getElementsByClassName("attmptHistoryBut_C");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
However, the <pre> does not toggle on button click. The behaviour does not function.
What have I done wrong?

if (content.style.display === "block")
This will only catch elements with display:block; in their style="..." attribute (either on the original HTML or added by JS). Try reversing the logic
if (content.style.display === "none") {
content.style.display = null;
} else {
content.style.display = "none";
}

Related

Button Array seems to not be working

I have an exercise that I had to do for my class and was not sure why my button array does not work. The number of times I click the button does not equal to the exact number of times being clicked if that makes sense.
function changeDisplay(buttonClicked) {
if (currentButton == buttonClicked) {
return;
}
if (buttonClicked == "linear") {
buttonArray[0] = buttonArray[0] + 1;
document.getElementById('linear').innerHTML = " Linear = " + buttonArray[0];
document.getElementById('section1').style.float = 'none';
document.getElementById('section1').style.width = "100%";
document.getElementById('sidebar').style.float = 'none';
document.getElementById('section2').style.float = 'none';
currentButton = buttonClicked;
console.log("linear " + buttonArray[0]);
} else if (buttonClicked == "right") {
buttonArray[0] += 1;
document.getElementById('right').innerHTML = " Right Sidebar = " + buttonArray[0];
document.getElementById('section1').style.float = 'none';
document.getElementById('section1').style.width = "100%";
document.getElementById('sidebar').style.float = 'right';
document.getElementById('sidebar').style.width = "25%";
document.getElementById('section2').style.float = 'none';
currentButton = buttonClicked;
console.log("right " + buttonArray[1]);
} else if (buttonClicked == "center") {
buttonArray[0] += 1;
document.getElementById('center').innerHTML = " Center Sidebar = " + buttonArray[0];
document.getElementById('section1').style.float = 'left';
document.getElementById('section1').style.width = "30%";
document.getElementById('section1').style.marginRight = "25px";
document.getElementById('sidebar').style.float = 'left';
document.getElementById('sidebar').style.width = "25%";
document.getElementById('section2').style.float = 'none';
document.getElementById('section2').style.width = "100%";
currentButton = buttonClicked;
console.log("center " + buttonArray[2]);
} else if (buttonClicked == "left") {
buttonArray[0] += 1;
document.getElementById('left').innerHTML = " Left Sidebar = " + buttonArray[0];
document.getElementById('section1').style.float = 'none';
document.getElementById('section1').style.width = "100%";
document.getElementById('sidebar').style.float = 'left';
document.getElementById('sidebar').style.width = "25%";
document.getElementById('section2').style.float = 'none';
document.getElementById('section2').style.width = "100%";
currentButton = buttonClicked;
console.log("left " + buttonArray[3]);
}
}
</script>

Issue using addEventListener() in Javascript

I am making a battleships game, and I am currently working on placing your own boats. I want to be able to click, and one square on the grid to change color. I am adding event listeners to each tile through a nested for() loop, and getting each button to reference itself when the function is run.
The issue is, some of the tiles are changing color when I click on them, but others are not, and there is no pattern I can make out as to which change and which do not, as sometimes, I can click two or three times, and it will change color. The code is here. (I also added a color selector).
var x_client = 0;
var y_client = 0;
var battlefield_client = "";
for (y_client = 1; y_client < 11; y_client++) {
battlefield_client += "<tr>";
for (x_client = 1; x_client < 11; x_client++) {
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
}
battlefield_client += "</tr>";
}
$(document).ready(function() {
$("#tableGrid_client").html(battlefield_client); //loads table
for (y_client = 1; y_client < 11; y_client++) {
for (x_client = 1; x_client < 11; x_client++) {
boatStatusClient = document.getElementById('cell_client_' + x_client + "_" + y_client);
boatStatusClient.addEventListener("click", function(){boatGrid.placeBoat_client()});
}
}
document.getElementById("redButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("orangeButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("yellowButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("greenButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("blueButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("violetButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("brownButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("blackButton").addEventListener("click", function(){boatGrid.colorSelect()});
}); //This is for the color selector.
colorSelect : function() {
colorPick = event.target || event.srcElement;
colorPick = colorPick.id
console.log(colorPick);
if (colorPick == redButton) {
colorSelect = "red";
}
else if (colorPick == orangeButton) {
colorSelect = "orange";
}
else if (colorPick == yellowButton) {
colorSelect = "yellow";
}
else if (colorPick == greenButton) {
colorSelect = "green";
}
else if (colorPick == blueButton) {
colorSelect = "blue";
}
else if (colorPick == violetButton) {
colorSelect = "purple";
}
else if (colorPick == brownButton) {
colorSelect = "brown";
}
else if (colorPick == blackButton) {
colorSelect = "black";
}
console.log(colorSelect);
},
placeBoat_client : function() {
var demoColor = "orange"
var source_client = event.target.id;
console.log(source_client);
source_client.id = document.getElementById(source_client.id);
document.getElementById(source_client).style.backgroundColor = demoColor;
},
}
I have applied some fixes:
-Loops now use local variables to count iteration, so loop runs and uses its own variable. Next loop is not allowed to write over a variable in a different scope.
-You were adding anonymous functions were just function names were expected as
parameters. The second parameter inside an 'addEventListener' sets a call just
receiving function name, otherwise it is redundant.
-Changed a variable name to make it different from selectColor().
-Functions & variables on top of script, so are the first thing to be read.
-Small things like missing semicolons, extra commas, brackets, etc.
Here you go, hope it helps:
//var x_client = 0;
//var y_client = 0;
var battlefield_client = "";
var setColor='';
function colorSelect (){
colorPick = event.target || event.srcElement;
colorPick = colorPick.id;
console.log(colorPick);
if (colorPick == redButton) {
setColor = "red";
}
else if (colorPick == orangeButton) {
setColor = "orange";
}
else if (colorPick == yellowButton) {
setColor = "yellow";
}
else if (colorPick == greenButton) {
setColor = "green";
}
else if (colorPick == blueButton) {
setColor = "blue";
}
else if (colorPick == violetButton) {
setColor = "purple";
}
else if (colorPick == brownButton) {
setColor = "brown";
}
else if (colorPick == blackButton) {
setColor = "black";
}
console.log(setColor);
}
//---end of colorSelect
function placeBoat_client () {
var demoColor = "orange";
var source_client = event.target.id;
console.log(source_client);
source_client.id = document.getElementById(source_client.id);
document.getElementById(source_client).style.backgroundColor = demoColor;
}
for (var y_client = 1; y_client < 11; y_client++) {
battlefield_client += "<tr>";
for (var x_client = 1; x_client < 11; x_client++) {
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
}
battlefield_client += "</tr>";
}
$(document).ready(function() {
$("#tableGrid_client").html(battlefield_client); //loads table
for (var y_client = 1; y_client < 11; y_client++) {
for (var x_client = 1; x_client < 11; x_client++) {
boatStatusClient = document.getElementById('cell_client_' + x_client + "_" + y_client);
boatStatusClient.addEventListener("click", /*boatGrid.*/placeBoat_client, false);
}
}
document.getElementById("redButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("orangeButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("yellowButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("greenButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("blueButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("violetButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("brownButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("blackButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
}); //end of ready

How to hide rows in a form until they are clicked using javascript.?

I need to hide rows until they are clicked. I didn't initially write the code and I was having hard time fixing the issues. It's for an advanced order form for a private jet company. The form is supposed to have only 2 visible legs and then you'll be able to click on add a leg button to add a leg, instead it shows 15 legs.
jQuery(document).ready(function () {
jQuery('.trip-type').change(function () {
if (jQuery(this).val() == "multi-leg") {
jQuery("#addleg").css("display", "block").hide().end();
for (var i = 2; i <= 3; i++) {
jQuery('.to_leg_' + i).val('');
jQuery('.to_leg_' + i).attr('data-code', "");
jQuery('.to_leg_' + i).attr('data-name', "");
jQuery('.to_leg_' + i).attr('data-real-city', "");
jQuery('.to_leg_' + i).attr('data-country', "");
jQuery('.to_leg_' + i).attr('data-latitude', "");
jQuery('.to_leg_' + i).attr('data-longitude', "");
}
for (var n = 3; i <= 5; i++) {
jQuery('.from_leg_' + i).val('');
jQuery('.from_leg_' + i).attr('data-code', "");
jQuery('.from_leg_' + i).attr('data-name', "");
jQuery('.from_leg_' + i).attr('data-real-city', "");
jQuery('.from_leg_' + i).attr('data-country', "");
jQuery('.from_leg_' + i).attr('data-latitude', "");
jQuery('.from_leg_' + i).attr('data-longitude', "");
}
var allElements = jQuery('#multileg-block').find("div.row");
for (var i = 0; n < allElements.length; i++) {
if (jQuery(allElements[i]).hasClass("non-one-way") === true) {
jQuery(allElements[i]).removeClass('non-one-way');
jQuery(allElements[i]).removeClass(i);
jQuery(allElements[i]).css("display", "none");
jQuery(allElements[i]).attr('attribute', "");
}
}
var trelements = jQuery('#multi-table').find("tbody tr.multileg-table");
for (var i = 1; i < trelements.length; i++) {
if (jQuery(trelements[i]).hasClass('non-one-way') === true) {
jQuery(trelements[i]).removeClass("non-one-way");
jQuery(trelements[i]).css("display", "none");
jQuery(trelements[i]).attr('attribute', "");
}
}
$('.info-distances tbody tr.multileg-info:eq(0)').addClass('non-one-way');
} else {
jQuery("#addleg").css("display", "none");
jQuery('.info-distances tbody tr:eq(1)').removeClass('non-one-way');
var mutrelements = jQuery('.info-distances').find("tbody tr.multileg-info");
for (var i = 1; i < mutrelements.length; i++) {
if (jQuery(mutrelements[i]).hasClass('non-one-way') === true) {
jQuery(mutrelements[i]).removeClass("non-one-way");
}
}
}
});
jQuery('#addleg').on("click", function () {
var allElements = jQuery('#multileg-block').find("div.row");
for (var i = 0; i < allElements.length; i++) {
if (jQuery(allElements[i]).hasClass("non-one-way") == false) {
jQuery(allElements[i]).addClass('non-one-way');
jQuery(allElements[i]).addClass(i);
jQuery(allElements[i]).css("display", "block");
jQuery(allElements[i]).attr('attribute', i);
break;
}
}
var trelements = jQuery('#multi-table').find("tbody tr.multileg-table");
for (var i = 0; i < trelements.length; i++) {
if (jQuery(trelements[i]).hasClass('non-one-way') === false) {
jQuery(trelements[i]).addClass("non-one-way");
jQuery(trelements[i]).css("display", "table-row");
jQuery(trelements[i]).attr('attribute', i);
break;
}
}
var mutrelements = jQuery('.info-distances').find("tbody tr.multileg-info");
for (var i = 1; i < mutrelements.length; i++) {
if (jQuery(mutrelements[i]).hasClass('non-one-way') === false) {
jQuery(mutrelements[i]).addClass("non-one-way");
break;
}
}
});
jQuery('.Leg_remove').on("click", function () {
jQuery(this).parent().parent().css('display', 'none');
jQuery(this).parent().parent().removeClass('non-one-way');
index = parseInt(jQuery(this).parent().parent().attr('attribute'));
jQuery('.non-one-way[attribute=' + index + ']').removeClass('non-one-way').css('display', 'none');
index += 2;
jQuery('.info-distances tbody tr:eq(' + index + ')').removeClass('non-one-way');
});
}); < /script>

JS/JSp issue in IE 10 for scrollbar and sorting

I am facing issue in table where we are using scroll bar and sorting.
In compatible mode sorting option is coming where as not coming in non compatible mode
Please suggest changes in js or jsp
function makeScrollableTable(tbl, scrollFooter, height, hasSelectAllButton, hasAddButton, columnNo) {
var c, pNode, hdr, ftr, wrapper, rect;
//alert("Shree");
if (typeof tbl == 'string') tbl = document.getElementById(tbl);
pNode = tbl.parentNode;
fixTableWidth(tbl);
c = container.length;
container[c] = document.createElement('<SPAN style="height: 100; overflow: auto;">');
container[c].id = tbl.id + "Container";
pNode.insertBefore(container[c], tbl);
container[c].appendChild(tbl);
container[c].style.width = tbl.clientWidth + 2 * tbl.clientLeft + scrollbarWidth();
hdr = tbl.cloneNode(false);
hdr.id += 'Header';
hdr.appendChild(tbl.tHead.cloneNode(true));
tbl.tHead.style.display = 'none';
if (!scrollFooter || !tbl.tFoot) {
ftr = document.createElement('<SPAN style="width:1;height:1;clip: rect(0 1 1 0);background-color:transparent;">');
ftr.id = tbl.id + 'Footer';
ftr.style.border = tbl.style.border;
ftr.style.width = getActualWidth(tbl) + 2 * tbl.clientLeft;
ftr.style.borderBottom = ftr.style.borderLeft = ftr.style.borderRight = 'none';
} else {
ftr = tbl.cloneNode(false);
ftr.id += 'Footer';
ftr.appendChild(tbl.tFoot.cloneNode(true));
ftr.style.borderTop = 'none';
tbl.tFoot.style.display = 'none';
}
wrapper = document.createElement('<table border=0 cellspacing=0 cellpadding=0>');
wrapper.id = tbl.id + 'Wrapper';
pNode.insertBefore(wrapper, container[c]);
wrapper.insertRow(0).insertCell(0).appendChild(hdr);
wrapper.insertRow(1).insertCell(0).appendChild(container[c]);
wrapper.insertRow(2).insertCell(0).appendChild(ftr);
wrapper.align = tbl.align;
tbl.align = hdr.align = ftr.align = 'left';
hdr.style.borderBottom = 'none';
tbl.style.borderTop = tbl.style.borderBottom = 'none';
// adjust page size
if (c == 0 && height == 'auto') {
onResizeAdjustTable();
onResizeHandler = window.onresize;
window.onresize = onResizeAdjustTable;
} else {
container[c].style.height = height;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
//alert("");
if (hasSelectAllButton) {
//include select all button
var selButton = document.createElement('<input id="_myButton11" type="button" value="Select All" onClick="selectAll();">');
insertNode(selButton);
}
if (hasAddButton) {
var btext = '<input id="_myButton12" type="button" value="Add" onClick="posCursor(\'' + tbl.id + '\',\'' + columnNo + '\');">';
var addButton = document.createElement(btext);
insertNode(addButton);
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function insertNode(toInsert) {
var tbs = document.getElementsByTagName('input');
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "button") {
var backButton = tbs[i];
var text = backButton.value.toUpperCase();
if (text == "BACK") {
var pNode = backButton.parentNode;
pNode.insertBefore(toInsert, backButton);
var textNode = document.createTextNode(" ");
pNode.insertBefore(textNode, backButton);
return;
}
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function posCursor(tbl, columnNo) {
var table = document.getElementById(tbl);
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
//cells = rows[i].cells;
//if(columnNo > cells.length) continue;
var cell = rows[i].cells[columnNo];
if (getFocus(cell) == true) {
selectCheckBox(rows[i].cells[0]);
return;
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectCheckBox(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a checkbox input node
if (node.tagName == "INPUT" && node.type == "checkbox") {
node.checked = true;
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (selectCheckBox(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function getFocus(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a text input node
if (node.tagName == "INPUT" && node.type == "text" && node.value == "") {
node.focus();
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (getFocus(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectAll() {
//added by Venkatesh Bhat e-mail:vb106#dcx
var button = document.getElementById('_myButton11');
var butText = button.value;
var tbs = document.getElementsByTagName('input');
if (butText == 'Deselect All') {
button.value = "Select All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = false;
}
}
} else {
button.value = "Deselect All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = true;
}
}
}
}
function onResizeAdjustTable() {
if (onResizeHandler) onResizeHandler();
var rect = container[0].getClientRects()(0);
var h = document.body.clientHeight - (rect.top + (document.body.scrollHeight - rect.bottom));
container[0].style.height = (h > 0) ? h : 1;
}
function printPage() {
var tbs = document.getElementsByTagName('TABLE');
var e;
for (var i = 0; i < container.length; i++) container[i].style.overflow = '';
window.print();
for (var i = 0; i < container.length; i++) container[i].style.overflow = 'auto';
}

LightZAP v2.54 (silent update2) (Lightbox custom plugin) auto start when page loads with tag name (#img1)

I have LightZAP plugin which is an alternative to Lightbox running on my website. I want to run it (pop out an image gallery with a specific image) when page loads using: index.html#img1 link if thats possible.
I have seen similar scripts for lightbox v2, did try to customize them to use on LightZAP but couldn't run it. Thats the example in here: http://frankleng.me/2010/07/21/drupal-tip-lightbox-pop-up-on-page-load/
Any help would be much appreciated.
Code for LightZAP:
` /* LightZAP v2.54 (silent update2)
by Szalai Mihaly - http://dragonzap.szunyi.com
original by Lokesh Dhakar (lightbox) - http://lokeshdhakar.com
For more information, visit:
http://dragonzap.szunyi.com/index.php?e=page&al=lightzap&l=en
Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
- free for use in both personal and commercial projects
- attribution requires leaving author name, author link, and the license info intact
Thanks
- Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
- Artemy Tregubenko (arty.name) for cleanup and help in updating to latest proto-aculous in v2.05.
- Szalai Mihaly (dragonzap.szunyi.com), automatic image resize for screen, fullscreen viewer, print button, download button, like button and new design.*/
var imgNotFound,
//----- Options --------
imagetext = "", //"Image "
oftext = " / ",//" of "
bytext = "", //"by"
notfoundtext = "Image not found",
print = false,
download = true,
like = true;
buy = true;
//----------------------
var $lightzap, $container, $image, $lbContainer;
var windowWidth, windowHeight, originalWidth, originalHeight, album = [], currentImageIndex = 0, isfull = false, marginWidth = -1, marginHeight = -1;
var pfx = ["webkit", "moz", "ms", "o", ""];
function getElementsByClassName(element, className) {
if (element.getElementsByClassName)
return element.getElementsByClassName(className);
else
return document.querySelectorAll('.' + className);
};
function lzInit()
{
//Set links
var _ref = document.links, i = _ref.length;
while (i--)
{
var a = _ref[i];
if (a.getAttribute("data-lightzap") != null)
a.onclick = function () {return lzStart(this);};
}
//FullScreen
var pfx0 = ["IsFullScreen", "FullScreen"], pfx1 = ["CancelFullScreen", "RequestFullScreen"];
var k, m, t = "undefined", p = 0;
while (p < pfx.length && !document[m])
{
k = 0;
while (k < pfx0.length)
{
m = pfx0[k];
if (pfx[p] == "")
{
m = m.substr(0, 1).toLowerCase() + m.substr(1);
pfx1[0] = pfx1[0].substr(0, 1).toLowerCase() + pfx1[0].substr(1);
pfx1[1] = pfx1[1].substr(0, 1).toLowerCase() + pfx1[1].substr(1);
}
m = pfx[p] + m;
t = typeof document[m];
if (t != "undefined")
{
pfx = [pfx[p] + pfx1[0], pfx[p] + pfx1[1], m];
p = 2;
break;
}
k++;
}
p++;
}
//Build lightzap
$lightzap = document.createElement("div");
$lightzap.id = "lightzap";
$lightzap.style.display = 'none';
document.body.appendChild($lightzap);
var tmp = document.createElement("div");
tmp.className = "lz-bg";
tmp.onclick = lzEnd;
$lightzap.appendChild(tmp);
$container = document.createElement("div");
$container.className = "lz-container";
$container.style.display = 'none';
$lightzap.appendChild($container);
tmp = document.createElement("div");
tmp.className = "lz-loader";
$container.appendChild(tmp);
$image = document.createElement("img");
$image.className = "lz-image";
$container.appendChild($image);
var group = document.createElement("div");
group.className = "lz-nav";
$container.appendChild(group);
tmp = document.createElement("a");
tmp.className = "lz-prev";
tmp.onclick = function ()
{
lzChangeImage(currentImageIndex + 1);
return false;
};
group.appendChild(tmp);
tmp = document.createElement("a");
tmp.className = "lz-next";
tmp.onclick = function ()
{
lzChangeImage(currentImageIndex - 1);
return false;
};
group.appendChild(tmp);
group = document.createElement("div");
group.className = "lz-buttonContainer";
$container.appendChild(group);
tmp = document.createElement("a");
tmp.className = "lz-button lz-more";
tmp.onclick = function ()
{
if (getElementsByClassName($container, "lz-desc")[0].style.display == 'none') getElementsByClassName($container, "lz-desc")[0].style.display = '';
else getElementsByClassName($container, "lz-desc")[0].style.display = 'none';
return false;
};
group.appendChild(tmp);
tmp = document.createElement("a");
tmp.className = "lz-button lz-print";
tmp.onclick = lzPrint;
group.appendChild(tmp);
tmp = document.createElement("a");
tmp.className = "lz-button lz-download";
tmp.onclick = lzDownload;
tmp.target = "_blank";
group.appendChild(tmp);
tmp = document.createElement("a");
tmp.className = "lz-button lz-buy";
tmp.onclick = lzBuy;
group.appendChild(tmp);
tmp = document.createElement("a");
tmp.className = "lz-button lz-like";
tmp.onclick = lzLike;
group.appendChild(tmp);
//Buttons
if (p != 4) pfx = false;
else
{
tmp = document.createElement("div");
tmp.className = "lz-button lz-fullScreen";
tmp.onclick = function ()
{
if (isfull) document[pfx[0]]();
else $lightzap[pfx[1]]();
};
group.appendChild(tmp);
}
tmp = document.createElement("a");
tmp.className = "lz-button lz-close";
tmp.onclick = lzEnd;
group.appendChild(tmp);
$lbContainer = document.createElement("div");
$lbContainer.className = "lz-labelContainer";
$container.appendChild($lbContainer);
tmp = document.createElement("div");
tmp.className = "lz-float lz-caption";
$lbContainer.appendChild(tmp);
tmp = document.createElement("div");
tmp.className = "lz-float lz-desc";
tmp.style.display = 'none';
$lbContainer.appendChild(tmp);
tmp = document.createElement("div");
tmp.className = "lz-float lz-resolution";
$lbContainer.appendChild(tmp);
tmp = document.createElement("a");
tmp.className = "lz-float lz-by";
tmp.target = "_blank";
$lbContainer.appendChild(tmp);
tmp = document.createElement("div");
tmp.className = "lz-float lz-number";
$lbContainer.appendChild(tmp);
};
window.onload = lzInit;
function lzStart($link)
{
//Show overlay
lzShowOthers(false);
lzSizeOverlay();
$lightzap.style.display = '';
$container.style.display = '';
window.onresize = lzSizeOverlay;
//Get original margin
if (marginWidth == -1)
{
imgNotFound = window.getComputedStyle($image, "").getPropertyValue("background-image").replace("url(", "").replace(")", "").replace('"', '').replace('"', '');
$image.style.backgroundImage = "none";
var tmp = window.getComputedStyle($container, "");
marginHeight = parseInt(tmp.getPropertyValue("margin-top")) + parseInt(tmp.getPropertyValue("margin-bottom")) + parseInt(tmp.getPropertyValue("padding-top")) + parseInt(tmp.getPropertyValue("padding-bottom")) + parseInt(tmp.getPropertyValue("border-top-width")) + parseInt(tmp.getPropertyValue("border-bottom-width"));
marginWidth = parseInt(tmp.getPropertyValue("margin-left")) + parseInt(tmp.getPropertyValue("margin-right")) + parseInt(tmp.getPropertyValue("padding-left")) + parseInt(tmp.getPropertyValue("padding-right")) + parseInt(tmp.getPropertyValue("border-left-width")) + parseInt(tmp.getPropertyValue("border-right-width"));
}
//Create album
album = [];
var a, i, _len, _ref, imageNumber = 0;
if ($link.getAttribute("data-lightzap") == "")
lzReadAlbum($link);
else
{
var _ref = document.links, _href = $link.href, _attr = $link.getAttribute("data-lightzap"), i = _ref.length, j = 0;
while (i--)
{
var a = _ref[i];
if (a.getAttribute("data-lightzap") != null && a.getAttribute("data-lightzap") == _attr)
{
lzReadAlbum(a);
if (a.href == $link.href) imageNumber = j;
j++;
}
}
}
lzChangeImage(imageNumber);
return false;
};
function lzReadAlbum($link)
{
var download = false, like = false, buy = false, print = false, options = $link.getAttribute("data-options");
if (options != null && options.length > 4)
{
download = options.indexOf("download") != -1;
buy = options.indexOf("buy") != -1;
like = options.indexOf("like") != -1;
print = options.indexOf("print") != -1;
}
album.push({
link: $link.getAttribute("href"),
title: $link.getAttribute("title"),
desc: $link.getAttribute("data-desc"),
by: $link.getAttribute("data-by"),
by_link: $link.getAttribute("data-link"),
download: download,
buy: buy,
like: like,
print: print
});
};
function lzChangeImage(imageNumber)
{
//Hide other
document.onkeypress = lzKeyboardAction;
getElementsByClassName($container, "lz-loader")[0].style.display = "";
getElementsByClassName($container, "lz-nav")[0].style.display = "none";
getElementsByClassName($container, "lz-buttonContainer")[0].style.display = "none";
$lbContainer.style.display = "none";
$image.className = "lz-hide";
//New image
var preloader = new Image;
preloader.onload = function ()
{
$image.src = album[imageNumber].link;
originalWidth = preloader.width;
originalHeight = preloader.height;
currentImageIndex = imageNumber;
return lzGetImageSize();
};
preloader.onerror = function ()
{
album[imageNumber].title = notfoundtext;
album[imageNumber].link = imgNotFound;
$image.src = album[imageNumber].link;
originalWidth = 256;
originalHeight = 256;
currentImageIndex = imageNumber;
return lzGetImageSize();
};
preloader.src = album[imageNumber].link;
};
function lzSizeOverlay()
{
var _windowWidth, _windowHeight;
if(typeof(window.innerWidth) == 'number') //Non-IE
{
_windowWidth = Math.min(window.innerWidth, document.body.clientWidth);
_windowHeight = window.innerHeight;
}
else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) //IE 6+ in 'standards compliant mode'
{
_windowWidth = document.documentElement.clientWidth;
_windowHeight = document.documentElement.clientHeight;
}
else if (document.body && (document.body.clientWidth || document.body.clientHeight)) //IE 4 compatible
{
_windowWidth = document.body.clientWidth;
_windowHeight = document.body.clientHeight;
}
//If chanced size
if (windowWidth != _windowWidth || windowHeight != _windowHeight)
{
//Set size
windowWidth = _windowWidth;//(_windowWidth <= screen.width) ? _windowWidth : screen.width * 0.8;
windowHeight = _windowHeight;//(_windowHeight <= screen.height) ? _windowHeight : screen.height * 0.8;
$lightzap.style.width = _windowWidth;
$lightzap.style.height = _windowHeight;
//Is fullscreen?
isfull = false;
if (pfx != false) isfull = (typeof document[pfx[2]] == "function" ? document[pfx[2]]() : document[pfx[2]]);
if (!isfull) isfull = (windowWidth >= screen.width * 0.99 && windowHeight >= screen.height * 0.99);
//Set style
if (isfull)
{
$lightzap.className = "full-screen";
$lightzap.style.width = "";
$lightzap.style.height = "";
$container.style.height = "100%";
getElementsByClassName($lightzap, "lz-bg")[0].onclick = null;
}
else
{
getElementsByClassName($lightzap, "lz-bg")[0].onclick = lzEnd
$lightzap.className = "";
$container.style.width = "";
$container.style.height = "";
}
//Update image size
if (album.length > 0)
lzGetImageSize();
}
};
function lzGetImageSize()
{
//Sizes
var placeWidth = windowWidth, placeHeight = windowHeight, imageWidth = originalWidth, imageHeight = originalHeight;
var master = $container.style, slave = $image.style;
if (!isfull)
{
placeWidth -= marginWidth;
placeHeight -= marginHeight;
}
else
{
slave = master;
master = $image.style;
if (pfx)
{
placeWidth = screen.width;
placeHeight = screen.height;
}
}
//Calculate optional size
if (imageWidth > placeWidth)
{
imageHeight = (placeWidth * imageHeight) / imageWidth;
imageWidth = placeWidth;
}
if (imageHeight > placeHeight)
{
imageWidth = (placeHeight * imageWidth) / imageHeight;
imageHeight = placeHeight;
}
//Set box style
slave.top = "0";
slave.left = "0";
slave.width = "";
slave.height = "";
master.top = (placeHeight - imageHeight) * 0.5 + "px";
master.left = (placeWidth - imageWidth) * 0.5 + "px";
master.width = imageWidth + "px";
master.height = imageHeight + "px";
lzShowImage();
};
function lzShowImage()
{
lzUpdateNav();
lzUpdateDetails();
//Preload
var preloadNext, preloadPrev;
if (album.length > currentImageIndex + 1)
{
preloadNext = new Image;
preloadNext.src = album[currentImageIndex + 1].link;
}
if (currentImageIndex > 0)
{
preloadPrev = new Image;
preloadPrev.src = album[currentImageIndex - 1].link;
}
setTimeout(function(){
$image.className = "lz-image";
getElementsByClassName($container, "lz-nav")[0].style.display = "";
$lbContainer.style.display = "";
getElementsByClassName($container, "lz-buttonContainer")[0].style.display = "";
getElementsByClassName($container, "lz-loader")[0].style.display = "none";
},380);
};
function lzUpdateDetails()
{
//Counter
var element = getElementsByClassName($lbContainer, "lz-number")[0];
if (album.length > 1)
{
element.textContent = imagetext + (album.length - currentImageIndex) + oftext + album.length;
element.style.display = "";
}
else element.style.display = "none";
//Caption
element = getElementsByClassName($lbContainer, "lz-caption")[0];
if (album[currentImageIndex].title != null && album[currentImageIndex].title != "")
{
element.textContent = album[currentImageIndex].title;
element.style.display = "";
if (album[currentImageIndex].title == notfoundtext) return false;
}
else element.style.display = "none";
//Description
element = getElementsByClassName($container, "lz-more")[0];
if (album[currentImageIndex].desc != null && album[currentImageIndex].desc != "")
{
element.style.display = "";
element = getElementsByClassName($lbContainer, "lz-desc")[0];
element.innerHTML = album[currentImageIndex].desc;
element.style.display = "none";
}
else
{
element.style.display = "none";
getElementsByClassName($lbContainer, "lz-desc")[0].style.display = "none";
}
//Author
element = getElementsByClassName($lbContainer, "lz-by")[0];
if (album[currentImageIndex].by != null && album[currentImageIndex].by != "")
{
element.innerHTML = bytext + " <span>" + album[currentImageIndex].by + "</span>";
element.style.display = "";
if (album[currentImageIndex].by_link != null && album[currentImageIndex].by_link != "") element.href = album[currentImageIndex].by_link;
}
else
{
element.innerHTML = "";
element.style.display = "none";
if (album[currentImageIndex].by_link != null && album[currentImageIndex].by_link != "") getElementsByClassName($container, ".lz-caption").html() + '</a>';
}
//Others
getElementsByClassName($container, "lz-like")[0].style.display = (album[currentImageIndex].like != like) ? "" : "none";
getElementsByClassName($container, "lz-buy")[0].style.display = (album[currentImageIndex].buy != buy) ? "" : "none";
getElementsByClassName($container, "lz-download")[0].style.display = (album[currentImageIndex].download != download) ? "" : "none";
getElementsByClassName($container, "lz-print")[0].style.display = (album[currentImageIndex].print != print) ? "" : "none";
getElementsByClassName($lbContainer, "lz-resolution")[0].textContent = originalWidth + " x " + originalHeight;
};
function lzUpdateNav()
{
getElementsByClassName($container, "lz-prev")[0].style.display = "none";
getElementsByClassName($container, "lz-next")[0].style.display = "none";
if (currentImageIndex > 0) getElementsByClassName($container, "lz-next")[0].style.display = "";
if (currentImageIndex < album.length - 1) getElementsByClassName($container, "lz-prev")[0].style.display = "";
};
function lzKeyboardAction(e)
{
var keycode = e.keyCode, key = String.fromCharCode(e.charCode).toLowerCase(),
KEYCODE_ESC = 27,
KEYCODE_LEFTARROW = 37,
KEYCODE_RIGHTARROW = 39,
KEYCODE_F11 = 122;
if (keycode == KEYCODE_ESC || key.match(/x|o|c/)) lzEnd();
else if (key == "n" || keycode == KEYCODE_RIGHTARROW)
{
if (currentImageIndex != 0) lzChangeImage(currentImageIndex - 1);
}
else if ((key == "p" || keycode == KEYCODE_LEFTARROW) && currentImageIndex != album.length - 1) lzChangeImage(currentImageIndex + 1);
};
function lzPrint()
{
win = window.open();
self.focus();
win.document.open();
win.document.write("<html><body stlye='margin:0 auto;padding:0;'><h1 style='margin:0 0 0.48em;'>" + getElementsByClassName($container, "lz-caption")[0].textContent + "</h1><div style='text-align:center;'><img src='" + album[lz.currentImageIndex].link + "' style='max-width:100%;max-height:100%;'/></div><div style='text-align:right;'><i>" + getElementsByClassName($container, "lz-by")[0].textContent + "</i></div></body></html>");
win.document.close();
win.print();
win.close();
};
function lzLike()
{
if (!window.focus) return true;
window.open("http://www.facebook.com/sharer/sharer.php?u=" + $image.src, "", 'width=400,height=200,scrollbars=yes');
};
function lzBuy()
{
if (!window.focus) return true;
window.open("../shop.html",'_self');
};
function lzDownload()
{
if (window.webkitURL)
{ //Webkit
var xhr = new XMLHttpRequest();
xhr.open("GET", album[currentImageIndex].link);
xhr.responseType = "blob";
xhr.onreadystatechange = function ()
{
var a = document.createElement("a");
a.href = (window.URL) ? window.URL.createObjectURL(xhr.response) : window.webkitURL.createObjectURL(xhr.response);
a.download = album[currentImageIndex].link.substring(album[currentImageIndex].link.lastIndexOf("/") + 1);
var e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
};
xhr.send();
return true;
}
else if (navigator.appName == 'Microsoft Internet Explorer')
{ //IE
win = window.open(album[currentImageIndex].link);
self.focus();
win.document.execCommand("SaveAs");
win.close();
return true;
}
else
{ //Opera & Firefox (CANVAS)
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
if (typeof canvas.getContext != "undefined")
{
try
{
var context = canvas.getContext("2d");
canvas.width = Math.min(originalWidth, 1024);
canvas.height = Math.min(originalHeight, originalHeight / originalWidth * 1024);
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
context.drawImage($image, 0, 0, canvas.width, canvas.height);
document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
document.body.removeChild(canvas);
return true;
}
catch (err)
{
document.body.removeChild(canvas);
}
}
}
alert("Sorry, can't download");
};
function lzEnd()
{
if (isfull && pfx != false) document[pfx[0]]();
album = [];
document.onkeypress = null;
window.onresize = null;
$lightzap.style.display = 'none';
$container.style.display = 'none';
lzShowOthers(true);
return false;
};
function lzShowOthers(show)
{
var _ref, i, tagNames = ["select", "object", "embeds"], tagNum = 3;
show = (show) ? "visible" : "hidden";
while(tagNum--)
{
_ref = document.getElementsByTagName(tagNames[tagNum]);
i = _ref.length;
while (i--)
_ref[i].style.visibility = show;
}
}'
I managed to solve it myself. If anyone will need it in the future here is how I did it:
Javascript that lets the page to load and starts after 100ms (let
lightZAP create itself first).
Get and save hash element.
Create an if statement: If website has a hash (ex: index.html#img) start lightZAP with element id hash
<script type="text/javascript">
setTimeout(function(){
var hash = window.location.hash.split('#')[1];
if (window.location.hash != "" ) {
lzStart(document.getElementById(hash));
}}, 100);
Also, when defining images that are required to be displayed by lightZAP it is necessary to add a few lines:
a tag is suppose to have rel="lightzap" and id="img"
Example:
<div class="single first"><a rel="lightzap" id="a1" gref="../images/Alaska/a1.jpg" data-lightzap="Alaska" data-desc = "desc" title="Alaska"> <img src="../images/Alaska/a1-thumb.jpg"> </a> </div>

Categories

Resources