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