I'm writing java script code in script tag in head like:
<head>
<script language="javascript">
object o = new object({....});
</script>
</head>
and trying to use object a in body tag
<body>
<script>
alert(o.value);
</script>
</body>
how can i access object from body???
is their any alternatives?
<head>
<script language="javascript">
var o = new Object();
o.value="a"
</script>
</head>
<body>
<script>
$(document).ready(function()
{
alert(o.value)
});
</script>
</body>
In this case var a is accessible in complete application, but one thing you need to make sure if you are using external JS files then it must be loaded when you using the variable. try onload function to assure JS is loaded and ready to use in body:
window.onload = function ()
{
alert(a);
}
Since your variable is declared outside any functions it can be accessed from anywhere in your document from the same script block or from a seperate script block like in your example. it can even be accessed from html event-attributes like this (note that its better to attach events to html elements using using js):
<button onclick="alert(a);">Click this button to open an alert!</button>
Related
I have 2 files the first one is an HTML file the other one is a javascript file. What I was trying to do was define a variable on the javascript file and access it on the Html side. Is it possible? A rough code is attached below but it doesn't work I get favColor is not defined error. thanks in advance.
JS Side
const favColor = "red"
Html side
<script src="pathtojsfile"></script>
<p id="insertHere"></p>
<script>
document.getElementById("insertHere").innerHTML = favColor
</script>
It is widely considered bad practice to work with global variables. To avoid it, you can make use of ECMAScript Modules, introduced back in 2015 with ES6/ES2015.
This allows your first Javascript, let's name it colors.module.js to export the variable:
export const favColor = 'red';
Then, in your script that needs to access this variable, you import it:
import { favColor } from '/path/to/js/modules/colors.module.js';
For that to work, you need your importing script to have type=module attribute, and the import must be done on top of your Javascript. The script you import from does not need to be included in the page.
Here's some helpful links to get you started with modules:
ES Modules Deep Dive
Javascript Modules on MDN
Flavio Copes' take on ES Modules
I've set up a tiny github repo demonstrating this very basic usage of an ES module.
If modules are not an option, e.g. because you must support IE 11, or your build stack doesn't support modules, here's an alternative pattern that works with a single namespace object you attach to the global object window:
// colors.module.js
window.projectNamespace = window.projectNamespace || {};
projectNamespace.colors = window.projectNamespace.colors || {};
projectNamespace.colors.favColor = 'red';
and in your page you access it from that name space:
document.getElementById("insertHere").innerHTML = window.projectNamespace.colors.favColor;
This way you have a single location to put all your globally accessible variables.
As the code is written in your example it should work fine. Just like my example here:
<script>
const favColor = "red";
</script>
<p id="insertHere"></p>
<script>
document.getElementById("insertHere").innerHTML = favColor;
</script>
But there can be a number of issues if the code is not like this. But the JavaScript code could just go in the same file. Try to separate the html from the JS like this (the code in the script element could be moved to it's own file):
<html>
<head>
<script>
const favColor = "red";
document.addEventListener('DOMContentLoaded', e => {
document.getElementById("insertHere").innerHTML = favColor;
});
</script>
</head>
<body>
<p id="insertHere"></p>
</body>
</html>
Here I'm also adding the eventlistener for DOMContentLoaded, so that I'm sure that the document is loded into the DOM.
Where your variable is declared is not the problem per se, but rather the loading order of scripts.
If you want to make sure external scripts are loaded before you execute yours, you can use the load event of window object. It will wait until all resources on your page are loaded though (images, css, etc.)...
const myvar = "Hey I'm loaded";
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script>
//console.log(myvar); //<- fails
window.addEventListener('load', e => {
document.querySelector('#insertHere').innerHTML = myvar;
});
</script>
</head>
<body>
<p id="insertHere"></p>
</body>
</html>
Or you can put all your code in js files, and they will be invoked in the order they are declared.
Edit
Given objections and more questions popping in the comments, I'll add this. The best and cleanest way to achieve this remains to put your code in a .js file of its own and put all your <script> tags inside <head>, with yours last, as it relies on others to run.
Then you can either add the attribute defer to your <script> or have everything wrapped in an event handler for DOMContentLoaded so that it gets run after the DOM is fully loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src='other1.js'></script> <!-- let's say this one declares myvar -->
<script src='other2.js'></script>
<script src='other3.js'></script>
<script src='myscript.js'></script>
</head>
<body>
<p id="insertHere"></p>
</body>
</html>
myscript.js
window.addEventListener('DOMContentLoaded', e => {
document.querySelector('#insertHere').innerHTML = myvar;
});
I followed this to set up the node.js server: Using node.js as a simple web server
So I installed the serve-static npm.
I then created a file called file called test.html with the following code
<html>
<head>
<h2>Google</h2>
</head>
<body>
<button onclick="test()">Click me</button>
</body>
</html>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript">
function test() {
console.log('test');
}
</script>
When I click on the button, I get:
Uncaught ReferenceError: test is not defined
at HTMLButtonElement.onclick (test.html:8)
and nothing else. This code looks ok...? Why is this function not found?
Remove your src part if you want to have your own function in between your script tags.
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function test() {
console.log('test');
}
</script>
Also, you should put your scripts before your </body>
Put your javascript just before closing body tag (</body>)
And in your case you are binding event handler in the html itself, in this case you have to define those functions before you use them.
In this case put test() function code in head tag. It will work fine
Your JavaScript (script tag) is outside of html element. Put it in head or body.
I'm trying to make a Javascript a key value object and use it as my Resources for localization
I have made this Jascsript code in a javascript file:
var Values = {
lbl_CustomerName:"Customer name: "
}
now need to use this object in my HTML file:
<title>Title</title>
<script src="../content/JS/Resources/en-us/Resources.js"></script>
</head>
<body>
Values.lbl_CustomerName
</body>
</html>
but it's parsed as a plane text!
I need to call this Object and access the key to show it's value in my HTML file how to do this?
we can truly advice you to use a javascript framework like angular js that embed this kind of behavior inside the framework.
without javascript framework, you will need to modify the DOM by yourself to insert your expected value. If you want to do it in pure javascript function you can write a functio like :
function insertKey(elem,id) {
elem.innerHTML = Values[id];
}
In your case it will look like that :
<title>Title</title>
<script src="../content/JS/Resources/en-us/Resources.js"></script>
<script type="text/javascript">
function insertKey(elem,id) {
elem.innerHTML = Values[id];
}
</script>
</head>
<body>
<div onload="insertKey(this,'lbl_CustomerName')"></div>
</body>
</html>
Whenever you want to parse a JavaScript code, you should wrap it inside a script tag.
<title>Title</title>
<script src="../content/JS/Resources/en-us/Resources.js"></script>
</head>
<body>
<script> document.write(Values.lbl_CustomerName); </script>
</body>
</html>
Browsers have interpreters and virtual machines. Natively, they parse the codes as HTML. if you need to use other syntaxes like CSS and JavaScript, you should tell them hey browser, parse this section as a CSS, JavaScript.
That's why we need and tags
I got the answer, the Javascript file must return an object, so I can use it on my page as follows:
javascript:
function resourcesObject() {
return {
"customerName": "Customer name";
};
}
HTML
<script>
var resources=resourcesObject();
var customerName=resources["customerName"];
</script>
I have a JS
function check(obj) {
for( i=0; i<obj.elements.length; i++){
if(obj.elements[i].type=="checkbox"&&obj.elements[i].checked){
if(confirm(onSubmitMessage)){
return true;
}
else{
return false;
}
}
}
alert(alertMessage);
return false;
}
It's called from jsp page like this:
<script src="/TestAppChanged/check.js" type="text/javascript">
var onSubmitMessage = '"<bean:message key="body.onsubmit.delete"/>"';
var alertMessage = '"<bean:message key="body.alert.delete"/>"';
</script>
...
<form action="MyAction" method="POST"
onsubmit="return check(this)">
The problem is in that it doesn't see these glabal variables: onSubmitMessage and alertMessage. I thought that the problem was in the way that these things are set and changed it's values to usual strings like "qwe" but it didn't work again. So script in it's body simply doesn't see these variables. And the question is how to get them from script?
The <script> tag is used either to load an external file, like <script src="path/to/file.js"></script> or to define JS code inside the tag, like:
<script type="text/javascript">
// Your JS code.
</script>
You can't have both on the same tag. Thus, split your code:
<script src="/TestAppChanged/check.js" type="text/javascript"></script>
<script type="text/javascript">
var onSubmitMessage = '"<bean:message key="body.onsubmit.delete"/>"';
var alertMessage = '"<bean:message key="body.alert.delete"/>"';
</script>
A block between <script src=""></script> parsed when the browser don't support javascript. You need another <script> block, and put in this your variables.
It doesn't see the globar variabes because you declare a source in the script tag.
You should remove the global variables and declare them before the code of the function, in the js page, and then simply include the page like this:
<script src="/TestAppChanged/check.js" type="text/javascript"></script>
You should have two script tags. One for the variables. And then another one below it, linking to your javascript file.
You can set contents in tag OR set the src attribute.
It should be:
<script type="text/javascript">
var onSubmitMessage = '"<bean:message key="body.onsubmit.delete"/>"';
var alertMessage = '"<bean:message key="body.alert.delete"/>"';
</script>
<script src="/TestAppChanged/check.js" type="text/javascript"></script>
Don't mix the src attribute and code within the tag. Use two tags.
I have two files screen.html and db_fun.js.I have declared a variable at just the beginning as follows:
db_fun.js
var name = "abc";
now i tried to access this variable in the screen.html file as follows
screen.html
<html>
<body>
<form name = "screen" action = "db_fun.js">
<p> <script>document.write(name);</script> </p>
</form>
</body>
<script src="db_fun.js" type="text/javascript" />
</html>
it doesn't print nethn. Y so?
add this to the head
<script type="text/javascript" src="db_fun.js"></script>
I think that you should move
<script src="db_fun.js" type="text/javascript" />
In the head of the page. I.e. before document.write.
Because in the moment where you are trying to print 'name', the variable is still not created. Also I think that it is not a very good practice to use document.write to add content to your page. Try using jQuery or some other library. For example:
$(document).ready(function() {
$("p").html(name);
});
That's because you are inserting your JavaScript in the page footer. You have to firstly load your javascript file into your web site (in the head section for example) and then use your variable.