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.
Related
I am trying to reference a global variable's value using my array output but I am unsure how to do that. I want to make these references outside the function as I will need to create many functions that use these variables.
Ignore the PFGetValue part, I need to use that for the program I am coding in. There will be many more dd_meg_x but this is just to show you what I'm doing. Currently, this will return the correct the text "dd_meg_x" - but I want to then reference the variable defined above. So for example, if the result in the array is dd_meg_1, I want the output to be "M Energy 16"
var dd_meg_1 = "M Energy 16";
var dd_meg_2 = "Ulra Energy";
var dd_meg_3 = "Another Option Here";
function canOrderMeg1() {
var brand = "meg";
var arrayLength = 21;
var canArray = [];
var variableName;
for (i = 0; i <= arrayLength; i++) {
variableName = ("dd_" + brand + "_" + i);
if (PFGetValue(variableName) === "Y") {
canArray.push(variableName);
}
canArray.join(", ");
}
return canArray[0];
}
function canOrderMeg2() {
var brand = "meg";
var arrayLength = 21;
var canArray = [];
var variableName;
for (i = 0; i <= arrayLength; i++) {
variableName = ("dd_" + brand + "_" + i);
if (PFGetValue(variableName) === "Y") {
canArray.push(variableName);
}
canArray.join(", ");
}
return canArray[1];
}
Try
return eval('string output code');
So this would look like
return eval(array output);
Try this:
var dd_meg_1 = "M Energy 16";
var dd_meg_2 = "Ulra Energy";
var dd_meg_3 = "Another Option Here";
function canOrderMeg1() {
return ["dd_meg_1", "dd_meg_2", "dd_meg_3"];
}
for(let i = 0; i < canOrderMeg1().length; i++){
if(typeof canOrderMeg1()[i] !== "undefined") {
console.log(window[canOrderMeg1()[i]]);
}
}
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.
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Constructors in Javascript objects
im trying to learn how to create class's in javascript. I found that is very diffuclt for me to understand it.
now, i want to know if is possible to create a constractor in javascript, like we can do in c# or other programming languages.
i tried few things:
way 1:
function SiteProfile(_url) {
this.url = "";
this.name = this.ExtractNameFromURL();
}
SiteProfile.prototype.ExtractNameFromURL = function () {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
way 2:
function Site() {
this.url = "";
this.name = "";
this.Site = function (_url) {
this.url = _url;
this.name = this.ExtractNameFromURL();
}
this.ExtractNameFromURL = function () {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
}
both of class's should take a URL, and just get the name from him with out the www. or the .com
i want to know if i can design a class, that i can create an instance like so:
var site = new SiteProfile("www.google.co.il");
document.write(site.name); // becuse, this do nothing
(sorry for my english)
You're real close. The problem with your first form is simply that you are not setting the url property with the _url parameter.
function SiteProfile(_url) {
//change the line below to:
//this.url = _url;
this.url = "";
this.name = this.ExtractNameFromURL();
}
SiteProfile.prototype.ExtractNameFromURL = function() {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
var site = new SiteProfile("www.google.co.il");
document.write(site.name); // with the change above, this will behave as expected
Here's the fiddle for the first form: http://jsfiddle.net/BCnfx/
The problem with the second form is two-fold. The main function should be called "SiteProfile" if you still want to instantiate it as such. The second problem is that you need to initialize the url property by passing in the url to the Site method.
//function below should be called "SiteProfile", not "Site"
function Site() {
this.url = "";
this.name = "";
this.Site = function(_url) {
this.url = _url;
this.name = this.ExtractNameFromURL();
};
this.ExtractNameFromURL = function() {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
};
}
//now instantiate like this instead.
var site = new SiteProfile();
site.Site("www.google.co.il");
document.write(site.name); // with the changes above, this will behave as expected
Here's the fiddle for the second form: http://jsfiddle.net/BCnfx/1/
in your first example:
function SiteProfile(_url) {
this.url = _url;
this.name = this.ExtractNameFromURL();
}
then you will be able to do :
var site = new SiteProfile("www.google.co.il");
document.write(site.name);
I am trying to make a debugger that will be dynamiaclly created with some variables. The names on the left div need to show a div for the corresponding variables Description,Variable ID, and initial Value as well as another div that will show history and lock status when variables are updated later. Where I am having trouble is properly adding the show/hide to the dom I think. Everything starts hidden and then when I click a name the Variables for that name show up but the next click doesn't hide the values from the former. Also any cleanup/optimization advice?
<script type="text/javascript">
var variableIDArray = {};
function loadVariables(variables) {
if (typeof variables != "object") { alert(variables); return; }
var namearea = document.getElementById('namearea');
var description = document.getElementById('description');
var varid = document.getElementById('varid');
var initialvalue = document.getElementById('initialvalue');
var valuelock = document.getElementById('valuelock');
for (var i = 0; i < variables.length - 1; i++) {
var nameDiv = document.createElement('div');
nameDiv.id = variables[i].variableID + "namearea";
nameDiv.className = "nameDiv";
nameDiv.onclick = (function (varid) {
return function () { showvariable(varid); };
})(variables[i].variableID);
nameDiv.appendChild(document.createTextNode(variables[i].name));
namearea.appendChild(nameDiv);
var descriptionDiv = document.createElement('div');
descriptionDiv.id = variables[i].variableID + "description";
descriptionDiv.className = "descriptionDiv";
descriptionDiv.appendChild(document.createTextNode("Description : " + variables[i].description));
description.appendChild(descriptionDiv);
var varidDiv = document.createElement('div');
varidDiv.id = variables[i].variableID + "varid";
varidDiv.className = "varidDiv";
varidDiv.appendChild(document.createTextNode("Var ID : " + variables[i].variableID));
varid.appendChild(varidDiv);
var initialvalueDiv = document.createElement('div'); ;
initialvalueDiv.id = variables[i].variableID + "initialvalue";
initialvalueDiv.className = "initialvalueDiv";
initialvalueDiv.appendChild(document.createTextNode("Initial Value : " + variables[i].value));
initialvalue.appendChild(initialvalueDiv);
var valuelockDiv = document.createElement('div');
valuelockDiv.id = variables[i].variableID + "valuelock";
valuelockDiv.className = "valuelockDiv ";
valuelockDiv.appendChild(document.createTextNode("Value : " + variables[i].value));
valuelockDiv.appendChild(document.createTextNode("Lock : " + variables[i].locked.toString()));
valuelock.appendChild(valuelockDiv);
variableIDArray[variables[i].variableID];
}
};
function showvariable(varid) {
for (v in variableIDArray)
hide(variableIDArray[v]);
show(varid + "description");
show(varid + "varid");
show(varid + "initialvalue");
show(varid + "valuelock");
}
function show(elemid) {
document.getElementById(elemid).style.display = "block";
}
function hide(elemid) {
document.getElementById(elemid).style.display = "none";
}
Yes. jQuery. Will reduce your code to about 6 lines. :) http://jquery.com