basic javascript alert not working in Intel XDK code editor - javascript

I'm starting fresh with a new blank Intel project and I haven't even started coding yet. I'm just setting up my file tree and making sure the html and javascript pages are connected via the right anchors and script paths. My first .js file won't work though.
I've included a screen shot of test code and the errors. I know the syntax is correct because it works when I put it in <script> tags in the index.html file.
I'm getting "document not defined" and "alert not defined" errors or the js page though. I don't know what that means.
I've considered that my script tag src path in the index file is incorrect, but all the paths are relative in the commented out template script tags intel provides on the index page right out of the box, so why would I have to use an absolute path?
My path is: js/Test.js and it's the last script tag before the body.
Index.html file
*****UPDATE****
So I've tried a few things and it's still not working but I HAVE managed to get my errors down to just one inexplicable "missing semicolon", which will turn into an "unnecessary semicolon" error if I place it.
Any way as per the first screen shot you'll see that I wasn't placing the document object inside of an explicitly declared variable. Once I did that and accessed it through dot syntax instead of an equal sign then I stopped getting the error. I included this screenshot to show my work before I made the changes.
so the problem I went on to have is that unless every function or dom object was declared with "Var", I'd get an error. This includes the alert() function which I don't think I've ever seen needing to be declared that way, but I gave the code editor what it wanted and this last screenshot is the results. It's not working, BUT I'm not getting the errors I was before, except for the missing/unnecessary semicolon paradox. Removing it or including it throws an error.

JavaScript can be loaded before or after the HTML, however the way it is done is slightly different depending on how you do it.
For example if you wish to include your JavaScript files within the head of the HTML file then you must wrap your JavaScript code with either DOMContentLoaded or jQuery's $(document).ready().
The common misconception of using window.onload will not fix the issue where the elements have not loaded in correctly.
The Mozilla Developer Network states on this page:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event - load - should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
That quote in itself should prove that onload should not be relied on if you want the full DOM to be loaded properly before you start manipulating it. Instead you should do the following:
Vanilla
document.addEventListener("DOMContentLoaded", function (e) {
/** DOM has been fully loaded here, so manipulation can begin. **/
/** Your code here. **/
});
jQuery
$(document).ready(function () {
/** DOM has been fully loaded here, so manipulation can begin. **/
/** Your code here. **/
});
Click this link to see the difference between vanilla and jQuery.
The second way you can load JavaScript is by having all the script tags within the body but after all the HTML, that way it is guaranteed to load after the HTML.
Example
Try this working example I quickly coded up.
HTML
Replace the content within the body tag of your HTML to the following:
<button id="myJsTest">Click Me!</button>
<div id="clickCounter">Click Count: 0</div>
Replace the contents of your JavaScript with the following:
JavaScript
document.addEventListener("DOMContentLoaded", function() {
var clickCount = 0;
document.getElementById("myJsTest").addEventListener("click", function() {
clickCount++;
document.getElementById("clickCounter").innerText = "Click Count: " + clickCount;
});
});
Then use the Emulate tab in Intel XDK to test it.
Additional Information
When I use Intel XDK and I have an error, I quickly load the file in to the browser and check the console. It can be a really helpful and effective way of squashing those pesky little bugs.
Try using window.alert as alert is defined in the window object.

The reason you're seeing all those "error" messages in the editor window is because you've got the various JSLint/Hint tools loaded in the editor. They're trying to keep you honest and save you lots of time in the debugger chasing potential syntax errors.
The editor inside the XDK is Brackets, it is using standard Brackets extensions to provide those JSLint/Hint tools. You can download it and run it standalone on your system and edit directly within it, you don't have to use the editor inside the XDK (or you can use any other editor you like).
Because the Lint/Hint tools only look at one file at a time, and because your app is normally spread over multiple files, they don't know much about about what's defined in your other files. Likewise, those hint/lint tools need to be told that you're using some of the standard global methods and properties that are expected to be found in a browser (but which may not be found in other JavaScript environments, because JavaScript is no longer limited to just a browser environment -- in fact, your XDK app, aka Cordova app, runs inside a "webview" not in a browser, but that's another story...)
So, you should follow some standard practice of setting up your JSHint/Lint directives at the top of your JS files. For example, this is a good starting point:
/*jslint browser:true, devel:true, white:true, vars:true */
/*global $:false, intel:false */
See the JSHint documentation for details... and see the "Blank Cordova Starter App" in the "Start a New Project" section of the Projects tab for a better blank template to start (there is no real difference between a blank template and a demo app, they are structured identically).
For a more complete and even more instructive app, see the "Hello, Cordova" sample app. Both of those apps can also be found on the Intel XDK GitHub repo.

You are adding the js file that is <script src="js/Test.js"></script> inside header tag.
So js will be first loaded and and it will attach all events to it. But when js is loaded button id="jsTest" is not present because DOM is not loaded.
Solutions :-You can follow either of the approach
Add your js files after DOM is ready
<body>
<button id ="js/Test.js">Test JS</button>
// other HTML tags
<script src = "js/Test.js></script>
</body>
Use window.onload
The load event fires at the end of the document loading process.
window.onload = testJsFile(){
//Your code goes here
}
I will prefer to use the first approach since that also address other issues like page loading time

Try to put the line outside your JS function
document.getElementById(......
inside your html page between
<script>HERE</script>
If this is still no working. Try to add onClick attribute to the button like this:
<button id="" onClick="testJsFile()">
Its also good to use google chrome element inspection while devlopping cuse it will give you error msg for all these things.

Related

Javascript returns null in Chrome, HTML element in source

I am trying to read this HTML in the console in Chrome:
<span id="lblSummaryFreight">Kr 79</span>
Using this JS:
document.getElementById('lblSummaryFreight').innerHTML;
However, after the page has loaded, running this line returns null or invalid. If i inspect the element and then run the code, it works as intended and returns "Kr 79". So, is it some kind of DOM issue I am not aware of, or a browser-specific issue?
I am using this as a variable in Google Tag Manager, and it works in 50% of the cases. I don't have access to the source code of the webpage itself, so that's why I need to lean on this rather clunky way of getting the data.
A lot of posts on this suggest that this is because the script is fired before the DOM is ready, but I don't think this is an issue, as I am also testing this in the console after the page has loaded (and the HTML elements are present), and in Google Tag Manager I have specified that the tag should fire after DOM is ready.
Any clues?
Edit / Clarification: I can't alter the code of the page itself, only read the output source, which i am trying with JS via GTM
Don't seem to be able to resolve this issue, and as it seems to be the fault of some quirky source, I will try to figure out another way to get the data I need.
What I have learned:
The issue seems to be specific to Chrome, as it works in other browsers. This is supported by the fact that the GTM tag where this code is implemented returns correct values in ~50% of the cases
Testing the page in Android native browser, it will also return 'undefined'. After reloading the page that fires the tag, it returns correct value.
The whole DOM seems unavailable in the console. Tried also this:
document.getElementsByClassName('complete').length
Which returns 0, but there are around 10 instances of the class in the source. After inspecting anywhere on the page, it returns correct number.
Any delay in running the script won't help, only the symbolic inspecting of elements or reloading the page helps.
So my conclusion is that the way this webpage is built somehow goes against the grain of some browsers - it seems like the source goes out of the memory after the source is loaded. But this is way beyond my level of understanding.
Thanks all for all inputs!
It looks like an async issue. Try this:
//Using Jquery
$( document ).ready(function() {
document.getElementById('lblSummaryFreight').innerHTML;
});
or
//Add this at the end of the body, after all of your content
<script>
(function() {
document.getElementById('lblSummaryFreight').innerHTML;
})();
</script>
Try to change how the tag is fired in GTM. Fire them when Window Loaded, and try again.
Maybe the element is being changed in another js file.
Trying jQuery is a good point. I have had similar problems and jQuery have solved them all.

Debug a script that sits in a partial view

Why I can't debug scripts that reside in a partial view, that gets created in runtime?
To see the script in the list of scripts (in Chrome for example) and debug it, I have to move it to the "regular" view on the upper level or I have to move it to a separate .js file.
But what, if the script so small that I don't want to move it anywhere, and still want to be able to debug it?
If you do not load the partial view via ajax (the view is in place at the initial page rendering) you can use 'debugger'. If the code you want to run is added to the dom IE will not know where the actual code is located that you want to debug. So:
// javascript
var foo = 2;
debugger;
// more javascript
There's a much better way to do this now, just use the syntax
//## sourceURL=someValue
immediately after opening your script tag. Example:
<script type="text/javascript">
//## sourceURL=_fooPartialView.cshtml
function foo() {}
</script>
--edit--
Apparently due to some IE compatibility issue javascript source mapping has been changed from the above to:
//# sourceURL=_fooPartialView.cshtml
Also note, although not mentioned earlier, the ## was only necessary for source mapping in razor views since "#" had other significance.
It's generally considered poor practice to include a script inside of a partial view. You could run into all kinds of issues with multiple script references and performance. The better approach here is to ensure the script gets moved up to a placeholder in your head tag. For a few examples on this, check out:
Linking JavaScript Libraries in User Controls
and
Include JavaScript file in partial views
If you insist on loading the script from the partial, the 'debugger' approach above is very effective.

Is it OK to put javascript code anywhere in HTML code?

I see that Javascript code is normally in heading part of HTML code.
<head>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</head>
Is it OK to put the Javascript code in a body part of HTML code? I tested it, but it seems to work.
<body>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</body>
If so, why the examples of Javascript books put the javascript code in heading part?
If not, what's the difference between putting the javascript code in body/heading part?
Not only is it OK, it's actually better, since it lets the content come first.
If your viewers have a slow (eg, mobile) connection, it's better to send the actual content first, so that they can read it while the browser downloads the Javascript.
All the people saying it is better only applies if you are talking about at the bottom of the page (and that is an up for debate thing) from a code quality point of view, it is NOT ok to sprinkle script tags through your html. All references to javascript should be in a single place on the page, either the head (where they should be), or the very bottom (as a perf optimization)
Edit:
Basically, a web page is made up of 3 pieces; style (css), structure (html), and behavior (javascript). These pieces are all very distinct, so it makes sense to keep them as separate as possible. That way if you need to change some javascript, it is all in one place. If it is sprinkled through the file, it becomes much more difficult to find the code you are looking for, and that code basically becomes noise when you are just looking at structure.
It is the same arguments as why not sprinkle db access code all over your page. It has nothing to do with technical reasons, purely an architectural/design decision. Code that does different things should be kept separate for readability, maintainability, and by extension, refactorability (not sure if that last one is actually a word...)
You can do it, and people often do.
For example, people like to put their script tags just before the closing </body> to make web pages render quicker.
Also, if you do a script block after an element is created, you don't need to wait for DOM ready.
Be warned though, don't add, or remove an element from an unclosed ancestor in the markup tree (not including the script block's immediate parent element), or you will get the dreaded Operation Aborted error in IE.
Just something to add on:
I have preference of putting Javascript file right before </body>. My reasons being that:
Content can load and be shown first. If you load huge Javascript files first, which most are meaningless until the page is loaded, the user won't be able to see anything until the JS files are loaded.
Most Javascript code require to work with the UI can only run after the UI has been loaded. Placing the codes at the end of the html file reduces the need to use the onload event handler.
It is very bad habit to place Javascript snippets all over the HTML file. Placing all at the back of the HTML file allows you to manage your Javascript more efficiently.
It is legal according to the spec.
Most examples use them in the header as the headers come first and the browser will be able to parse the reference and download the JS files faster.
Additionally, these are links and are not part of the display, so traditionally, put in the header.
It is perfectly legal but there seem to be some differing opinions about it. Those who say to put all the javascript references in the head argue that the script is downloaded before the rest of the page become visible and dependent on it. So your user will not see an object on screen, attempt to interact with it and get an error because the javascript code is not yet loaded.
On the other hand, the argument goes that it takes longer to load all the script before the user sees the page and that can have a negative impact on perceived speed of your site.
JavaScripts inside body will be executed immediately while the page loads into the browser
Placing javascript at the end of the body will defer javascript load (ie: the page will render faster), but remember that any javascript function used for an event should be loaded before the event declaration, it is mainly because users may be able to fire an event before the page is completely loaded (so before the function is loaded)!
I used to put it in the head, then I've heard that it takes longer for the page to load so I started placing the scripts at the very bottom. However, I found out the most 'clean' way to do it is to place it in the head BUT you place the script inside a document.ready function. This way you have the best of both worlds. It is cleaner because it is in the head and it is not loaded before the content has been loaded, so there aren't any problems performance wise either.
With jQuery for instance, you can do it like this:
$(document).ready(function() {
alert('test');
});
The alert will only popup when the page has been fully loaded, even though the script is in the head.

onload Event in embedded SVG not calling function in attached script. Scope Issue?

So I've got an XHTML page with a script - not inline
> <script type="text/javascript"
> src="../global/js/scripts.js"></script>
and an embedded (I tried embed and object, same behavior) SVG document with a onload="CheckIfLoaded(evt)" attribute.
The problem is firefox doesn't call the CheckIfLoaded() function in scripts.js. Firebug gives me "CheckIfLoaded() is not defined" with no reference to any line numbers. I can't find any information regarding the scope of javascript functions with respect to embedded content. Curiously, it works fine in IE.
I could of course add a reference to the script into the SVG file as well but I believe that will result in the client downloading the scripts file twice and in addition I have 1000+ svg files and I'd really rather not add one line to all of them, although I suppose I could write a batch file or whatever if I have to.
Any one know more about this?
Do you have the onload on the svg element or on the object/embed tag?
Sounds like you want to call functions in the referencing ("parent") document, see examples here.
Are you sure that the script is getting loaded? Are there errors in the error console? If you put an alert() in the script, do you see it? (Before or after an alert() that you put in the onload handler?)

Is possible to debug dynamic loading JavaScript by some debugger like WebKit, FireBug or the IE8 Developer Tool?

From my recent question, I have already created some JavaScript functions for dynamic loading of a partial view. But I can't debug any dynamic loading JavaScript. Because all of the loaded JavaScript will be evaluated by the "eval" function.
I found one way to create new JavaScript by using the following script to dynamically create the script into the header of current document. All loaded scripts will be displayed in the HTML DOM (and you can use any debugger to find it).
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.text = "alert('Test!');";
document.getElementsByTagName('head')[0].appendChild(script);
By the way, most debuggers (IE8 Developer Toolbar, Firebug and Google Chrome) can’t set breakpoints in any dynamic script. Because debuggable scripts must be loaded the first time after the page is loaded.
Do you have an idea for debugging when using dynamic script content or a dynamic file?
Update 1 - Add source code for testing
You can use the following xhtml file for trying to debug someVariable value.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dynamic Loading Script Testing</title>
<script type="text/javascript">
function page_load()
{
var script = document.createElement('script')
script.setAttribute("id", "dynamicLoadingScript");
script.setAttribute("type","text/javascript");
script.text = "var someVariable = 0;\n" +
"someVariable = window.outerWidth;\n" +
"alert(someVariable);";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
</head>
<body onload="page_load();">
</body>
</html>
From answer, I just test it in FireBug. The result should be displayed like below images.
Please look at the "dynamicLoadingScript" that is added after page load.
But it is not found in the script tab of FireBug
Update 2 - Create Debug Breakpoint in dynamic loading script
Both of the above images show inserting "debugger;" statement in some line of the script can fire a breakpoint in the dynamic loading script. However, both debuggers do not show any code at breakpoint. Therefore, it is useless to this
Thanks
It would also be possible to use chrome for the same. Chrome has a feature where you can specify a parser attribute and make the piece of dynamic JS appear as a file which can then be browsed to and break points set.
the attribute that needs to be set is
//# sourceURL=dynamicScript.js
where dynamicScript.js is the name of the file that should show up in the script file browser.
More information here
Paul Irish also talks about it briefly in his excellent talk on Tooling & The Webapp Development Stack
Try adding a "debugger;" statement in the javascript you're adding dynamically. This should cause it to halt at that line regardless of breakpoint settings.
Yes, It is (now) possible to debug dynamically loaded JavaScript using Google Chrome!
No need to add extra debugger; or any other attribute for dynamically loaded JS file. Just follow the below steps to debug:
Method 1:
My tech lead just showed a super-easy way to debug dynamically loaded Javascript methods.
Open Console of chrome and write the name of the method and hit enter.
In my case, it is GetAdvancedSearchConditonRowNew
If the JS method has loaded then it will show the definition of the method.
Click on the definition of the method and the whole JS file will be opened for debugging :)
Method 2:
As an example, I'm loading JS file when I click on a button using ajaxcall.
Open network tab in google chrome dev tools
Click on a control (ex. button) which loads some javascript file and calls some javascript function.
observe network tab and look for that JS function (in my case it is RetrieveAllTags?_=1451974716935)
Hover over its initiater and you'll find your dynamically loaded JS file(with prefix VM*).
Click on that VM* file to open.
Put debugger whereever you want in that file :D
I'm using google chrome for that purpose.
In chrome at scripts tab you can enable 'pause on all exceptions'
And then put somewhere in your code line try{throw ''} catch(e){}. Chrome will stop execution when it reaches this line.
EDIT: modified image so it would be clearer what I'm talking about.
I think you might need to give the eval'd code a "name" like this:
http://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
If you do, I think it's likely the debugger approach from "update 2" should work then.
UPDATE: the syntax for sourceUrl has been changed (# is replaced by #) to avoid errors on unsupported browsers (read: IE). Details
Using Chrome(12.0.742.112) with the code you provided plus a debugger statement like this
script.text = "debugger;var someVariable = 0;\n" +
"someVariable = window.outerWidth;\n" +
"alert(someVariable);";
works for me.
I need to modify some JavaScript (limiting scope of all jQuery selector to current partial >view div) before execute it.
May its more tangible if you bind the selector change to an event on your partial view instead of creating script elements in the html body ( doesnt feel right ).
You could do something like this
(function(j)(
var limiting_selector = '';
j(".partial_views").bind('focusin over',function(e){
limiting_selector = j(this).attr('someattr') // or j(this).data('limiting-selector')
}).bind('focusout out',function(e){
limiting_selector = '';
});
// And then go on with
// j(limiting_selector+' .someclass')
))(jQuery)
This code would always add a limiting selector to all jQuery select operations done while the mouse is in a certain element given the HTML isnt to messed up.
(Still seems hackerish, may be someone has a better solution)
cheers
In Firebug, you should be able to see that script after the page is loaded and the script is injected. When you do, you can set a breakpoint in the appropriate place, and it'll be preserved when you refresh the page.
Dynamicly loaded Javascript still has to be parsed by the browser this is where WebKit, or FireBug debugger is sat so it's subject to the debugger no matter what, i think this is the same for the developer tools in IE8,
So your code is subject is to the debugger so where your getting a problem will not be in that file or text if it does not error
The other thing is script.text = "alert('Test!');"; is not valid so it wont work in all browsers what you want is script.innerHTML = "alert('Test!');";
even though its innerHTML it means code inside the HTML Tags not the HTML inside just the most use people use it for this so it gets explained wrong
EDITED FOR UPDATE TWO
And on Second update using Chrome i did this
go to about:blank
Open the console up and past in
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.innerHTML = "alert('Test!');debugger;";
document.getElementsByTagName('head')[0].appendChild(script);
then it will break and open the script tab with about:blank shown (nothing to see)
Then on the right hand side show the call stack list, then click on the second (anonymous function) and it will show you.
So on your file you will have a (anonymous function) that is the code your running and you will see the break point in there. so you know your in the right one.
Using Google Chrome (or Safari) Developers Tool, you can run JavaScript line by line.
Developer Tool > Scripts > Choose which script you want to debug > pause sign on the right side
Or set breakpoints by click the line number
One option I like to use it adding a console.log('') statement in my code. Once this statement appears in the console a line number is associated with it. You can click that number to go to the location in the source and set a breakpoint. The drawback to this approach is that breakpoints are not preserved across page reloads and you have to run through the code before you can add a debugger.

Categories

Resources