Global variable in jquery not giving output - javascript

I need to declare value in global variable that I pull from data attribute. But on test script I am able to print on console but when I use it on page its giving undefined in console. Here is the jquery script I came up with.
var PClevel;
$(document).ready(function() {
var array = [];
$(".proimg").slice(0,3).each(function() {
array.push($(this).data("pid"));
PClevel = ("["+array.join(",")+"]");
});
});
console.log(PClevel);
https://jsfiddle.net/wq3tqkzo/
Can anyone advise please why its not printing the output on live page. I have jquery library available on it. Or can anyone advise if I can have similar function in pure javascript.

You are logging the variable outside of the document ready. It will not be populated until the document ready runs, which will be after that console.log runs. Move it inside the doc ready.

Related

Jquery Variable Not Passing

I'm having an issue where I cannot seem to pass the variable "notes" into the placeholder of a form. More Info Below Code:
request.done(function(data) {
window.notes = data;
//document.write(notes);
});
request.fail(function() {
// document.write("fail");
});
$(document).ready(function(){
$('form').find("textarea").each(function(ev)
{
if(!$(this).val()) {
// document.write(notes); Says undefined?
$(this).attr("placeholder",window.notes);
}
});
});
The placeholder code works...if I use
$(this).attr("placeholder","test");
It works without problem as it should, but it will not if I try to use the var notes.
The setting of var notes works as well. If I uncomment the document.write("notes") I get the value I expect.
I have tried:
I originally started with Var notes = data; but moved to window.notes based on a suggestion by another question to make it global. Did not work. I also tried "forcing" the variable to be global by setting outside the function scope empty, but that didn't work either.. Is there something I'm missing?
Thanks!
Sorry I don't have much credit to comment . I just wanted to say that the document.ready function works on load at the starting of the page load while request.done or request.fail works after it so initially on load the window.notes is undefined.
And when you use the code document.write(notes) it gets defined and hence no error.

Function is not defined in javascript

can you help me?
I'm using a script in one file to call other function in another file, but I'm getting function is not defined. So I've start searching to fix this way but I didn't get any positive results. Check my code below:
index.html
$(document).ready(function(){
setInterval(function(){
lAs = new loadAsync();
}, 900);
});
js/plugins.js
function window.loadAsync() {
$(".loadAsync").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
}
So, what should I do to fix this problem? Thank you.
#edit:
<script src="js/plugins.js"></script>
I've already wrote this in index.html
First, your syntax is wrong. An identifier may not have a . in it. Just use loadAsync and it'll be global unless you've nested it in another scope.
You can also make the jQuery more efficient by calling .attr() with a callback instead of using .each().
Finally, it seems unlikely that you actually want to use new to invoke the function. I changed the code below to simply pass it as the callback to setInterval. I also declared the lAs variable properly.
function loadAsync() {
$(".loadAsync").attr("src", function(){
return $(this).attr("data-src");
});
}
var lAs;
$(document).ready(function(){
lAs = setInterval(loadAsync, 900);
});
And of course all this can be done easily without jQuery.
function loadAsync() {
for (const el of document.querySelectorAll(".loadAsync")) {
el.src = el.dataset.src;
}
}
var lAs;
document.addEventListener("DOMContentLoaded", function(){
lAs = setInterval(loadAsync, 900);
});
First of all, function window.whatever() {} is wrong (could you include the link of the SO thread where you saw that being used ?).
Since you are getting an error even without that, please make sure that:
1. loadAsync is declared in the global scope in the plugins file.
2. You are including js/plugins.js correctly. Go on and insert foo bar; in js/plugins.js and then check if you get a SyntaxError (while including it before the other JS file), if you don't, you are not correctly including it.

Passing Scope Through $(document).ready

Can someone explain to me why this doesn't work and show me how to make it work? I've tried creating a namespace and IIFEs functions but I cannot seem to get it.
$(document).ready(function() {
alert (hi);
});
$(document).ready(function() {
var hi = "hello"
});
Thank You!
When you do this:
$(document).ready(function() {
var hi = "hello"
});
You are creating a variable named hi that is local to that callback function. It is simply not accessible outside that function. This is a feature of the language.
You can declare the variable at a higher scope like this:
var hi;
$(document).ready(function() {
hi = "hello"
});
And, then the value of that variable will be available outside the scope, but you will not necessarily know when it gets the proper value because you won't know when the $(document).ready() callback is called unless you put your code inside that callback.
It really makes little sense to try to share a variable between two calls to $(document).ready(). It would make much more sense to just put the code inside the same $(document).ready() callback:
$(document).ready(function() {
var hi = "hello"
alert (hi);
});
Not Really Recommended
If you were going to try to share a variable between two calls to $(document).ready() (something I don't really recommend because it makes your code somewhat fragile), it can be done. Callbacks to $(document).ready() will be called in the order they are attached so you will have to order things appropriately:
var hi;
$(document).ready(function() {
hi = "hello"
});
$(document).ready(function() {
alert (hi);
});
This will make sure that the first $(document).ready() callback that sets the value of hi will be called first before the second one where you try to use the value.

TypeError: Result of expression 'printWindow' [undefined] is not an object

I'm trying to create hidden iframes in my page dynamically to load 3 other pages so that i can grab all the HTML and combine them into 1 in a new window.
However i'm stuck at this.
tHe frames are created fine.
But whenever the javascript runs to the part of
var printWindow="";
function openNewWindow()
{
printWindow = window.open("","");
printWindow.document.open();
printWindow.document.write(HTMLfromFrames);
printWindow.document.close();
}
i get this error:
TypeError: Result of expression 'printWindow' [undefined] is not an object.
but if i generate a button to call this function seperately, it works fine.
however i need it to run all in one click event
Anybody has any idea what's wrong?
Thanks!
It looks to me like a scoping problem. The scope of your printWindow object ends when openNewWindow returns; in other words, the variable only exists inside that function and disappears as soon as the function ends. Remove the var to make the variable available globally (considered bad form) or declare the variable elsewhere in your code and make sure it's available to openNewWindow when it executes.
oh i solved it. SOmehow i declared as a global var
then declare the obj earlier in the method.
printWindow = window.open("","");
still not sure why i can't declare it after i dynamically create my iframes.
Thanks for the help!:D

"Decompile" Javascript function?

[1] Ok, I don't even know how to call this, to be honest. So let me get some semi-pseudo code, to show what I'm trying to do. I'm using jQuery to get an already existing script declared inside the page, inside a createDocument() element, from an AJAX call.
GM_xmlhttprequest({
...
load:function(r){
var doc = document_from_string(r.responseText);
script_content = $('body script:regex(html, local_xw_sig)', doc).html();
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.innerHTML = script_content; // good till here
(function(sc){
eval(sc.innerHTML); // not exactly like this, but you get the idea, errors
alert('wont get here ' + local_xw_sig); // local_xw_sig is a global "var" inside the source
})(scriptEl);
}
});
So far so good, the script indeed contains the source from the entire script block. Now, inside this "script_content", there are auto executing functions, like $(document).ready(function(){...}) that, everything I "eval" the innerHTML, it executes this code, halting my encapsulated script. Like variables that doesn't exist, etc.
Removing certain parts of the script using regex isn't really an option... what I really wanted is to "walk" inside the function. like do a (completely fictional):
script = eval("function(){" + script_content + "};");
alert(script['local_xw_sig']); // a03ucc34095cw3495
Is there any way to 'disassemble' the function, and be able to reach the "var"s inside of it?
like this function:
function hello(){
var message = "hello";
}
alert(hello.message); // message = var inside the function
Is it possible at all? Or I will have to hack my way using regex? ;P
[2] also, is there any way I can access javascript inside a document created with "createDocument"?
Simply trying to access a local variable inside a function from outside of it is impossible due to scope. However, using closures you can absolutely accomplish this:
function hello(msg){
return function message(){
return msg;
}
}
alert(hello("yourMessage")()); // will alert "yourMessage"
Note exactly what's happening here. You are calling a function which returns a function, in which "yourMessage" is now defined inside its scope. Calling that inner closure the second time will yield that variable you set earlier.
If you are not familiar with closures in JS, I suggest you read this wonderful FAQ.
It's not possible that way. You can introspect object's properties (any function is an object), but not before you have created an instance with new operator.
Looking at your code sample, it seems that your approach is a bit messy – eval()'ing script blocks is something one should not do unless absolutely necessary (a situation I can't imagine).
In your example at
function hello(){
var message = "hello";
}
alert(hello.message); // message = var inside the function
you can in fact use hello.toString() to get the function source, like this:
alert(hello.toString().match(/var message = \"(.*)\";/));
You want to eval the script in global scope. Briefly it is,
// Evalulates a script in a global context
globalEval: function( data ) {
data = jQuery.trim( data );
if ( data ) {
if ( window.execScript )
window.execScript( data );
else if ( jQuery.browser.safari )
// safari doesn't provide a synchronous global eval
window.setTimeout( data, 0 );
else
eval.call( window, data );
}
}
Also check out Google's caja for secure external script evaluation.

Categories

Resources