can't get jqPlot chart to show line from Variable - javascript

I'm using jqPlot to plot some points in my webApp, so I'm trying this:
var plot10 = $.jqplot ('heightChartDiv', [[3,7,9,1,5,3,8,2,5]]);
and it works fine, I this exact chart here
but when I take it out, to give it a value, like so:
$(document).ready(function(){
var serie1 = [[3,7,9,1,5,3,8,2,5]];
}
function doGraph(){
var plot10 = $.jqplot ('heightChartDiv', serie1);
}
It doesn't work. am I declaring the variable wrong? please HELP!
~Myy

Your variable scoping is all off. The variable serie1 has local scope to the anonymous function defined in $(document).ready event. Read up on javascript scope here and here.
Perhaps something like this:
// the document ready will fire when the page is finished rendering
// inline javascript as you've done with your doGraph will fire as the page renders
$(document).ready(function(){
// first define graph function
// make the series an argument to the function
doGraph = function(someSeries){
var plot10 = $.jqplot ('heightChartDiv', someSeries);
}
// now call the function with the variable
var serie1 = [[3,7,9,1,5,3,8,2,5]];
doGraph(serie1);
}
EDITS IN RESPONSE TO COMMENT
See this below example:
$(document).ready(function(){
var a = 1;
someFunc = function(){
var b = 2;
alert(a);
}
someFunc(); // this works
alert(b); // this produces an error
});​
Here the variable a is considered global to the function someFunc. A variable declared in someFunc, though, does not persist outside of it.

Related

Why doesn't document.ready work in this case?

If I use this:
<script>
$(document).ready(function() {
if (window.localStorage.getItem('createTicket')) {
var createTicketInfo = JSON.parse(window.localStorage.getItem('createTicket'));
}
});
</script
I see an error in the console:
Uncaught ReferenceError: createTicketInfo is not defined
But if I remove document.ready:
<script>
if (window.localStorage.getItem('createTicket')) {
var createTicketInfo = JSON.parse(window.localStorage.getItem('createTicket'));
}
</script>
Everything is ok:
Why?
It's because, in the first example, createTicketInfo is only visible within the callback (function) of ready.
function test() {
var boo = "Hi! I'm boo.";
// ...
console.log(boo); // visible here
}
test();
console.log(boo); // not visible here (even if we call test first)
In the second example, createTicketInfo is not wrapped in a function, thus it is global (visible everywhere).
if(true) {
if(true) {
if(true) {
var foo = "Hi! I'm foo.";
// ...
console.log(foo); // visible here
}
}
}
console.log(foo); // visible here too (because javascript doesn't have block scopes)
Always put in mind that javascript has function scopes, but not block scopes.
Note: As mentioned by #nnnnnn in the comment bellow, ECMAScript 6 introduced a new way of declaring variables using let or const that respect block scopes. So:
if(true) {
let zoo = "Hi! I'm zoo.";
// ...
console.log(zoo); // only visible inside this block
}
console.log(zoo); // not visible here
Something else isn't right in another section of your code.
Look at this fiddle I created.
It accurately reads and writes the value. Exactly the same code:
https://jsfiddle.net/nxka5h7y/2/
<head>
<script src = "https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
window.localStorage.setItem('createTicket', '{"a":"1"}');
$(document).ready(function() {
if (window.localStorage.getItem('createTicket')) {
var createTicketInfo = JSON.parse(window.localStorage.getItem('createTicket'));
console.log(createTicketInfo);
} else { console.log("none"); }
});
</script>
</head>
<body>
<script>
</body>
The only thing I added, was actually setting the createTicket item in localStorage, just to ensure the "if" statement inside document/ready will pass.
My semi-logical guess is that JSON stored in createTicket is malformed, based on how it was set (which is not shown in your example.) I don't really think that's the issue. But, the fact is your example produces accurate results in jFiddle. Look elsewhere in your code. Like, the part where you actually set the createTicket. Or that your jQuery is actually included, or something silly like that.

How to return variable value from jquery event function?

Can I get value from jquery event function?
I want to get something like this:
function Init() {
var my_variable = $some_object.click(function() {
var my_variable = 'value';
return my_variable // I need to get the variable value from click event
// but I don't know ways to do it
});
console.log(my_variable); // I want to have possibility to use the value here
}
No.
The function that sets the event handler will have finished running before the event handler runs.
No, you can't do that. You can only capture the value in a variable defined outside the scope of your handler:
function Init() {
var my_variable = '';
$some_object.click(function() {
my_variable = 'value';
});
console.log(my_variable); //Prints empty string
$some_object.trigger('click');
console.log(my_variable); //Prints 'value'
}
The answer to your question is No!. You cannot return a value from event handler.
Now next thing which made you curious is how to get some data which comes from the event handler itself. This is where event propagation comes and passing some data along with that.
Checkout below fiddle which shows how data which was created in event handler of button click, is being passed for any custom purpose.
http://jsfiddle.net/kowmwq9j/
Below is simple html and understandable javascript code
<div id='parent'>
<button id='test'>CLick</button>
</div>
var a=document.getElementById('test');
a.addEventListener('click', function(){
var str='sample';
//creating a custom event with name 'build' and passing object as data
var event = new CustomEvent('build', { 'detail': str });
//dispatches the event which invokes the affected listeners
this.dispatchEvent(event);
})
//Listening for 'build' event
document.getElementById('parent').addEventListener('build', getData, true);
function getData(e){
alert(e.detail);
}
Links shared which can help one to understand the concept. dispatchEvent & createCustomEvent .Hope that helps to answer your question!
Added some comments & links which will help those who aren't aware of the functions & behavior used.
If I understand the question maybe you can do something like this...
Variable = 5 is used within 2 functions...each function does something with it's value...
the last function uses the totals of the first 2 functions and again does something.. So the point is that u can access the 2 totals variables and use them in the third function... As long as you set your function variable as global...so don't put VAR in front of it. If you set var in front of it u are saying that your variable is private for that function...
Change the value of the original variable and all the values changes ....
variable = 5; // this is a global variable
source = $('div#een h2'); // put your source here
function Init(){
source.on('click', function(){
Total1 = variable * 2;
console.log(Total1); // It outputs 10
});
};
Init();
function Init2(){
source.on('click', function() {
Total2 = variable * 5;
console.log(Total2); // It outputs 25
});
};
Init2();
function Init3(){
source.on('click', function() {
Total3 = Total1 * Total2; // here we use the 2 Totals...
console.log(Total3); // outputs the Total of both totals... should be 250
});
};
Init3();

Calling a JavaScript function from another function in a different JS file

I have a web page displaying an HTML5 canvas. When the web page loads, the following JavaScript function is called:
window.onload = function(){
var sources = {};
sources[0] = document.getElementById("building").src,
sources[1] = document.getElementById("chair").src,
sources[2] = document.getElementById("drink").src,
sources[3] = document.getElementById("food").src,
sources[4] = document.getElementById("fridge").src,
sources[5] = document.getElementById("land").src,
sources[6] = document.getElementById("money").src,
sources[7] = document.getElementById("oven").src,
sources[8] = document.getElementById("table").src,
sources[9] = document.getElementById("van").src,
sources[10] = document.getElementById("burger").src,
sources[11] = document.getElementById("chips").src,
sources[12] = document.getElementById("drink").src,
sources[13] = document.getElementById("franchiseFee").src,
sources[14] = document.getElementById("wages").src,
sources[15] = document.getElementById("admin").src,
sources[16] = document.getElementById("cleaners").src,
sources[17] = document.getElementById("electricity").src,
sources[18] = document.getElementById("insurance").src,
sources[19] = document.getElementById("manager").src,
sources[20] = document.getElementById("rates").src,
sources[21] = document.getElementById("training").src,
sources[22] = document.getElementById("water").src,
sources[23] = document.getElementById("burger").src,
sources[24] = document.getElementById("chips").src,
sources[25] = document.getElementById("drink").src,
sources[26] = document.getElementById("creditors").src,
sources[27] = document.getElementById("electricity").src,
sources[28] = document.getElementById("food").src,
sources[29] = document.getElementById("hirePurchase").src,
sources[30] = document.getElementById("loan").src,
sources[31] = document.getElementById("overdraft").src,
sources[32] = document.getElementById("payeTax").src,
sources[33] = document.getElementById("tax").src
loadImages(sources, drawImage);
drawGameElements();
drawDescriptionBoxes();
};
This function loads some images from the hidden section of the HTML into the JavaScript, and draws them to the canvas by calling the 'drawImage()' function on each image in the 'sources' array. It then calls the 'drawGameelements();' function, which draws a few more things to the canvas, and finally, I then want to call the 'drawDescriptionBoxes()' function.
This function however, is in a separate JS file to the rest of the code, and when I view the page in a browser, although 'loadImages()' and 'drawGameElements()' are called, and draw what they're supposed to to the canvas, I get an error in the console saying:
ReferenceError: drawDescriptionBoxes is not defined
which I assume means that I haven't referenced the function correctly, since it's not in the same file as where I'm calling it.
What I'm wondering is how do I call this function from the other file? Would it be something like: filename.js.drawDescriptionBoxes ?
There's really two possibilities why the drawDescriptionBoxes function is undefined.
1) It's out of scope
In JavaScript, variables exist in some sort of scope. This maybe global, such as:
<script>
var foo = 123; //foo can be referenced anywhere, it's global!
</script>
Or scoped within another block of code:
function myFunc()
{
var bar = function () //bar can only be accessed within myFunc
{
};
};
//bar() here is undefined
There's a possibility your drawDescriptionBoxes function is not in the global scope.
2) It's not yet defined when your code runs
It's also possible you have some code like this:
File 1
<script>
var result = someFunc(123);
</script>
File 2
<script>
function someFunc(x)
{
return x * 2;
}
</script>
If File 2 gets included after File 1, someFunc doesn't yet exist when file 1 is run. You can get around this by running everything after the document fully loads, using event handlers. If var result = someFunc(123); was run in the onload event, it would work fine regardless of what file someFunc was defined in.
Hope this helps!
if drawDescriptionBoxes is defined as a global function, such as
function drawDescriptionBoxes() {
}
then the fact that it is not found means that the javascript file containing it did not load. Show how you include this file in html and how the function is defined.

Reaching an Object's Property

In my application I have an object with several properties that get set in various places in the application.
In one of my prototype functions I have a function that runs in intervals to update a timer, and in that function the property (this.)theTime should be set. The problem is that this doesn't happen, and I guess the reason is that this.theTime points to the function itself instead of the object.
Below is two versions of my code, and neither of them works. Any tips for me?
// 1.
function changeTime() {
this.theTime = setTime(time);
time.setSeconds(time.getSeconds()+1);
p1.html(this.theTime);
}
interval = setInterval(changeTime(), 1000 );
// 2.
function changeTime(theTime) {
theTime = setTime(time);
time.setSeconds(time.getSeconds()+1);
p1.html(theTime);
}
interval = setInterval( function() { changeTime(this.theTime); }, 1000 );
...
Too make it more clear, the function above updates a timer (eg. 00:00:01 -> 00:00:02) every second, and I want this.theTime to be updated with the time.
When the timer stops (which happens in another prototype function) I want to be able to see what time the timer stopped on, but as it is now this.theTime is the default value, which means that the function above doesn't update the objects property. Instead this.theTime in the function above must be a local variable.
NOTE: setTime() is another function that exists in the same prototype function as the function above.
Well when you use this in some function this is referencing to the object which actually the function is. Here:
function myF() {
this.var = 'hey';
}
You can reach var using this (myF as a constructor function):
var obj = new myF();
alert(obj.var);
Or here:
function myF2() {
if (typeof this.var === 'undefined') {
this.var = 0;
} else {
this.var += 1;
}
alert(this.var);
}
Here var again is a property of myF2 (which as I said is not just a function because in JavaScript functions are objects).
Each time you call myF2 this.var is going to be incremented and alerted (just in the first call it's going to be initialized).
In the second function (anonymous function using in the second setInterval) you're doing the same.
One solution is to make theTime global in both cases so you don't need to use:
this.theTime
So the result can be something like this:
var theTime = 0, interval;
function changeTime() {
theTime += 1;
document.body.innerHTML = theTime;
setInterval
}
interval = setInterval(changeTime, 1000 );
http://jsfiddle.net/u3EuC/
You can verify easily by writting a
debugger;
to set a breakpoint in your functions. Then it may be pretty easy to find your problem.
You are correct in your assumption that there's something wrong with your this keyword. this in JavaScript is a bit tricky, so using it in functions (especially with setTimeout or setInterval is risky.
What you want to do is save the value of this when you create the function.
Here's more information: http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/
Maybe these comments will direct you to the right way
var theTime; // global variable
function changeTime() {
theTime = setTime(time); // theTime is global variable declared above (accesible from anywhere)
// var myTime = setTime(time); // myTime is local variable
time.setSeconds(time.getSeconds()+1);
p1.html(theTime);
}
interval = setInterval(changeTime, 1000 ); // no braces
Jason, after your clarification, I believe it is better to provide you whole new answer trying to explain this statement in JS as good (and simple) as possible. I hope it helps.
<html>
<body>
<div id="output1"></div>
<div id="output2"></div>
<script>
// theTime is undefined in global scope
function obj(target) {
var theTime = 0;
var that = this; // var means "private"
this.changeTime = function() { // here "this" points to obj and means "public"
theTime++; // no var => outer scope = obj scope
// here "this" points to changeTime function, not to obj!
// "that" points to obj, you may use that.theTime
document.getElementById(target).innerHTML = theTime;
}
}
var o1 = new obj("output1");
var o2 = new obj("output2");
setInterval(o1.changeTime,1000); // update output1 content every second
setInterval(o2.changeTime,500); // update output2 content twice a second
</script>
</body>
</html>

jQuery global selection "cache"

I don't think I'm the first one to run into this issue but I haven't find a way to search for this without getting results that have nothing to do with the issue.
I adopted the not so extended good practice of "caching" repetitive jQuery selections into vars like var element = $('#element'); to prevent "DOM pool searching" for every repeated use of the element
The problem I'm having is that now I'm doing this caching inside a function. Something like:
function functionname (id) {
var id = $('#'+id);
//extra stuff
}
I'm not expert in variables scopes but I'm not being able to do
functionname ('some-div-id');
some-div-id.dialog('open');
So I'm pretty sure it's because the variable created inside the function is not accesible outside the function itself.
Then I came up with
function functionname (id) {
window.id = $('#'+id);
//extra stuff
}
but if I try to do window.some-div-id.dialog('open'); I get TypeError: 'undefined' is not a function
What am I missing? I'm sure it's a small dumb thing but I'm missing it just in front of my eyes.
Thanks
EDIT
Thanks everyone but you're missing something.
The code suggestions are missing the fact that the inside "global" variable name is dynamic:
var CACHEobject = {};
function doSomething (NAMEHERE) { //note the function parameter
CACHEobject.NAMEHERE = $('#'+NAMEHERE);
}
So the idea is that the function creates a javascript variable with the same name that the #element_id. If I pass a name to the function it should select the html id with that name and "cache it" to a global variable with the same name:
doSomething('myDialogOne'); doSomething('myDialogTwo');
so I can later do
CACHEobject.myDialogOne.dialog('open'); CACHEobject.myBox.dialog('close');
This is what you want (based off the edit):
var CACHEobject = {};
function doSomething(id) {
CACHEobject[id] = $('#' + id);
}
Your idea is fine. Just set up an object for that. Here's an example using STASH as the caching object:
<html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var STASH = {};
$(document).ready(function(){
// stash your elements
STASH.item = $('#item');
STASH.otherItem = $('#otherItem');
// do stuff to them
STASH.item.css({
color: '#f00'
}); // sets #item to red
alert(STASH.otherItem.text()); // alerts foo
});
</script>
<style></style>
<body>
<div id="item">bar</div>
<div id="otherItem">foo</div>
</body>
</html>
window.some-div-id.dialog('open');
is interpreted as:
window.some - div - id.dialog('open');
i.e. subtracting, which causes three undefined variables, one of which is id.dialog which causes an error when trying to be executed as a function.
For special characters, use:
window["some-div-id"].dialog('open');
And to define:
window[id] = $("#" + id);
Anyhow, I would not advise you to use global variables. You'd better overwrite the jQuery function to implement caching (using an object with the selector as key and the matched element as value).
You could just declare the variable outside the function.
var $foo;
function some_function(id) {
$foo = $('#' + id);
}
function setDialog(selector) {
window.$dialogElem = $(selector);
//window.dialogSelector = selector;
}
var id= 'mensajes';
setDialog('#'+id);
window.$dialogElem.dialog();
//$(window.dialogSelector).dialog();
commented stuff is an alternative that takes less memory. But why the hell use window?? check this fiddle for various simple techniques.

Categories

Resources