Converting javascript function to global variable - javascript

I've been struggling to convert a JavaScript function to a global variable.
I've got 2 files in total that are basically part of the entire function, here is the JavaScript function.
<script type="text/javascript">
$.get("banner1.php", function(getbannerlink1) {
$("#banner1").load(getbannerlink1+ " #productImage");
// var window.bannerlink1=getbannerlink1; (this doesn't want to work)
});
<script>
Basically banner1.php selects ONE random URL out of an array, and echoes the URL. This JavaScript then gets the URL, and then does a .load() function of that URL and gets the #productImage class from that URL, basically it gets the product image from the random URL. That works all good. Now I need to convert the getbannerlink1 variable to a global variable, because I would like to use the link outside of this function as well.
I've tried using the following just before closing the function:
var window.bannerlink1=getbannerlink1;
but this is just destroying the function altogether :/
What am I doing wrong?

var window.bannerlink1 is a syntax error. var should only be used with variable identifiers, which may not contain a period.
You want to set a property of window, not declare a new variable name, so just drop the var.

Drop the var
window.bannerlink1 = getbannerlink1;
Ideally you would avoid using a lot of globals and use a global namespace to hold the values.

Related

In JavaScript, how do I get the URL of the JavaScript file, not the location URL?

I would like to use a query string parameter so that way I can specify the name of a DOM element.
I have some code that requires the height of the header and I would like that code to work for any theme. Only at times the header uses the <header> tag, at times it has a specific identifier, at times it is a specific class... to be able to reuse that code over and over again, I'd like to include it in a way such as:
<script src="https://www.example.com/js/my-script.js?c=header"></script>
What I want to be able to do is get the "?c=header" part from that JavaScript URL to send search a DOM object with jQuery(".header"). Do we have a way to know the URL of the JavaScript itself from the JavaScript being executed?
Obviously, I know of window.location.href and that's not the URL I'm looking for.
As mentioned by #Kaiido in a comment, there is the document.currentScript parameter that gives you access to the <script> tag which is currently running. Only there is a small trick to it, that parameter is defined on the first pass, not when executing functions within your script.
So what one can do is save that information, or at least what you need from that object, in the global scope or a static in your object.
In my case, I just did the following:
// Script to tweak things on many websites
var this_script_url = document.currentScript.src;
jQuery(document).ready(function()
{
// at this point: "document.currentScript === null"
var qs = this_script_url.split("?", 2);
if(qs && 2 == qs.length)
{
... // handle qs[1] which is the query string (a=1&b=3&...)
}
});
Please make sure you don't use a global name that's too generic. It should include the name of your script or abbreviation thereof. Otherwise you are likely to clash with another script's global.
Now if you have a prototype object, I would suggest you use a static member instead of a global.
var my_class = {};
my_class.script_url = document.currentScript.src;
// and later you can reference it directly as in:
url = my_class.script_url;
This way you are more likely to avoid clashing problems (the only thing that needs to be changing in case of a clash is the name my_class).
At this point, the ES5 or ES6 class keyword does not offer you to create variables.

JSON/AJAX and local variables in JavaScript functions

Working with JSON for the first time, I'm trying to call strings stored in a JSON file like this:
var getText = function(pat,id){
$.getJSON('assets/brospeak.json',function(js){
$('#pim1').append(js.pat.id);
});
}
So my intent is that pat and id get passed to getText when it's called to find the string. The problem is, the local variables in the line $('#pim1').append(js.pat.id); aren't getting called properly, so basically every time I call getText it looks for myfile.pat.id instead of, say, myfile.pattern.a. It works fine when I do just the getJSON part and explicitly tell it where the strings are.
The heck am I doing wrong?
Use js[pat][id] instead if the property name is dynamic:
var getText = function(pat,id){
$.getJSON('assets/brospeak.json',function(js){
$('#pim1').append(js[pat][id]);
});
}

Is it possible to concatenate a function input to text of another function call?

Firstly appologies for the poor title, not sure how to explain this in one line.
I have this Javascript function (stripped down for the purpose of the question)...
function change_col(zone){
var objects= zone1227.getObjects();
}
I am passing in an integer into the function. Where I have "zone1227", I want that 1227 to be the integer I pass in.
I've tried this;
var zonename = "zone" + zone;
var objects= zonename.getObjects();
but that doesn't work.
Is this possible? The functions do exist for every possible integer passed in, but I was hoping to keep the code compact rather than a long list of if statements with hardcoded function names.
Since zone1227 is apparently a global variable, it can also be written as window.zone1227 or as window['zone1227']. This means that you can achieve what you describe, by writing this:
function change_col(zone){
var objects= window['zone' + zone].getObjects();
}
Nonetheless, I agree with Interrobang's comment above. This is not a good way to accomplish whatever it is that you really want to accomplish. You should not be referring to global variables via strings containing their names.
No, you cannot refer to a variable with the value of a string, nor can you concatenate anything onto a variable name. EDIT: turns out you can. You still shouldn't.
Yes, you can avoid using a long hard-coded if/elseif sequence: use an array.
Then you can say this:
function change_col(arr, i)
{
var objects= arr[i].getObjects();
}
And the call would be something like:
change_col(zone, 1227);

Javascript getVariableName

This is my first post.
I'm trying to do some basic meta-programming with javascript, and I was wondering if there is a way of get the id of a particular object and with that id, access to the variable name, or get simply the variable name of a particular object. I wanna recreate a situation in which you first create every single html in a web page, and append to some of the html tags events associated to a particular class -example class Person-. for example: Supposed the next code:
var someFunction = function(someText){alert(someText);}
function SomeClassFunction(){
this.aClassFunction = someFunction;
}
var aVariableName = new SomeClassFunction();
and in the HTML code suppose I have the next piece of code.
<html>
<head>
<title></title>
</head>
<body>
<div onclick="aVariableName.aClassFunction('Some text to show in alert');">
</div>
</body>
</html>
Then, as you may notice the onclick event uses the aVariableName I created before, but because I first create the name of the variable and then append the name in the code cause I knew aVariableName was the name of that object. What I wanna do or implement is to create the text above in html without know the variable name of an specific object. I have surfed on the net but, unfortunately I haven't found anything about it.
i dont know how to get the name of a variable from the code its self without doing a whole load of work parsing stuff, which will get messy, and i'd shoot someone for this.
var someValue;
var foo = function() { someValue; }
alert((foo + '')); // this is now a string, use substr to extract variable name
You know you can set events like this in javascript someElement.onclick = someFunction so you dont really need to know the name of the variable if all you're doing is setting an event handler.
In general, no — you can't get the name of a particular variable or its "id" either.
If you really want to, it may be possible to do Bad Things with exceptions and stack traces to get that information… But I don't know off the top of my head how to do that.
Edit: I assume that, by “variable ID”, you mean “a unique identifier for the object referenced by that variable”, like Python's id builtin:
>>> x = {}
>>> y = z = {}
>>> (id(x), id(y), id(z))
(123, 567, 567)
I'm not 100% sure that I understand your question correctly in regards to meta-programming, but typically you would attach an event handler to the click event of the DOM element, then you can examine properties of the element within the handler.
There are a couple things in JavaScript that facilitate meta-programming: eval will let you interpret arbitrary code, so you can build a string of code and eval it. The security concerns are numerous. You can also access properties of an object by index or by name, e.g.
aVariableName.aClassFunction
is the same as
aVariableName["aClassFunction"]
Hope that helps.

Convert location.href URL to Anchor link

Exists any JavaScript or Objective-C method to convert a location.href="MyURL" to ??
I have over 200 location.href URL not working with UIWebViewNavigationTypeLinkClicked :-S
Thanks to everyone can help me!
<script type="text/javascript">
document.getElementById("myAnchor").setAttribute("href", window.location.href);
var loc = document.getElementById("myAnchor").getAttribute("href");
var t = document.createTextNode(loc);
document.getElementById("myAnchor").appendChild(t);
</script>
Here is one way of doing it: document.getElementById() grabs a reference to the ID attribute of your anchor(s). The second argument of setAttribute(), "window.location.href" grabs a reference to the url in the current window and sets the href attibute in your anchor to this, however if you have a bunch of location.href()s declared in your code, then store these as a variable before the first line instead and then reference that variable at around the same line as where I have declared "loc". The variable "loc" declares a variable which stores a reference to the newly created href attribute you just declared in the previous line. Then I am declaring a variable "t" which creates a text node in the DOM, with the href from the previous line as the value this variable will hold. Lastly, I use document.getElementById to get "myAnchor" again and append the text node from the previous line to it. So now we can actually see the url in the link.
//Also, use a for loop to run this action 200 times and correct all of the hrefs on your page.
<script type="text/javascript">
for (var i=0;i<200;i++){
//run document.getElementById() and .setAttribute, .createTextNode, etc. here
}
</script>
Working fiddle: http://jsfiddle.net/1so33q4z/36/
I would not recommend using document.write(); as mentioned in the other person's post, as this causes the page to work in a way the DOM is not meant to (writes serialized text). Especially if you need to correct 200 of them. See this post Why is document.write considered a "bad practice"?

Categories

Resources