Button Array seems to not be working - javascript

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>

Related

Code not accessing nextElementSibling correctly

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

How to terminate infinite scrolling using Javascript

I am currently working on this javascript based slider
I want the slider to hide the next button when it reaches the final slide and should not slide after that
how can I do this
Codepen Link
fixed it for you sorry
function shiftSlide(dir, action) {
items.classList.add('shifting');
items.classList.add('shifting');
console.log(index)
if (allowShift) {
if (!action) { posInitial = items.offsetLeft; }
if (dir == 1) {
items.style.left = (posInitial - slideSize) + "px";
index += dir;
} else if (dir == -1) {
items.style.left = (posInitial + slideSize) + "px";
index+= dir;
}
if(index == slidesLength -1){
document.querySelector('#next').style.display = 'none';
document.querySelector('#prev').style.display = 'block';
}
else if(index == 0){
document.querySelector('#prev').style.display = 'none';
document.querySelector('#next').style.display = 'block';
}
else{
document.querySelector('#prev').style.display = 'block';
document.querySelector('#next').style.display = 'block';
}
};
allowShift = false;
}
You can check when you shift the image if it is the last elm in the list and make the button display none
function shiftSlide(dir, action) {
items.classList.add('shifting');
if(index == document.querySelectorAll('#slides .slide').length){
document.querySelector('#next').style.display = 'none';
}
if (allowShift) {
if (!action) { posInitial = items.offsetLeft; }
if (dir == 1) {
items.style.left = (posInitial - slideSize) + "px";
index++;
} else if (dir == -1) {
items.style.left = (posInitial + slideSize) + "px";
index--;
}
};
allowShift = false;
}

Javascript: Global Variables Aren't Defined In Other Functions

I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].
try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!
You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.
My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.

Javascript Page Reset

Im trying to get my page to reset to its original layout once the popup goes away after 5 seconds. I've tried setTimeOut(fullReset(true), messageHIde, 5000) but that stops the pop up from working.I know how to get it back to its original layout if it was the case of using a button. Any tips about how to get it working? My java script is below for the popup and the fullReset.
if ((playerChoice == "higher") && (playerCard > computerCard))
{
document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
/* increase the score by 5 because the user won */
total = total + 5;
}
else if ((playerChoice == "higher") && (computerCard > playerCard))
{
document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;
}
else if ((playerChoice == "equal") && (playerCard > computerCard))
{ document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total +5 ; }
else if ((playerChoice == "equal") && (computerCard > playerCard))
{ document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;}
else if ((playerChoice == "lower") && (playerCard > computerCard))
{
document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total + 5;}
else if ((playerChoice =="lower") && (computerCard > playerCard))
{document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;}
/* display the new total */
alert(total + " " + playerChoice + " " + playerCard + " " +computerCard);
document.getElementById('score').innerHTML = total;
}
function messageHide(){
document.getElementById('popup').style.display = "none";
}
function fullReset(){
document.getElementById('img1').src = 'back.gif';
document.getElementById('img2').src = 'back.gif';
document.getElementById('higherButton').style.backgroundColor = "white";
document.getElementById('lowerButton').style.backgroundColor = "white";
document.getElementById('equalButton').style.backgroundColor = "white";
document.getElementById('drawButton').style.backgroundColor = "white";
document.getElementById('score').innerHTML = "0" +total;
startButton.disabled = false;
higherButton.disabled = true;
lowerButton.disabled = true;
equalButton.disabled = true;
drawButton.disabled = true;
}
Use
setTimeOut(function(){
messageHide();
fullReset();
}, 5000);

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