Javascript gallery with two items at a time - javascript

I have this gallery that shows two items at a time, but I was wondering if there's a more elegant way than repeating the same code all the time for the item B in the gallery.
Here's the main code:
var Gallery = new Object();
window.onload = function(){
Gallery.Images = ['red','blue','pink','green','yellow','purple','orange','navy'];
Gallery.CurrentIndexA = 0;
Gallery.CurrentIndexB = 1;
};
Gallery.Next = function(){
if (Gallery.CurrentIndexA < (Gallery.Images.length-1)){
Gallery.CurrentIndexA++;
Gallery.CurrentIndexB++;
console.log("A is:" + Gallery.CurrentIndexA);
console.log("B is:" + Gallery.CurrentIndexB);
}
else {
Gallery.CurrentIndexA = 0;
}
Gallery.Display();
};
Gallery.Prev = function(){
if (Gallery.CurrentIndexA > 0){
Gallery.CurrentIndexA--;
Gallery.CurrentIndexB--;
console.log("A is:" + Gallery.CurrentIndexA);
console.log("B is:" + Gallery.CurrentIndexB);
}
else {
Gallery.CurrentIndexA = (Gallery.Images.length-1);
}
Gallery.Display();
};
Gallery.Display = function(){
var photoA = document.getElementById('photoA');
var photoB = document.getElementById('photoB');
var currentImageA = Gallery.Images[Gallery.CurrentIndexA];
var currentImageB = Gallery.Images[Gallery.CurrentIndexB];
photoA.className = currentImageA;
photoB.className = currentImageB;
};
Here's a fiddle: http://jsfiddle.net/2AdA9/1/
Thanks very much!

If you want to make it look better one thing you could do is something like this.
Gallery.moveUp = function (){
Gallery.CurrentIndexA += 1;
Gallery.CurrentIndexB += 1;
};
Gallery.moveDown = function (){
Gallery.CurrentIndexA -= 1;
Gallery.CurrentIndexB -= 1;
};
Then just call those functions when you want to move up or move back.

Related

Why I get Indefined when displaying Img’s on page?

I have been playing with this code for a while and I was wondering why when I try to add img’s to the array on the js code makes the images appear on DOM but also makes a bunch of Undefined elements appear, How can I just make the 15 images appear without the undefined? Thanks
enter link description here
var previous = document.getElementById('btnPrevious')
var next = document.getElementById('btnNext')
var gallery = document.getElementById('image-gallery')
var pageIndicator = document.getElementById('page')
var galleryDots = document.getElementById('gallery-dots');
var images = ["https://exoplanets.nasa.gov/internal_resources/1763/",
"https://cdn.britannica.com/56/234056-050-0AC049D7/first-image-from-James-Webb-Space-Telescope-deepest-and-sharpest-infrared-image-of-distant-universe-to-date-SMACS-0723.jpg",
"https://assets.newatlas.com/dims4/default/ac389ce/2147483647/strip/true/crop/1620x1080+150+0/resize/1200x800!/quality/90/?url=http%3A%2F%2Fnewatlas-brightspot.s3.amazonaws.com%2Farchive%2Funiverse-expanding-acceleration-1.jpg",
"https://media.newyorker.com/photos/590966ee1c7a8e33fb38d6cc/master/w_2560%2Cc_limit/Nissan-Universe-Shouts.jpg",
"https://www.thoughtco.com/thmb/NY5k_3slMRttvtS7mA0SXm2WW9Q=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/smallerAndromeda-56a8ccf15f9b58b7d0f544fa.jpg",
"https://static.scientificamerican.com/sciam/cache/file/05B8482C-0C04-4E41-859DCCED721883D2_source.jpg?w=590&h=800&7ADE2895-F6E3-4DF4-A11F51B652E9FA88",
"https://qph.cf2.quoracdn.net/main-thumb-66277237-200-huqebnzwetdsnnwvysbxemlskpcxnygf.jpeg",
"http://www.pioneertv.com/media/1090/hero_shot_1080x720.jpg?anchor=center&mode=crop&width=600&height=400&rnd=133159257140000000",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRSWFW1EpMNFM5-dbZEUUnzJkzT3KbUCeuhPHx_eseFCpPeX4Q_DIVPopjS0LeKVmKdQho&usqp=CAU",
"https://cdn.mos.cms.futurecdn.net/rwow8CCG3C3GrqHGiK8qcJ.jpg",
"https://static.wixstatic.com/media/917d103965314e2eacefed92edb6492c.jpg/v1/fill/w_640,h_356,al_c,q_80,usm_0.66_1.00_0.01,enc_auto/917d103965314e2eacefed92edb6492c.jpg",
"https://astronomy.com/~/media/A5B9B6CF36484AB9A6FFAE136C55B355.jpg",
"https://discovery.sndimg.com/content/dam/images/discovery/fullset/2022/9/alien%20planet%20GettyImages-913058614.jpg.rend.hgtvcom.616.411.suffix/1664497398007.jpeg",
"https://images.newscientist.com/wp-content/uploads/2017/06/21180000/planet-10-orange-blue-final-small.jpg?crop=16:9,smart&width=1200&height=675&upscale=true",
"https://images.hindustantimes.com/img/2022/07/20/1600x900/Viral_Instagram_Planet_Rainbow_Nasa_1658316556293_1658316573815_1658316573815.PNG"
]
for (var i = 0; i < 15; i++) {
images.push({
title: "Image " + (i + 1),
source: images[i]
});
}
var perPage = 8;
var page = 1;
var pages = Math.ceil(images.length / perPage)
// Gallery dots
for (var i = 0; i < pages; i++){
var dot = document.createElement('button')
var dotSpan = document.createElement('span')
var dotNumber = document.createTextNode(i + 1)
dot.classList.add('gallery-dot');
dot.setAttribute('data-index', i);
dotSpan.classList.add('sr-only');
dotSpan.appendChild(dotNumber);
dot.appendChild(dotSpan)
dot.addEventListener('click', function(e) {
var self = e.target
goToPage(self.getAttribute('data-index'))
})
galleryDots.appendChild(dot)
}
// Previous Button
previous.addEventListener('click', function() {
if (page === 1) {
page = 1;
} else {
page--;
showImages();
}
})
// Next Button
next.addEventListener('click', function() {
if (page < pages) {
page++;
showImages();
}
})
// Jump to page
function goToPage(index) {
index = parseInt(index);
page = index + 1;
showImages();
}
// Load images
function showImages() {
while(gallery.firstChild) gallery.removeChild(gallery.firstChild)
var offset = (page - 1) * perPage;
var dots = document.querySelectorAll('.gallery-dot');
for (var i = 0; i < dots.length; i++){
dots[i].classList.remove('active');
}
dots[page - 1].classList.add('active');
for (var i = offset; i < offset + perPage; i++) {
if ( images[i] ) {
var template = document.createElement('div');
var title = document.createElement('p');
var titleText = document.createTextNode(images[i].title);
var img = document.createElement('img');
template.classList.add('template')
img.setAttribute("src", images[i].source);
img.setAttribute('alt', images[i].title);
title.appendChild(titleText);
template.appendChild(img);
template.appendChild(title);
gallery.appendChild(template);
}
}
// Animate images
var galleryItems = document.querySelectorAll('.template')
for (var i = 0; i < galleryItems.length; i++) {
var onAnimateItemIn = animateItemIn(i);
setTimeout(onAnimateItemIn, i * 100);
}
function animateItemIn(i) {
var item = galleryItems[i];
return function() {
item.classList.add('animate');
}
}
// Update page indicator
pageIndicator.textContent = "Page " + page + " of " + pages;
}
showImages();
I checked your code and make it work with a small modification.
You are reusing the same array with the links of images and push inside the new object with the shape of { title, source }.
You just need to do this changes:
Change the name of your array of images. Something from images to arrayOfImages.
const arrayOfImages = ["https://exoplanets.nasa.gov/internal_resources/1763/", ...]
Declare an empty array before your first for loop. Make something like const images = []
On your for loop, instead of loop over the images variable, do it over the arrayOfImages variable.
const images = [];
for (var i = 0; i < 15; i++) {
images.push({
title: "Image " + (i + 1),
source: arrayOfImages[i]
});
}
With those changes, everything works for me.
Also, as a recommendation, try to avoid the var keyword. If you want more details about this, this answer is very helpful: https://stackoverflow.com/a/50335579/17101307
You can use Array#map to create a new array of objects from the array of URLS, then replace the original array.
images = images.map((x, i) => ({
title: "Image " + (i + 1),
source: x
}));

.push commant executes "Underfind" from jquery function, how to execute a number?

So the script is really simple, I try to push the dNumber into variable pattern and the results are always "underfined".
when i try to do the same with just push a TEXT for example it's worked.
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber() {
var a = Math.floor((Math.random() * 100 / 25) + 1);
console.log(a);
console.log(pattern);
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
pattern.push(x);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber(){
var a = Math.floor((Math.random()*100/25)+1);
console.log(a);
console.log(pattern);
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
// pattern.push("alex"); this is work!
pattern.push(x);
pattern.push(dNumber());
//this isn't work what should be number looks like appear as underfined.
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to return a from dNumber function so that you can use :)
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber() {
var a = Math.floor((Math.random() * 100 / 25) + 1);
console.log(a);
console.log(pattern);
// return a here if not then it's gonna return undefined by default :)
return a;
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
pattern.push(x);
console.log(pattern);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Website not responding - I think due to javascript code

I'm trying to make a game in javascript and display it on my website, but the website isn't responding anymore. The internet connection is just fine.
Here is the code where I think it went wrong:
$(function(){
init();
console.log("Main Init Called")
});
function InitFilesRanksBrd() {
var index = 0;
var file = FILES.FILE_A;
var rank = RANKS.RANK_1;
var sq = SQUARES.A1;
for(index = 0; index < BRD_SQ_NUM; ++index) {
FilesBrd[index] = SQUARES.OFFBOARD;
RanksBrd[index] = SQUARES.OFFBOARD;
}
for(rank = RANKS.RANK_1; rank <= RANKS.RANK_5; ++rank) {
for(file = FILES.FILE_1; rank <= FILES.FILE_E; ++file) {
sq = FR2SQ(file,rank);
FilesBrd[sq] = file;
RanksBrd[sq] = rank;
}
}
console.log("FilesBrd[0]:" + FilesBrd[0] + " RanksBrd[0]:" + RanksBrd[0]);
console.log("FilesBrd[SQUARES.A1]:" + FilesBrd[SQUARES.A1] + " RanksBrd[SQUARES.A1]:" + RanksBrd[SQUARES.A1]);
//console.log("FilesBrd[SQUARES.C5]:" + FilesBrd[SQUARES.C5] + " RanksBrd[SQUARES.C5]:" + RanksBrd[SQUARES.C5]);
console.log(FilesBrd);
console.log(RanksBrd);
}
function init(){
console.log("init() called");
InitFilesRanksBrd();
}
In the inner for, the variable that you are comparing is rank, not file. It should be:
for(file = FILES.FILE_1; file <= FILES.FILE_E; ++file)
Because the rank variable isn't incrementing until the loop content end, but the loop content doesn't end because of the inner loop.

Global Variables in JavaScript to change within function

Hi I am trying to alter a global variable from within a function but it doesn't seem like this is going to work. Here is my JS:
var currentImg = 0;
var totalImg = 0;
var stored_year = 0;
var newYear = 0; //the variable i want to edit
$("a.work").click(function(){
var newYear = $(this).html(); // how I want it to be edited
console.log(newYear);
});
$("#next-button").click(function() {
if (currentImg == totalImg) {
currentImg = 0;
}
else {
currentImg++;
}
changeImg();
});
$("#previous-button").click(function() {
if (currentImg == 0) {
currentImg = totalImg;
}
else {
currentImg--;
}
changeImg();
});
function changeImg(galleryYear) {
if (galleryYear === stored_year) {
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
}
else {
currentImg = 0;
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
$("#gallery-type").html('<img id="gallery-switch" alt="Kyle Breitenbach Art Gallery Icon" src="images/gallery-icon.png" onClick="gallerySwitch('+window.newYear+')">');
stored_year = galleryYear;
}
}
t = 100;
d = 50;
function gallerySwitch(newYear){
$("#gallery-control-bar").fadeOut(t);
$("#gallery-image").fadeOut(t);
$("#info").fadeOut(t);
$(".gallery-viewer").fadeOut(t);
$('div.'+newYear).delay(t+d).fadeIn(t); // still not returning a number
} // other than 0.
function switchBack(){
currentImg = parseInt($(this).attr('id'));
alert(currentImg);
$(".gallery-viewer").fadeOut(t);
$("#gallery-control-bar").delay(t+d).fadeIn(t);
$("#gallery-image").delay(t+d).fadeIn(t);
$("#info").delay(t+d).fadeIn(t);
}
var navB = 0;
$("#mobileNav").click(function() {
if (navB == 0) {
$("#mobileMenu").fadeIn(t);
navB++;
}
else {
$("#mobileMenu").fadeOut(t);
navB--;
}
});
$(document).ready(function() {
changeImg(galleryYear);
});
How do I make variables global from within a function?
You can have multiple variables with the same name that will shadow each other. Don't add var when you want to use an existing variable.
$("a.work").click(function(){
newYear = $(this).html();
console.log(newYear);
});
Just not declare newYear again in the method if you want newYear to take the $('a.work') value:
$("a.work").click(function(){
newYear = $(this).html(); // how I want it to be edited
console.log(newYear);
});
You have put var newYear= in the function, this will have created a local version. Make it just newYear =
If you create a local variable with the same name as your global it will take precedence:
var newYear = 0;
$("a.work").click(function(){
var newYear = $(this).html(); // This is not your global newYear
}
You'll have to use the fully-qualified name:
var newYear = 0;
$("a.work").click(function(){
var newYear = $(this).html(); // This is not your global newYear
window.newYear = 'This is your global newYear';
}
But code with globals is already hard enough to maintain without duplicate names. I suggest you use unique names.

Issue while Accessing a Global variable in Javascript

I am unable to access NatArray[ ] in the second function, and u4count in the second function is coming as 0. What may be the reason?
<script type="text/javascript">
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1()
{
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check()
{
alert("coming here" + u4count + "natentry" + NatArray[0] );
}
</script>
Thanks in Advance
Works for me as excpected. The order you call your functions is important in this case:
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1() {
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check() {
alert("coming here " + u4count + " natentry " + NatArray[0]);
}
Check1();
Check();
As some answering users figured out is the unclosed inline comment bad but not the reason for your problem. Something about comments in inline-code
http://fiddle.jshell.net/r8sKf/
You can call this 2 functions in window.onload so it will call second function and also alert and NatArray[ ] value inside alert.
Try something like this:
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1() {
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check() {
alert("coming here " + u4count + " natentry " + NatArray[0]);
}
window.onload=function(){
Check1();
Check();
};
Here you go:
http://jsfiddle.net/R23eD/
You need to remove the <!-- from your script start. And you're also not calling the Check1() function to initialize the values

Categories