Run JavaScript embeded in HTML from FireBug - javascript

I have just started working through Professional JavaScript for Web Developers and am trying to run the code as I go along. I have hit a wall early on with trying to embed JavaScript in a HTML document. If I define a function and call it in the same document, nothng happens. Similarly, if I define a function in the document and call it from either the Firefox scratchpad or FireBug nothing happens. I can however run the whole thing (define the function and call it) from the scratch pad or FireBug.
The code I am using for the page is:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<script type="text/javascrtipt">
function compare(a, b) {
if (a < b) {
alert ("A is less than B");
} else if (a > b) {
alert ("A is greater than B");
} else {
alert ("A is equal to B");
}
};
</script>
</head>
<body>
<p>Paragraph 1</p>
<script type="text/javascript">compare(5, 6);</script>
</body>
</html>
I have found similar questions like the one below which I think answers my question but I don't understand it enough to apply it to my scenario. How would I make the function above global (if that is whats needed here)?
Calling custom functions from firebug console
Thanks,
Ger

The problem here is not in your logic, rather it is in a simple typing error.
Where you specify the script type in the head, you misspelled javascript - correct that and the script executes.
Further to this, it may be worth mentioning that, when using the HTML5 doctype, you omit the script type if you wish because this is now the default for HTML5 documents.

After correcting the typo "text/javascrtipt" the compare function can be successfully called from Firebug console (command editor) with, e.g.
compare(3,4);
and a following click on "execute". Tested with Firefox 24.0 / Linux.

Related

Trace and log all javascript functions calling tree/graph?

Is it possible to see all javascript function calls as a tree in any web debugger?
UPDATE
I mean debugger could remember each function call, from which other function it was done, also it could remember stack frame per each call and entire DOM snapshot.
UPDATE 2
The following page code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Trace and log all javascript functions calling tree/graph?</title>
<script type="text/javascript">
function init() {
setDiv2("This div text was changed once");
setDiv2("This div text was changed twice");
};
function setDiv2(text) {
document.getElementById("div2").innerHTML = text;
}
window.onload = init;
</script>
</head>
<body>
<h1>Trace and log all javascript functions calling tree/graph?</h1>
<p>Stack Overflow Question #20910262</p>
<div id="div1">This div will not changed</div>
<div id="div2">This div text will change</div>
<div>
<h2>The call graph should be follows</h2>
</div>
</body>
</html>
Should give the following call graph
because setDiv2() function called twice.
In profiler's top-down view it is visible as
where setDiv2() function drawn once. This is good for profiling, but this is not call graph.
So the question persists.
UPDATE 3
Moreover, users should be able to step on each tree node and see the values of all variables and the state of entire DOM tree at the moment, represented by the node.
Your need is obviously a custom profiler. Chrome JS profiler is a good handy tool. but i don't think that is correct tool for you. Also among the others Firebug or Safari profiler (webkits) won't do the job for you. So you need to develop your own custom profiler. since the others are only interested/targeted with CPU time profiling or memory usage profiling or CSS selectors.
You can modify Object.prototype.constructor. so all the global functions you have defined can have special profile method. or borrowed method via Function.prototype.bind() you can populate all the data you need from executions into a special data object. which can be like in a tree hierarchy. Here is the places to start a custom profiler.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
and
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
Let us know if you can complete a custom profiler for javascript. it will be really useful tool for more people including me.
Yes, of course. Every browser has support to debug javascript code. You need to read about in specific browser you use. For example you can open developer tools in Mozilla Firefox by clicking Ctrl+Shift+K. In Internet Explorer you need to click F12 key. For Google Chrome Ctrl+Shift+I. After openning tools, you need to set up breakpoint at which you want to see stack trace, local variables and etc. After setting breakpoint you need to reload web-page, because when page is loaded all js is executed first time, and you can catch after loading, or make some event for catch breakpoint.
try console.trace() in your setDiv2 function , in this case you will see the both tree calls in chrome console.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Trace and log all javascript functions calling tree/graph?</title>
<script type="text/javascript">
function init() {
setDiv2("This div text was changed once");
setDiv2("This div text was changed twice");
};
function setDiv2(text) {
document.getElementById("div2").innerHTML = text;
console.trace()
}
window.onload = init;
</script>
</head>
.....

Using a Javascript function to change link with a button

I have a link that I want to change with Javascript. I've got it working but I want it to all be done on just one line. I must be writing the syntax wrong.
This is what I've got working:
function buttonOne(){
window.location.href='http://www.' + brand() + '.com/';
}
Agent Stats
Ok and when I tried to combine them like this it didn't work:
Agent Stats
I'm sure I've just got the syntax wrong... Any ideas on how to write it so that it works fine?
Your syntax is correct. Using the exact code below works. You'll need to provide more details on the behavior you're experiencing. Are there any errors in the javascript console in your debugger? Does the brand function exist and does it return anything useful?
<html>
<head>
<script>
function brand() { return 'google'; }
</script>
</head>
<body>
Agent Stats
</body>
</html>
EDIT: The debugger is your friend. "Object is not a function" - referring to the anchor tag brand() function call. This is because you have a form with the same name. Rename the form to brand2 and it works fine. http://jsfiddle.net/k6LFB/

onbeforeunload event not firing in my code, but other examples work?

As usual, I want to alert users to unsaved changes when leaving a page. I have this test page:
<html>
<head>
<title>Testing</title>
<script language="JavaScript1.1" src="https://127.0.0.1:8443/scripts/base.js"></script>
<script language="JavaScript1.1" src="https://127.0.0.1:8443/scripts/edit.js"></script>
<script language="JavaScript1.1">window.onbeforeupload=moveAway</script>
</head>
<body onLoad="init()">
Google
</body>
</html>
The moveAway function is defined in "edit.js" like this:
function moveAway ()
return "foo";<br>
}
The event doesn't fire, or at least it just leaves the page silently (using IE8, Firefox 15, and Chrome 20). I've tried breakpointing the function in Firebug and it never gets to the breakpoint. I've tried it from the web server (an SSL server, the test version of which runs at 127.0.0.1:8443) and I've tried opening the file directly with the browser (which is why I used absolute URLs for the first two <script> tags). I've tried removing the "src=" attribute from the script tags.
On the other hand, this page has an example which does work (at least in Firefox):
https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm
There is also a very similar example at MSDN which also works:
http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx
I really can't see the difference between what they do and what I'm doing. can anyone tell me why their code works and mine doesn't?
use jQuery bind function.. it works great for me..
see bellow
$(window).bind('beforeunload', function() {
return "Want to leave?";
});
onbeforeupload , really ? it should be onbeforeunload. Is that a spelling mistake, or is that how your actual code is ?
You have a syntax error, the function should be:
function moveAway () {
return "foo";
}

Accessing javascript variables in different frames in chrome

I am having problems passing javascript values between frames in chrome. In other browsers (Opera and Firefox) it works. The first frame contains the following html:
<script> variable="frame 1 value";</script>
click here
and test.html is:
<html>
<head>
<script>window.onload = function() {
div = document.getElementById("fred");
div.innerHTML="<b>" + top.frames[0].variable + "</b>";
}
</script>
</head>
<body>
<div id="fred">
hi there</div>
</body>
</html>
I have looked on this site and others, and the have seen a suggestion that because chrome pages run in different processes they cannot pass values. Is this true, and if so is there a way around it (cookies?)
Thanks,
russell
(edited) I just found another answer which says this happens only on file protocol. Like the writer of the other question, I am writing an applicaiton meant to be run off a cd, so I need to use file protocol. The version of Chrome I am using is 9.0.
ry
This has something to do with cross-site scripting which may be a security issue. Since Chrome has a very strict behavior on this, it should be impossible to achieve what you want.
Fortunately, there may be a nifty trick that you can use (if your variable is only a string):
Change the link in the first frame to test.html?foo=bar
Read window.location.href in the second frame. This will yield something like "Z:\folder\test.html?foo=bar". Now you can use string manipulation functions to extract the value of foo (in case: bar) from the href.
HTML5 Storage to the rescue! For the first frame:
<script>localStorage.setItem('variable', 'frame 1 value');</script>
click here
And for test.html:
<html><head>
<script>
window.onload = function() {
div = document.getElementById("fred");
div.innerHTML="<b>" + localStorage.getItem('variable') + "</b>";
}
</script>
</head><body>
<div id="fred">hi there</div>
</body></html>
A note of caution: IE7 and some older browsers do not support localStorage. However, you should be able to use if (typeof(localStorage) == 'undefined') {} to detect which method you need to use.
Frames are deprecated since 1997 (HTML 4.0 specification) for many reasons - so the best recommendation is do not use them.
You can also run Chrome with command line argument --disable-web-security, but it is also bad recommendation.

Javascript problem solved, don't understand what the problem was

In the HTML head section:
<script type="text/javascript" src="Scripts/editScripts.js"></script>
Just above the </body> tag(closing tag, bottom of the html page). Also: this is the old code, this is how it was when it was not working:
<script type="text/javascript">if(document.getElementById)initialize();loadEvents();</script>
</body>
</html>
In the editScripts.js file:
/*global document,addFileInput*/
function loadEvents() {
var a = document.getElementById('addField');
a.onclick = addFileInput;
}
var upload_number = 2;
function addFileInput() {
var d = document.createElement("div");
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "addFile[]");
file.setAttribute("size", "35");
file.setAttribute("class", "file");
file.setAttribute("id", "addFile"+upload_number);
d.appendChild(file);
document.getElementById("moreUploads").appendChild(d);
upload_number++;
}
This would not work. I replace the javascript in the footer with this.This is the new code, which does work as I expect it to.:
<script type="text/javascript">if (document.getElementById)loadEvents();</script>
And now it does work... I don't see how leaving out that function call, even though it the function it was referring to doesn't exist, would mess things up so royally.
In an unbracketed if statement, only the first statement is conditional. Every statement following it is unconditional regardless of indentation.
Thus, in the first example, loadevents() executed unconditionally.
The browser would have reported an error when attempting to call the "initialize" function since there was no such function. Therefore, the very next line where you call "loadEvents" wouldn't run. See this example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JS Error Test</title>
</head>
<body>
<script type="text/javascript">
if(document.getElementById) {
initialize();
alert("You shouldn't see me!");
}
</script>
</body>
</html>
In that example, the alert box shouldn't appear because I haven't declared an "initialize" function and the browser will report a JS error. Removing the "initialize" function, however, will cause the alert box to appear.
So that's how by removing the cause of the Javascript error you fixed your problem.
probably because you arent calling your scripts on document load event. so when you called your scripts in the header before your dom fully loaded, none of it worked, but now when you are calling it after the dom loads, it works.
The correct fix for all of this should be calling your scripts after the document fully loads, or at least from the body onload event:
<body onload="initScripts()">
And then add all of the scripts you want to run on page load in the initScripts function.
also, there are much better ways of doing this, for example using jquery, and/or reading this: http://onlinetools.org/articles/unobtrusivejavascript/chapter4.html
You say: "I don't see how leaving out that function call, even though it the function it was referring to doesn't exist, would mess things up so royally." That's inconsistent with the rest of your question, which implies that adding the call messed things up. But I think the text I'm quoting is the correct description.
Here's the real answer. The old code:
if(document.getElementById)loadEvents();
does not call loadEvents if getElementsById is not defined. It's not defined in all browsers.
The new code, instead, you not only leave out the function call: the semantics change as well.
if(document.getElementById)initialize();loadEvents();
always calls loadEvents, so what you want to happen always does.

Categories