javascript loaded from a path; how to use document.getelementbyid - javascript

`
function init() {
var a = 'output of my processing';
alert('I am here'); // alert pops up
document.getElementById("<%=hdnField.ClientID %>").value = a;
}
<head>
<script src="../Scripts/myscripts.js"></script>
</head>
<body onload="init()">
<asp:HiddenField ID="hdnField" runat="server" />
</body>
`I have a page with lot of javascript; I am trying to clean it up by moving the scripts to a script folder and reference the path; Seems to work fine, except when it encounters 'document.getelementbyid(controlname.id)'- it throws 'TypeError: Cannot read property 'value' of null'
I understand it is not able to find the control. Why does that happen? I thought the DOM is already built - what difference does moving the javascript to a path make to that anyway? Any ideas on how to make it work? I would really like javascript to be moved from the page.

You're using ASP.Net inline calls inside your JS. This couldn't work, for two reasons:
It's likely you don't have your server configured to handle .js files using the ASP.Net processor.
Even if you did, the processing of the .js would be completely separate to the hosting .aspx page; meaning hdnField would not be in scope.
You would be better off passing knowledge about the items on your page directly to the JavaScript:
JS:
function init(config) {
var a = 'output of my processing';
alert('I am here'); // alert pops up
document.getElementById(config.hdnFieldID).value = a;
}
ASPX:
<head>
<script src="../Scripts/myscripts.js"></script>
</head>
<body onload="init({ hdnFieldID: '<%= hdnField.ClientID %>' })">
<asp:HiddenField ID="hdnField" runat="server" />
</body>
Hope that helps.

This answer assumes your directory structure is correct.
Move your script tag to the bottom of the body, just before . Here is a good SO answer to this question, and here is another.
In addition, in general, it's bad practice to call a JavaScript function from inside HTML elements. If you're not using jQuery, you can add a "DOMContentLoaded" event listener to run the code. With jQuery, the standard $(document).ready() has been proven to work well. Or, if you simply put your script tag at the bottom of the , and place init(); at the end of your JS file, it will all run properly. This would be for a very simple application, but simplicity is sometimes the best.
Finally, for a sanity check, you could hard-code the ID in your init function. I don't know asp.net, but you might want to check the output of <%=hdnField.ClientID %>. Are you sure you're getting the correct ID?
Good luck.

Related

Why can I call a javascript function from inside an event like onblur, but when I call the function at the bottom of <body> it becomes 'undefined'?

Here's a basic example of what's happening. I can understand that I'm probably calling the function in body before it's defined but then why is it so common to put javascript at the bottom of the page? I know my boss is going to say use bottom javascript so what should I do?
Also the root issue is when the page is first loaded, if there is a username from the server I need to run the CheckUsername() function. So is there a better way to do it conditionally?
<body>
<input type="text" name="username"
id="username" onblur="CheckUsername()"
maxlength="30" value="#username" />
#if (username.length > 5)
{
<script>
CheckUsername(); // this is the one that's undefined
</script>
}
#section bottomjavascript
{
<script language="JavaScript">
function CheckUsername() {
// does work
}
</script>
}
</body>
The actual body tags come from the master layout. But why can I use CheckUsername in the input tag, but I can't just call it on the page?
I decided to just remove the #section bottomjavascript so it wouldn't move any scripts in there below the body tag.. Not really a solution since this page no longer uses the master section for javascript but it works now
Put the function definition before the first call. When you call it the first time, the parser does not know what CheckUsername() is. So do this:
<body>
<input type="text" name="username" id="username" onblur="CheckUsername()" maxlength="30" value="#username" />
#section bottomjavascript
{
<script language="JavaScript">
function CheckUsername() {
// does work
}
</script>
}
<script>
$(document).ready(function() {
if (#{username.length} > 5)
{
CheckUsername(); // this is the one that's undefined
}
});
</script>
</body>
I normally put these functions in there own js file and reference them in the head of the document. That way it is defined when I need it below.
If you put the code in document.ready, then all js files should be loaded and you will be able to run the function. To do that, you have to put your if statement from razor into js.
Make the check execute when the page is loaded, like this:
#if (username.length > 5)
{
<script>
window.addEventListener("load", function() {
CheckUsername();
});
</script>
}
It does not matter where this script ends up: top, bottom, ... does not matter.
Adding Javascript before the </body> tag is recommended to prevents render blocking while the scripts load and is much better for site perception head. Adding Javascript before the </body tag will also improve the site loading speed.
You can find more about this on this topic: JavaScript in <head> or just before </body>?
To answer one question, script tags should be put just before </body> i.e just before the end of the document.
Why?
With stylesheets, progressive rendering is blocked until all stylesheets have been downloaded. Thats why its best to move stylesheets to the document HEAD, so they get downloaded first and rendering isnt blocked. With scripts, progressive rendering is blocked for all content below the script.
Use this:
<script>
window.addEventListener("DOMContentLoaded", function (event){
//do stuff
});
</script>
This checks if the page is fully loaded before firing off your function. Libraries e.g., jQuery $(document).ready automatically does this for you.

How to call an external function internally in javascript? [duplicate]

This question already has answers here:
javascript <script> tag - code execution before src download
(4 answers)
Closed 8 years ago.
I am relatively new to JavaScript so this might be somewhat trivial. However I can't seem to find the answer to this question.
Say I have a JavaScript file (bar.js) with a function in it called foo(). I want to call this function (foo) inside a script tag. I would like it to work like so.
<script type="text/javascript" src="bar.js">
foo();
</script>
I am not able to get this to work. I have ran the JavaScript console with my browser and what it seems to be doing is...nothing. No syntax errors or anything.
I can run a function similarly with a button click...using the script tag above and this.
<button type="button" onclick="foo();">Click Me</button>
I could do it this way, but in the actual circumstance I need to pass parameters into the function that is being called on the button click. I can't get those recognized either. I'm sure that something to do with scope.
The way I tried this was like so...
<script type="text/javascript" src="bar.js">
var a = "blah";
var b = "blab";
</script>
.... (some more html)
<button type="button" onclick="foo(a,b);">Click me </button>
Here I get that a is undefined. Which leads me to think that it is a scope problem. The script tag is in the head section and the button is in the body section. Can you put script tags outside of the head and body tags to make global data?
Thanks for the help in advance.
I have never used jsfiddle before and was having trouble getting it to work so I'll just post and example code here.
<html>
<head>
<script type="text/javascript" src="bar.js">
</script>
<!--From what yall say I should have another script
tag here for anything else. Say some variable?-->
<script type="text/javascript">
var a = "hello";
var b = "text";
</script>
</head>
<body>
<!--This should work now?-->
<button type="button" onclick="foo(b,a)">
Click me
</button>
</body>
</html>
bar.js contents:
function foo(id,string){
document.getElementById(id).innerHTML = string;
}
I got this to work.
Thanks everyone.
You need to first include the javascript containing the function:
<script type="text/javascript" src="bar.js"></script>
and then call it in another script tag:
<script type="text/javascript">
foo();
</script>
In your example you seem to have mixed 2 notions into a single script tag which is invalid: include an external javascript file and in the body of the script tag write your code.
According to the specification:
The script may be defined within the contents of the SCRIPT element or
in an external file. If the src attribute is not set, user agents must
interpret the contents of the element as the script. If the src has a
URI value, user agents must ignore the element's contents and retrieve
the script via the URI.
So basically you should avoid such situations and have separate script tags for including external files and for writing inline js.

Is there a way to use javascript code without using <script> tag?

So I'm working on my online portfolio using prosite.com and I created some simple hover thingy using javascript (http://wojtek.szukszto.com/index.html). The problem is prosite.com won't allow me to use < script > tag... Is there any way to do it? Maybe as an external html? I don't know... I'm not really good in coding, so any help would be appreciated.
You can have them as DOM Events like
<div onclick="alert('cat');">
I <strong>Really</strong> want a cat!
</div>
<body onload="//you can put a whole bunch of stuff here"></body>
(It is equivalent to window.onload = function(){ //stuff })
You can put your javascript code into external file and call in the head section of your html document
<head>
<script src ="/JS/yourjsfile.js"></script>
</head>
hope that your host allows you to call JS in the head section
The way I do it is by stating the type of script. The ProSite already has javascript integrated within itself. I use:
<script type="javascript"> Code-Goes-Here </script>

Uncaught ReferenceError $ is not defined

I'm very new to JavaScript (just started a few hours ago and trying to get a script working). I went through a few tutorials on W3 and the 'hello world' code works when I paste it directly into my HTML but I'm having a problem with a script (I've had problems with other scripts as well but I am not sure what I'm doing wrong).
I have this code that I want to test in my HTML, I copied the HTML in and it looks the same then I made a file in my static folder called edit.js and copied the JavaScript into it (exactly as shown). It didn't work no errors on the page but when I click it nothing happens. I tried to paste a W3 'hello world' code in and that worked but this script does not.
I tried to inspect the code in Chrome and that's where I see the above error (under the resources tab). I can open the js file using Chrome which makes me think the js file is accessible and pointing correctly but I'm not sure how to get it working. I'm using Jinja2 as my template engine to render the HTML and in my header I have:
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
and in my main template (the one that gets rendered on all pages) I have:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
edit.js:
(even putting it within the script tag directly on the page I want to use it on doesn't work)
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});​
HTML:
(it's embedded in a larger page)
<head>
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
</head>
... my html code..
<div id="wrapper">
<div id="container">
<div id="storedvalue"><span>Hello</span> [edit]</div>
<div id="altervalue" style="display:none;"><input type="text" name="changevalue" id="changevalue" value="Hello"> [save]</div>
</div>
</div>
I have never been able to successfully run a JavaScript that wasn't on W3 yet. I get the same problem with other scripts even though I see people online saying they work fine for them. Do I need to do anything extra to make this work?
My two questions are:
What am I doing wrong?
Because Javascript seems to just not work when there's a problem, is there a way to get errors or information on what's actually wrong?
I read Uncaught ReferenceError: $ is not defined? and have been trying to figure this out for the last hour and can't see my problem.
First you need to place the jQuery script tag first.
Second, you need to do one of the following things:
Put your code within this function:
$(document).ready(function(){/*CODE HERE*/});
Or like this:
$(function(){
/*CODE HERE*/
});
The DOM needs to be ready before you can use it. Placing your code within anonymous functions that are executed on the ready event of the DOM is how you can do this.
Edit:
$(function(){
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});​
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Script tag for jQuery should come before your custom javascript.
Follow by edit.js
<script type="text/javascript" src="static/edit.js"></script>
Try removing the language attribute..sometimes work for me. It's obsolete now .. i think
You need to include jquery before you can use it.

javascript error: this.node is null or not an object

I am working on ASP.NET 3.5, c#, visual studio 2010. I have made a master file and a default page that uses this master file. I have placed a couple asp:contentplaceholders in the master and corresponding code in the page that uses this master. I have also inserted JavaScript like this in the content page (and not the master):
<asp:Content ID="Content6" ContentPlaceHolderID="Mainpage" Runat="Server">
<script src="path1" type="text/javascript"></script>
<script src="path2" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var options = {
//some java code
};
$(".mycssclass").effect(options);
});
</script>
</asp:Content>
On running the website I get the following runtime error in visual studio:
Microsoft JScript runtime error: 'this.node' is null or not an object
and it point to some function inside the JavaScript like
this.node.onload=function(){..............//I am not a java guy so do not know much about this
Where am I going wrong? Why does the site compile correctly but throw this runtime error?
I also tried inserting this java code inside the master file in the <head>, but same error. This is urgent please so if someone experienced can pinpoint where exactly to put the code that would be solve my problem quickly.
Have you included a reference to the jQuery library? A good practice would be to have the jQuery include in the Master.
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<!-- the remainder of your .js references should follow-->
</head>
If it's your intention to have that script run on 'page load', then ensure you have it set correctly:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
More info on jQuery document ready.
I'm not sure exactly what it is you are doing with that snippet of code, but I don't think it is the proper syntax.
You probably should re-write it to look like this:
$(document).ready(
function () {
var options = {
//some java code
};
$(".mycssclass").effect(options);
});
Just passing in the function to the jQuery selector will probably get some wonkiness.
Thank you everyone! there was no problem with either the syntax in the javascript or the location/page where it was first included by me. I just figured out that the mistake was somewhere else. This javascript works on an <img> tag. It zooms the image insdie the <img> tag. I was using the <asp:ImageButton> instead og <img>. It works perfect as soon as I replaced it. Thank you all for your time and the knowledge sharing.

Categories