I am currently building a website that uses windows to load in new content via ajax. These windows are allowed to contain the same page as in another window using the same javascript. Currently I assign a unique id to the new window which it then stores for later use.
Once the code is loaded in, all the ids in that window are converted by adding on to them a unique_id. ie "box" becomes "box_win1". I then send this id to the javascript by assigning it to a variable so it can be used in document.ready function.
The pseudo code for the window is like the following:
document.ready{
var temp_id=id+1;
$("#mybox" + temp_id).val("abc")
//run some startup stuff
}
I am just wondering is there a better way to do this. As I find if I open to many new windows all at once the temp_id conflicts and goes to the wrong window.
I would like to some how create an instance of the code but I am not sure how. I cannot use global functions however as that may cause naming conflicts.
put this into a function
function callMe (){
var temp_id=id+1;
$("#mybox" + temp_id).val("abc")
//run some startup stuff
}
you can use callMe() anywhere then
Related
I'm trying to call a function from my html: tasks-div-upload.html to my other html: task-tareas-actualizadas.html.
I'm including my scripts on the script tags of the html files
I tried to call the function like this
First of all this is the html that calls the function: tasks-divs-upload.html
and the function is in task-tareas-actualizadas.html
I tried to call the function like i do in java that is
writing the class and then the function, for example: people.countPeople(5);
In this case, there are not classes because its an html file so what can I do?
//tasks-divs-upload.html
function contadorTareas(){
for(var x = 0; x < divs; x++){
var numeroTareas = x;
}
prueba(numeroTareas); // <---------
}
//task-tareas-actualizadas.html
function prueba(numero){
console.log(numero);
}
Console shows this error "Uncaught ReferenceError: prueba is not defined"
This CAN be done but is mostly a bad idea and is not very common and has some specific requirements. It is best it NOT be done unless the user is aware of the interaction.
IF your task-tareas-actualizadas.html opens tasks-divs-upload.html in a new window then tasks-divs-upload.html can call window.opener.prueba() BUT, if the first window gets closed, it will not be there and they must both be of the same origin.
This interaction can also go the other way if the parent keeps a reference to the child window.
Better to create a JavaScript file say "myfunctions.js" that includes the functions you wish to use and include it in both pages UNLESS for some reason you need/want the pages to interact - say the child page alters the parent page DOM or some such.
Reference https://developer.mozilla.org/en-US/docs/Web/API/Window/opener
and https://developer.mozilla.org/en-US/docs/Web/API/Window/open
Well scripts in HTML are JavaScript code. They need to be either defined in separate .js files or included in html using <script> tags.
It is not possible to define a JavaScript function in a html file and then use it in another html file. You need to define the function is a separate JavaScript file and then include this file in the html page.
You may also use JavaScript modules which are natively supported by modern browsers.
On my site I have a number of links to various external booking forms that should open in new windows. Unfortunately I can only change each links class (can't set the Id's).
What I'm trying to do is to come up with a Javascript that has a function for each external site to open in a new window. And some jQuery that executes the proper function for the link clicked with a certain class in it.
This is one of the functions (others have a different name and url):
function booking-site-1(elt) {
window.open("https://bookings.domainname.eu/4043/31", "_blank", "toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745");
}
And this is the jQuery
jQuery(".booking-site-1-class").click(function(){
alert("Finally!")});
Where the jQuery now successfully shows the alert when I click a link I'd like it to execute the function shown above. I such a n00b that I don't know how to do that.
Hope that someone could give me a few pointers here.
Firstly, function names declared using var/const/let/function can't have hyphens - - in fact, no names declared as such in JavaScript can. Use underscores instead:
function booking_site_1(elt) {
window.open("https://bookings.domainname.eu/4043/31", "_blank", "toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745");
}
And to make it execute, just add it to your click handling function:
jQuery(".booking-site-1-class").click(function(){
alert("Finally!");
booking_site_1($("#randomElement"));
});
As pointed out by Jaromanda X in the comments, you can make functions as a property of the window object, or of any object,
I have a control on a javascript page. I can access this by id, but what I want to do is cache the control since I'm referencing it in a few places. How can I cache this control with say an id=TestControl
You can create a variable1 and safe a reference to the element (control) in it:
var testControl = document.getElementById("TestControl");
Ensure ou run that code after the element has been created (for instance, put the script tag at the end of the document, just before the closing </body> tag).
If you do that at the top level of your code, for instance:
// Scoping function to avoid creating globals
(function() {
var testControl = document.getElementById("TestControl");
// Your code here
})();
...all of your code will have access to the variable.
1 In fact, the browser has already done that for you by creating an automatic global called TestControl, but I never advocate using automatic globals. The global namespace is just too crowded, too easy to get bitten by conflicts.
The problem was that code needed to go in a $(document).ready() function. I was trying to reference it before the document loaded. Thank you for your very fast response!
I want to be able to run JavaScript on my webpage and guarantee that it can be stopped cleanly without causing problems. You could think of it as running JavaScript as if it was contained in an iFrame but allow it to modify and interact with the root DOM. That way if I remove the iFrame, the JS dies.
Use Case/Justification
I want to turn any webpage into a weird mutant SPA. That means taking the traditional HTML, CSS, and JavaScript and then handling page switching myself. To propperly switch pages avoiding artifacts from previously executing JS I'd need to make sure one page's JS doesn't interact with the next page's JS. Ideally, to switch a page it would follow this general formula:
Load HTML and CSS with a framework like Ember.js
Load all linked JavaScript in a contained environment but with the ability to modify the root DOM
When the user clicks a link, stop all running JavaScript and return to step 1.
My Thoughts
I've run tests actually loading a webpage in a full-screen iframe (like this) which achieves the level of containment that I want when executing the JavaScript, but it has serious performance penalties. I want the contained JavaScript, with a minimal performance penalty.
One thought I had was after downloading JavaScript, replacing the actual code dynamically. I would change the code to instead of referencing the Window, referencing the Window.parent.
I'm not attached to the idea of using iFrames, but it just seems like it is the closest thing to a "container" that you can get in JavaScript/the browser. I'd love alternatives.
Related?
github.com/codeschool/javascript-sandbox
instantclick.io/
shadow DOM?
Mini-Followup:
Would it be feasible to build an app like this which would allow for proper handling of both JS life cycles and page switches?
You can't unload a script once it has been loaded. But you can encapsulate some script in an object, and create or destroy this object.
For instance:
var Robot = function(){
return{
sayHello : function(){
alert("Hello!");
},
doSomethingElse : function(){
alert("I'm doing something else");
}
}
}
robot = new Robot();
robot.sayHello(); // Actually alerts "Hello!"
robot = null; // the robot is destroyed.
In your case, if you load a script via ajax, say this piece of script in an object :
{
sayHello : function(){
alert("Hello!");
},
doSomethingElse : function(){
alert("I'm doing something else");
}
}
you can then encapsulate this script in a function :
var Robot = null,
robot = null;
$.get('scriptURL', function(ajaxedScriptObject){
Robot = function(){ return ajaxedScriptObject; };
createRobot();
})
function createRobot(){
robot = new Robot();
sayHello();
destroyRobot();
}
function sayHello(){
robot.sayHello(); // Should alert "Hello!" :)
}
function destroyRobot(){
robot = null;
}
I am currently coding in this way:
<script type="text/javascript">
var linkObj;
Is this a safe way to store data? My concern is what if a jQuery or other plug-in was to also use the variable linkObj. Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
$(document).ready(function(){
var linkObj;
});
as long as you use the var keyword, any variable defined in that scope won't be accessible by other plugins.
I you declare a variable this way it will be accessible to all scripts running on the page.
If you just want to use it locally, wrap it in a function:
(function() {var linkObj; ... })()
However, this way nothing outside of the function will be able to access it.
If you want to explicitly share certain variables between different scripts, you could also use an object as a namespace:
var myProject = {}
myProject.linkObj = ...
This will minimize how many global names you have to rely on.
Wrap it in a closure:
<script type="text/javascript">
(function() {
var linkObj;
// Rest of your code
})();
</script>
This way no script outside your own will have access to linkObj.
Is this a safe way to store data?
This is not storing data per se, it's only declaring a variable in a script block in what I assume is an HTML page. When you reload the page in the future, it will not hold previous values.
My concern is what if a jQuery or other plug-in was to also use the variable linkObj.
That's a valid concern, like others have pointed out. However, you would expect plugins not to rely on scope outside the plug-in. This shouldn't impact a lot as good plug-in design would likely prevent this from happening.
Also if I declare my variable like this then can it also be seen by other functions in scripts located in other js files that I include?
Yes. As long as their execution is triggered after your script block gets loaded. This normally follows the order in which your script declaration appears in the page. Or regardless of the order they appear on the page if they are executed, for example, after the jQuery DOM 'ready' event.
It's common to hear that is good to avoid 'global namespace pollution', which relates to this concern. To accomplish that you can use a function to contain code, and directly invoke that function in your script block.
(function () {
var a = 1; // the scope is within the function
alert('The variable a is equal to: ' + a);
}) (); // the parenthesis invoke the function immediately