i'm new to JavaScript i have this script and i want to declare a variable on a if but on document.write , returns nothing what am i doing wrong ?
<head>
<script>
(function () {
setInterval(function () {
var NetworkStatus = document.getElementById("status"),
isOnline = navigator.onLine;
if (isOnline) {
NetworkStatus.innerHTML = "Online";
NetworkStatus.className = "online";
var person="John Doe";
} else {
NetworkStatus.innerHTML = "Offline";
NetworkStatus.className = "offline";
var person="Santa Claus";
}
}, 100);
})();
</script>
</head>
<body>
<h1 id="status"></h1>
<script>
document.write(person + "<br>");
</script>
</body>
It's just all wrong, why use an IIFE and a timeout when all you have to do is add the script in the tag at the end of the DOM.
Also, you're setting the innerHTML of the element, and using document.write, which will overwrite the document ?
<head>
<title>I messed up</title>
</head>
<body>
<h1 id="status"></h1>
<script>
var NetworkStatus = document.getElementById("status"),
isOnline = navigator.onLine;
if (isOnline) {
var person = "John Doe";
NetworkStatus.innerHTML = "Online " + person;
NetworkStatus.className = "online";
} else {
var person = "Santa Claus";
NetworkStatus.innerHTML = "Offline " + person;
NetworkStatus.className = "offline";
}
</script>
</body>
You are in IIFE. which creates its own scope
And that's where it stays
Do this :
window.person="Santa Claus";
Instead of what you're doing.
var sets the scope of the variable to the function it is declared within. You are trying to document.write it from outside that function, so it is out of scope and inaccessible.
Use window.person instead of var person.
The function executes after 100ms which means the person variable has no value when the page loads.
Related
I'm making a quick site with a list and I can't call a function:
function:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
function AddAnime() {
var newItem = document.getElementById("div")
newItem.innerHTML = document.getElementById("box").value;
newItem.onClick = removeItem;
document.getElementById("list").appendChild(newItem);
}
</script>
</head>
But when I call it with this:
<input type="button" value="Add Anime" onclick="AddAnime();">
By the way, this is line 51
the error comes up.
I don't know what to do.
You need to expose the function outside of the onload scope:
<script>
function AddAnime() {
var newItem = document.getElementById("div") newItem.innerHTML = document.getElementById("box").value;
newItem.onClick = removeItem;
document.getElementById("list").appendChild(newItem);
}
window.onload = function() {
AddAnime();
}
</script>
I simply want to access the value of array status from another function. However, the alert is giving me value as undefined. Here's my code:
Test.php:
<html>
<body>
<script>
var status=[];
status[0]='1';
calculateInput();
function calculateInput(){
alert(status[0]);
}
</script>
</body>
</html>
You are colliding with window.status:
function calculateInput () {
alert( status === window.status ); // true
}
To avoid this, rename your array or get out of the global scope:
(function IIFE () {
var status = [];
status[0] = "1";
calculateInput();
function calculateInput () {
alert( status[0] );
}
}());
Change your variable name from status to something else
ex.
<html>
<body>
<script>
var mystatus=[];
mystatus[0]='1';
calculateInput();
function calculateInput(){
alert(mystatus[0]);
}
</script>
</body>
</html>
I need to add an external javascript file to the <head> section of a website - one file when on the Staging server, and a different one for production.
So far I have this, but I get an error: 'return' outside of function
<script type="text/javascript">
var pathOrigin = window.location.origin;
var headtg = document.getElementsByTagName('head')[0];
if (!headtg) {
return;
}
var linktg = document.createElement('script');
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
linktg.src = '/script-staging.js';
} else {
linktg.src = '/script-production.js';
}
headtg.appendChild(linktg);
</script>
What am I missing?
Thanks.
Return - Specifies the value to be returned by a function.
That means the error you got from the browser is correct. Your returnstatement is not part of a function, but of the global scope. You wil either have to skip using the return statement and use simple variable assingment like in #Azzy's answer, or encapsulate it in a function like so:
function getHead() {
var headtg = document.getElementsByTagName('head')[0];
if (typeof headtg === 'undefined') {
return; // will break the function
} else {
var linktg = document.createElement('script');
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
linktg.src = '/script-staging.js';
} else {
linktg.src = '/script-production.js';
}
headtg.appendChild(linktg);
};
};
getHead(); // don't forget to initialize the function
//or you could do:
element.onload/onclick/on<whatever_event> = getHead();
To me it is also not clear what you want to return, unless you simply want to stop script execution; citing from MDN:
If the expression in return [expression] is omitted, undefined is returned instead.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
NB: Check this why it is safer to use the typeofstatement than a simple !mark to check if something exists: Check if object exists in JavaScript.
EDIT: For a very simple use case of the return statement, you can check out this fiddle I made which is basically a counter that will output an error when it reaches 100.
Where place this code? Are you sure that the path is correct?
Another method to add js file into head is this method:
<head>
....
<script type="text/javascript">
var pathOrigin = window.location.origin;
var path = "";
if (pathOrigin.toLowerCase().indexOf("staging.server.com") >= 0) {
path = '/script-staging.js';
} else {
path = '/script-production.js';
}
document.write( '<script type="text/javascript" src="' + path + '"><\/script>' );
</script>
.....
</head>
<html>
<head>
<script type='text/javascript'>
var path = window.location.origin
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
if (path == 'local'){
fileref.setAttribute("src", 'file:///D:/JS/jquery.js')
}
else{
fileref.setAttribute("src", 'file:///D:/JS/jquery.js')
}
document.getElementsByTagName("head")[0].appendChild(fileref)
//list all the js loaded dynamically
var scripts = document.getElementsByTagName('script');
console.log(scripts);
</script>
</head>
<body>
<p>test</p>
</body>
</html>
To load script dynamically, you can try out this..
The javascript error "return statement outside of function" means you've created a code fragment that is not allowed to exist outside of a function definition.
I am new to web development.
Today I learn about classes(function) in javascript. I got an error how to call dynamically added method.
My Code :
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
MyMethod("start", function () { return "hi"; });
var abc = this.start(); //gives error
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<input type="button" value="Click" onclick="MyFunction1()"/>
</div>
</form>
Here when I click the input button then not able to call the dynamically added function
How can i call the start() function that i added here.
Please Help me.
Thanks in Advance.
this in MyFunction1 referes to the global object in that case(for browsers it is window) , because you call MyFunction1 as function and you don't create an object by using new MyFunction1().
Another thing to be noted. You should not use eval when it is possible to do it without eval.
You can do the same thing using:
function MyMethod(name, fn) {
MyFunction1.prototype[name] = fn;
}
Using eval prevents you from using optimization tools or tools to validate your code. At least most of these tools don't take eval into account or even give a warning about that you are using it.
Try adding "new" before your onclick call to MyFunction1, creating an instance of it.
It reseolved I did
Hi , It resolved .Thanks for the gret help i did :
function fnOnload() {
MyMethod("start", function () { return "hi"; });
}
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
}
function MyFunction2()
{
var aa = new MyFunction1();
var answee = aa.start();
}
and in click of button i callled function MyFunction2()
without changing your code you can do as follow , but I say it would be helpful if you read about invocations types and about this variable.
function MyMethod(name, fn) {
MyFunction1.prototype[name]= fn;
return MyFunction1.prototype;
}
function MyFunction1() {
var myPrototype= MyMethod("start", function () { return "hi"; });
var returnValue = myPrototype.start();
console.log(returnValue);
}
i got a ajax procedure that is working ok, but now i need to add a new function to be called just once. so i add this to my current script to get the apex collection clean, but now nothing happens, i placed an alert to verify, but no alert is shown, i guess is because i am placing my clean script in wrong place or there must be something else missing.
// Clean Collection
function()
{
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
}
here is my full script. thanks for your value tips !!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Totals</title>
<script type="text/javascript">
$(function()
{
$("#Calculate").click
(
function()
{
// Clean Collection
function()
{
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
}
$("input[name=f_qty]").each
(
function()
{
var valueInCurrentTextBox = $(this).val();
var productId = $(this).parents('tr').find("input[name=f_prod_id]").val();
$("#P12_PRODUCT_ID").val(productId);
if (valueInCurrentTextBox != '')
{
$("#P12_QTY").val(valueInCurrentTextBox);
var ajaxRequest = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=ADD_PRODUCTS",&APP_PAGE_ID.);
ajaxRequest.add('P12_PRODUCT_ID',html_GetElement('P12_PRODUCT_ID').value);
ajaxRequest.add('P12_QTY',html_GetElement('P12_QTY').value);
ajaxResult = ajaxRequest.get();
}
}
);
alert('Updated!');
}
);
}
);
</script>
</head>
<body>
<div id="totals"></div>
<p align="center" style="clear: both;">
<button type="button" style="font-weight: bold;background-color:lightgray;margin-left:auto;margin-right:auto;display:block;margin-top:0%;margin-bottom:0%" id="Calculate">Add Products</button>
</p>
</body>
</html>
You're declaring that inner function, but never actually calling it. You could assign it to a variable and then call that, but it's actually not needed at all.
Try:
$(function()
{
$("#Calculate").click
(
function()
{
// Clean Collection
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
$("input[name=f_qty]").each
(
function()
{
var valueInCurrentTextBox = $(this).val();
var productId = $(this).parents('tr').find("input[name=f_prod_id]").val();
$("#P12_PRODUCT_ID").val(productId);
if (valueInCurrentTextBox != '')
{
$("#P12_QTY").val(valueInCurrentTextBox);
var ajaxRequest = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=ADD_PRODUCTS",&APP_PAGE_ID.);
ajaxRequest.add('P12_PRODUCT_ID',html_GetElement('P12_PRODUCT_ID').value);
ajaxRequest.add('P12_QTY',html_GetElement('P12_QTY').value);
ajaxResult = ajaxRequest.get();
}
}
);
alert('Updated!');
});
});