Pass JavaScript JSON variable from index.js into index.html - javascript

This is my index.js file:
function fun()
{
var obj;
}
This is my index.html file:
<script>
src="js/index.js"
</script>
I want to use variable obj here.
I saw some solutions to create a variable and pass in index.html but is there any way of injection?
Actually, obj is a JSON object. I forgot to mention that previously. How would I use the JSON object keys and values in my index.html outside of the script tag?

Try out AngularJS. With this, you can declare variables in $scope and use it in your html like:
JavaScript:
...some angular logic...
$scope.foo = "bar";
...some other angular logic...
HTML:
<p>{{foo}}</p>
There are many tutorials out there. Read the documentation. It may be what you are looking for.

Although there isn't any way to inject a JS variable into HTML simply, you can use a javascript function to do the same thing:
In index.js:
function fun()
{
return obj; // Assuming obj is a defined variable.
}
document.getElementById("toReplace").innerHTML = fun();
In index.html
<p id="toReplace"></p>
<script src="index.js"></script>
Essentially, your javascript will replace the content of the <p> tag, which has the ID "toReplace", with the value of fun().

Related

access an object previously filled by another html file

I have 2 files html (index.html and event.html).
in my index.html in my file I import a JS:
<script type="text/javascript" src="../js/events/createEventOBJ.js"></script>
and this is my js example with filled object (infact, with console.log I can see my newObj):
var newObj = [];
function getOBJ(eventObj){
newObj = eventObj;
console.log(newObj);
}
function createObj(){
return newObj;
}
now, in another html file (event.html, in which I entered with a button in the index.html file) I use this:
<script type="text/javascript" src="../js/events/createEventOBJ.js"></script>
<script>
console.log(createObj());
</script>
but it is empty, why?
And, another question is:
if in event.html I have something like this:
<div id="idevent" class="classGraph"></div>
and in createEventObj.js I use this:
var event1 = document.getElementById('idevent');
event1 is undefined, why?
Js variables (e.g. your created objects) between to html pages are independent. It means that they have different instances and you cant share object like that. If you are on index.html and you are going to another page every js variable from index.html are destroyed.
If you want to share between two pages some variables you need to use cookies or local storage or have backend to store the values.
Or you need SPA

NODE.JS accessing functions within an EJS template

I have a scripts.js file that includes a function inside that i want to access within an EJS templates.
in the templates i included a header, in the header I added a script rel to scripts.js
<script src="/scripts/scripts.js" type="text/javascript"></script>
I tested it though console.log("test") and when the template is being called I see "test" appears in the console.
when I try to call an actual function (verify_data) within the EJS template i get an error verify_data is not defined.
the error code within the EJS looks like this:
<p><em>Submited By <%= verify_data(results.user.username) %></em></p>
the function check if the argument passed is null/undefined, if yes the data returns if not "n/a" string returns instead.
How do i access JS functions directly within EJS template ?
Thanks,
Assuming you're not using a SPA framework, you need to add a tag which will be either replaced by the function or to contain the data you want to store.
Look at this code snippet
<p><em>Submited By <span id='userData'></span></em></p>
<script>
//This is the script.js
function verify_data(userName) {
return `My data with '${userName}'`;
}
</script>
<script>
let data = verify_data("EleFromStack"); // assuming <%=results.user.username%> = "EleFromStack"
document.querySelector("#userData").textContent = data;
</script>

How to call a function that is inside another function javascript

I have two files as below:
trycapture.js (which has) trycapture() (which has) drawaggregate() definition
main.js from which I want to call drawaggregate();
trycapture.js
trycapture(){
... some code
function drawaggregate(){
... definition
}
}
main.js
.. some variables
var try_obj = new trycapture();
try_obj.drawAggregate(emit_x1,emit_y1,emit_x2,emit_y2);
HTML
<head>
<script src="trycapture.js"></script>
<script src="js/main.js"></script>
</head>
How can I call that function. I tried creating an object right before calling drawaggregation() such as above:
I still get the error:
TypeError:try_obj.drawaggregate is not a function
Also, in index.html I made sure that I include trycapture.js before main.js How can I call that function?
Add
this.drawaggregate = drawaggregate;
after your function definition to make it a public method of the trycapture object.
Overall, you will change your trycapture.js to the following:
function trycapture(){
... some code
// Locally accessible only
function drawaggregate(){
... definition
}
this.drawaggregate = drawaggregate; // Makes it publicly accessible also
}
the drawaggregate() method can then be called like so:
var try_obj = new trycapture();
try_obj.drawaggregate();

How to split jquery source code into multiple files when using the module pattern?

I've got some problems splitting up my jquery source code into more than one file. My real source code is a bit more complicated but the following simple example shows my problem very good. At first I would like to show you a working example with only one javascript file. Afterwards, I will describe what I tried in order to split the javascript into two files.
My html code looks like this ("./jquery" is a symbolic link to my local jquery download):
<html>
<head>
<script src="./jquery"></script>
<script src="./file1.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
The jquery source code in file1.js looks like this:
$(document).ready(function() {
var Test = (function() {
var content = $('#content');
var init = function() {
content.html('<p>test</p>');
};
return {
init: init
}
})();
Test.init();
});
After opening the page, "test" is displayed so that this example works as expected.
But now I want to put the whole Test part into another file file2.js. My html is basically the same but gets an additional line:
<script src="./file2.js"></script>
file1.js now contains only the call of the init function:
$(document).ready(function() {
Test.init();
});
and file2.js contains the definition of Test:
var Test = (function() {
var content = $('#content');
var init = function() {
content.html('<p>test</p>');
};
return {
init: init
}
})();
When I open the page, "test" is not displayed any more. In order to make sure that the init function is called at all, I added a console.log("test"); to the init function which is working fine. Therefore, I suppose that the function might be called before the DOM is ready, but actually I am pretty clueless. Maybe someone can give me a hint how to make that run.
Best regards and thanks in advance!
You can do several things according to your preferences...
1. Move your scripts to the end of the HTML file intead than in header...
<html>
<head>
</head>
<body>
<div id="content"></div>
</body>
<script src="./jquery"></script>
<script src="./file2.js"></script>
<script src="./file1.js"></script>
</html>
Think this problem secuencially... if you don't want to declare a var in each module referring an element in your DOM you need that the element exists first, then you can declare the "global" var to the module content. This way your original file2.js works.
Another way is to declare the content "global" to your module but init this in your init function...
var Test = (function() {
var content;
var init = function() {
content = $('#content');
content.html('<p>test</p>');
};
return {
init: init
}
})();
Now you can use the content variable in all of your module's functions.
Hope this helps, let me know.
file1 depends on file2. Make sure file1 comes ordinally after file2 in your html.
AngularJS offers dependency injection, modules, services, factories and all sorts of other goodness. Takes a bit to get used to, but well worth it IMO: much cleaner abstraction of javascript from DOM, data from presentation etc.
I appreciate your question is JQuery specific, but especially if you're starting a new site, I suggest you give Angular a try.
Modify your file2.js as follows:
var Test = {
content : $('#content'),
init : function() {
Test.content.html('<p>test</p>');
}
//, include other functions here
};
Modify your file1.js as follows:
$(document).ready(function(){
Test.init();
})
Now declare file2.js before your declare file1.js because file1.js is referencing a function from file2.js .

Calling a javascript function from other file

I have a javascript file that I'm am calling in the head of an HTML file, it's called custom.js, it defines this function:
var example = function(element){
console.log(element);
};
Then in the actual HTML document, just before the body tag closes, I try to initialize it by calling the same function like this
example('.header-background');
I get the error example is not a function, what exactly am I doing wrong? Thank you so much for your help.
here is a bit more context
<!DOCTYPE html>
<html>
<head></head>
<body>
// the main body of html
<script src="custom/custom.js"></script> // here is the file with the example function
example ('.header-background'); // here im calling the function
</body>
</html>
Change var example to window.example. If you declare a variable with var inside of a function or closure it isn't globally accessible.
e.g.,
function foo()
{
var test = 'hi';
}
console.log(test); // error, test isn't accessible
function foo()
{
window.test = 'hi';
}
console.log(test); // works
Global variables should generally be avoided there. There's most likely a better way to do what you want to do.
Make sure to the file where your function in the html page you are calling the function:
<script type="text/JavaScript" src="youtpathtothefile/custom.js"></script>
Hope it helps
Please make sure two things:
your javascript file is loaded after jQuery library.
your javascript is loaded after the every dom in the html file has finish loading.
Maybe that could help you.

Categories