Why is my variable undefined after I import it? - javascript

I have a function that gets the inner html of a div container.
function saveTab(el){
let saveTabContainer = document.getElementById(el);
module.exports.innerHTMLTabContainer = saveTabContainer.innerHTML;
}
If I console.log the variable in this file, it returns with the appropriate value.
However, when I import it using:
let {innerHTMLTabContainer} = require('../public/javascripts/saveTab');
the value becomes undefined.
I used
console.log(innerHTMLTabContainer);
in my file that imports the innerHTMLTabContainer variable but it prints out "undefined".

Related

how to access global variable from function in javascript

I am trying to access global variable from function, i want to call variable outside from inside function variable.This is what I tried.
Note: the query function should be work after click on query function from html drop down selection.
Thank you for helping.
HTML
<select name="myInput" id="choice1">
<li><option value="6011">apib_cadastral:bivel</option></li>
<li><option value="6012">apib_cadastral:burhchaura</option></li>
</select>
javascript
var layer_name;
function query() {
var text_value = document.getElementsByName('myInput')[0];
var layer_name = text_value.options[text_value.selectedIndex].text;
}
query();
var config = {
geojson: layer_name,
};
Remove the "var" inside the function. With that you define a new variable that exists inside the function.
You should change your code in this way.
Because, when you re-declare variable inside query() it will occupy another cell from memory with different address. And, variable inside config object cannot access it. It will access layer_name [first defined] which contains undefined value
var layer_name ;
function query() {
var text_value = document.getElementsByName('myInput')[0]
layer_name = text_value.options[text_value.selectedIndex].text;
}
query();
var config = {
geojson: layer_name
}
In addition to other answers, which correctly state that you should remove var from the variable declaration inside the query() function, you could change the function to return the value, rather than relying on shared/global state.
function query() {
var text_value = document.getElementsByName('myInput')[0];
return text_value.options[text_value.selectedIndex].text;
}
var config = {
geojson: query()
};
Note that this may have a performance impact depending on how many times you call query() as the return value would have to be computed each time, but it's worth considering from the perspective of alleviating the need for shared/global state.
Also note, consider replacing var with more modern const and let...
const when the variable is initialised and never needs to change.
let when the variable needs to change beyond initialisation.
function query() {
const text_value = document.getElementsByName('myInput')[0];
return text_value.options[text_value.selectedIndex].text;
}
const config = {
geojson: query()
};

How to make a js var in a function global to use it outside?

I want to make the "var id" in the function global. That i can use the value of it in the alert outside the function. Thats my code:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
}
alert(id);
</script>
You didn't specified what is your final goal or why are you trying to move id to a global scope, but you can do it by simple moving the var id (declaration) outside the function, then it will be global and accessible by all functions.
Obviously, the alert will show "undefined" since id only gets some value when the myFunctionGetCode() is called.
The code below shows this.
var id;
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
id = con+code;
console.log(id)
}
alert(id);
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
BUT if you want to throw the alert with the id value only when it gets some value then you should move the alert() inside the function. (You can still declare the id variable outside the function to let it global, or inside the function, as you currently have)
Open snippet to see:
//var id; -> You can still declare it here (as global)
function myFunctionGetCode() {
var code = getInputVal('code');
var con = "/";
var id = con+code; //or you can declare it here, but not global
alert(id);
}
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
From your sample code I guess that you do not want to make your value global, but that you want to return a value - after all you are doing an operation inside your function that calculates a value from certain inputs.
So you would use the return keyword, and call the function to get the value:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
return id;
}
alert(myFunctionGetCode());
</script>
As a rule you do not want to make function variables global, since this means the value can be changed anywhere in your script or website, and that might lead to side effects and unexpected values in your function. If you need to pass something in use function parameters (or read from a text input like in your case), if you want to give back a result use return.
Can you move the alert inside the function or return the "id" value from the function instead?
You can make the variable global by doing something like:
window.your_namespace.id = value;
and then access the variable in the same way:
value = window.your_namespace.id
but its best not to pass data around using the global namespace.
You have to make var id to property of window object then you can access the id out side the function.
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
window.id = 10;// Change to this
}
myFunctionGetCode();
alert(id);

why value is not changing of a `var` when it is in the scope of the function

just look at this question: What is the scope of variables in JavaScript?
in the answer which is accepted look at the point 3
according to him a will be 4 but now look at my function:
function JIO_compiler(bpo){ // bpo means that " behave property object " and from here i will now start saying behave property to behave object
var bobj = bpo, // bobj = behave object
bobj_keys = Object.keys(bobj), // bobj_keys = behave object keys. This willl return an array
Jcc_keys = Object.keys(JIO_compiler_components), // Jcc = JIO compiler components
function_code = ""; // get every thing written on every index
if (bobj.hasOwnProperty('target') === false) { // see if there is no target defined
console.log("No target is found"); // tell if there is no target property
throw("there is no target set on which JIO-ASC will act"); // throw an error
};
if (bobj.hasOwnProperty('target') === true) {
console.log("target has been set on "+ bobj['target']+" element"); //tell if the JIO-ASC has got target
function x(){
var target_ = document.getElementById(bobj['target']);
if (target_ === null) {throw('defined target should be ID of some element');};
function_code = "var target="+target_+";";
console.log("target has successfully been translated to javascript");//tell if done
};
};
for(var i = 0; i < bobj_keys.length; i++){
if(bobj_keys[i] === "$alert"){ // find if there is $alert on any index
var strToDisplay = bobj[bobj_keys[i]];
var _alert = JIO_compiler_components.$alert(strToDisplay);
function_code = function_code+ _alert;
};
};// end of main for loop
alert(function_code);
new Function(function_code)();
};
well it is big... but my problem is in the second if statement. now according to the accepted answer the value of function_code should change according to what is instructed. but when at last i alert the function code then it alert blank. i mean it should alert at least var target = something ; and the last console.log statement of this if statement is not showing text in the console.
so what is wrong in this ?
You're setting function_code inside the definition for function x(), but x() is never called. function_call won't change until you make a call to x.
thats because your variable is inside the function scope, you need to define your variable outside of it, as
function_code = "";
function JIO_compiler(bpo){
....
};// end of main for loop
//call the function
JIO_compiler(some_parameter);
//alert the variable
alert(function_code);
you need to call the function JIO_compiler() first so that the appropriate value is set to function_code variable from JIO_compiler() function, as

Using Meteor: strange behavior using helper functions in template helpers

I'm getting some strange behavior using Meteor.
I'm in a template helper defined in client/ . The function "percentCompleted" is a helper function defined in client/lib/helper.js. When I call "percentCompleted" in the return line, percentCompleted completes normally. However, whenever I call percentCompleted outside of the return line, the console logs an error that the function "percentCompleted" is undefined. Why would a helper function be defined or undefined depending on where in the template helper it is called??
This works:
Template.chapter.percentComplete = function(){
if(_.isEmpty(this))
return "";
return percentCompleted(this)
}
This throws an error with "percentCompleted" undefined.
Template.chapter.percentComplete = function(){
if(_.isEmpty(this))
return "";
var percentCompleted = percentCompleted(this)
return percentCompleted;
}
The problem is that you have a local variable called percentCompleted which shadows the function percentCompleted. Rename the variable to something else and it should work.
Note that local variable declarations in Javascript are hoisted to the top of the function, so it behaves as if you wrote:
Template.chapter.percentComplete = function(){
var percentCompleted;
if(_.isEmpty(this))
return "";
// Here we attempt to call the function in the percentCompleted
// var, but that is undefined.
percentCompleted = percentCompleted(this)
return percentCompleted;
}

update numeric variables when changed in prototype function

I am trying to add two numbers but for some reason I am not getting NaN.
Following is the sample code
function Slider(container, nav, pagination){
this.articleWidth = this.div.width() + 20;
this.divWidth = 960;
this.articleMargin = 0;
this.pageMargin = this.divWidth + this.articleMargin
}
Slider.prototype.articleTransition = function(pageNum){
var currArticle = pageNum -1;
this.articleMargin = currArticle * this.articleWidth;
this.container.animate({'margin-left': -this.articleMargin});
}
Here everything works as expected. But this.pageMargin is always 0 even though this.articleMargin's value is changing in the articleTransition function. And when I console log this.pageMargin is says NaN. I am trying to change value of this.articleMargin's value, everytime it is being invoked in the function.
Here is how I am invoking the function in my HTML.
var slider = new Slider($('div#contentSleeve'), $('a.anav'), $('ul#scroller li'));
slider.pagination.live('click', function(){
slider.articleTransition($(this).data('num'));
});
I guess that's because you are calling in anonymous function scope. Try like this:
slider.articleTransition.call(slider, $(this).data('num'));
I did fix this. All I had to do was to create a global variable that will store the value of both pageMargin and ArticleMargin.

Categories

Resources