I'm a beginner with limited knowledge of both Javascript and html, sorry if my questions are very basic.
I'm trying to write a basic webpage that will do something to an array using Javascript when a button is clicked, then print the result to the page.
<!DOCTYPE html>
//error here
<html>
<head>
<title>Thursday's Homework</title>
<script>
var problem1 = function()
{for (var i = 0; i <= 50; i += 5) {
document.write(i + " ");
}
}
var myArray = []
var problem2 = function()
{for (var i = 0; i <= 9; ++i){
myArray[i]
}
document.write(myArray)
</script>
</head>
<body>
<center><h2><b> My Homework for Thursday<b></h2></center>
<p>This is my code for Problem 1:</p>
<input type="button" onclick = "problem1()" value="Does it work?">
//error here
<p>This is my code for Problem 2:</p>
<input type="button" onclick = "problem2()" value="Does it work?">
//error here
</body>
</html>
I'm getting three error messages when I debug in Chrome using developer tools:
After line 1: Uncaught SyntaxError: Unexpected end of input
After line 22(the first button): Uncaught ReferenceError: problem1 is not defined
After line 24(the second button): Uncaught Reference Error: problem2 is not defined
I'm also wondering if there's a better way to display the outputs than document.write because that makes it so that the page needs to be reloaded each time to see the next result.
I'm new, so my apologies if this is completely the wrong way to create this whole thing. If that's the case, just point me in the right direction.
UPDATE:
I've fixed the syntax errors and it's running fine. I'm still wondering about a better way to display my result that document.write. I'm not too knowledgeable, so if you have a suggestion, could you give me an idea of how to implement it?
You are missing a closing } after problem2.
That is the most common cause for this kind of error. The JS interpreter breaks since the function body is not properly closed, stops parsing. Then something else tries to reference a variable/function that failed to get parsed and triggers the Reference Error.
I can see a few issues.
You are missing a closing } after problem2.
You have spaces around your = for onclick =.
You're not actually doing anything with myArray. That does not seem intentional.
Your code formatting is unclear and that can lead to difficulties later (and I think this, in part, caused the bug). Unless you have a particularly good reason you should avoid things like {for. Instead add a newline after the {.
close the brace of problem2();
instead of document.write(); u can specify a id like
or
and in the js use
document.getElementById("abc").innerHTML=i+" ";
for better and safer coding use jsLint ..
As for you second question, you can find a lot of helpful extensions for both Chrome and Firefox that can satisfy you for debugging.
Chrome has internal tools such as "Web Console" that allow you to watch variables for exemple.
Related
i am trying to add a tag (to custom javascript) to my google tag manager, but i get "Error at line 12, character 5: Parse error. primary expression expected". Can i please get help to correct my code?
<script>
var x=document.getElementById("ad"),
z=window.getComputedStyle(x,null),
y=z.getPropertyValue("display");
function showAdblockAlert()
{alert("You're missing ads, therefore turn off your AD-blocker!")
}function adBlockNotDetected()
{alert("Thank you for not using AD-blocker");
console.log
("no ad-blocker")}console.log(y);
"none",
==y?showAdblockAlert():adBlockNotDetected();
</script>
This code is odd. It combines some basic mistakes as well as advanced techniques if you can call that a ternary or using commas with a var.
Anyhow, your error is likely due to poor copying. The "none",== part, I think, got there from somewhere else.
Here, try this:
var x = document.getElementById("ad"),
z = window.getComputedStyle(x, null),
y = z.getPropertyValue("display");
function showAdblockAlert() {
alert("You're missing ads, therefore turn off your AD-blocker!")
} function adBlockNotDetected() {
alert("Thank you for not using AD-blocker");
console.log("no ad-blocker")
}
console.log(y);
y ? showAdblockAlert() : adBlockNotDetected();
You should know, however, that alerts in production is a very good way to get your site blacklisted one way or another.
Besides, declaring globals like that is a very bad idea.
Your code is unsafe. It relies on getComputedStyle to be there, as well as other elements. It throws errors otherwise.
Finally, the use of functions there seems to be a little excessive. They're not needed if you swap the ternary with a normal if, making the code much more readable.
IE8 has been throwing this error at me
SCRIPT65535: Unexpected call to method or property access.
load-scripts.php, line 4 character 25690
I removed a .js file from the code, and the error went away. I started commenting functions out, and narrowed it down to this one. With this one commented, I don't get the error. With it active, I do get it
$("title, .ab-item").each(function() {
var text = $(this).text();
text = text.replace("RepAgent", "Review Scout");
$(this).text(text);
});
I've used JSHint and it says that it's valid?
I'm pretty sure that Internet Explorer doesn't like you messing with <title> element contents. That's not really how you set the document title anyway; just set document.title.
jQuery uses appendChild inside $.text() .
Although <title/> has a appendChild-method(inherited from HTMLElement), this method may not be used.(it's also not listed in the title-methods)
I have a problem with our website. I am trying to replace all occurrences of one phone number with different one.
If you go to www.paintballgames.co.uk you will see the regular page
If you go to www.paintballgames.co.uk/?test=phtest you will see one with changed number
However the rotator is not working in the second case.
I tried to compare source codes and only difference was, that in second case, I had some code that is changing the code displayed.
The code I am using is:
<script type="text/javascript">
var str = document.getElementById('forChange').innerHTML;
str = str.replace("844 477 5050", "844 477 5178");
document.getElementById('forChange').innerHTML = str;
</script>
Anyone can share any light on that?
First of all I see an exception with javascript even on the regular site:
$("#container-inline").html("<input type="image" name="op" value="GO" id="search-form-submit" class="form-image" />");
This will not work, as you should either escape quotes or use single quotes:
$("#container-inline").html("<input type=\"image\" name=\"op\" value=\"GO\" id=\"search-form-submit\" class=\"form-image\" />");
or
$("#container-inline").html("<input type='image' name='op' value='GO' id='search-form-submit' class='form-image' />");
UPDATE:
And one more exception in "click_heatmap.js":
Drupal.behaviors.click_heatmap = function()) {
// the "function()) {" is invalid. It should be "function() {"
click_heatmap.js:6 Uncaught SyntaxError: Unexpected token )
if (window.location.href != parent.location.href) {
$('#admin-menu').remove();
}
}
UPDATE 2:
It is possible, that after fixing the errors, you'll see the root of the problem.
UPDATE 3:
Why at all you are changing the phone number in Javascript and not on your server side?
UPDATE 4:
Now I've got even more interesting things! The 'forChange' element is almost the whole site wrapper! You should never write such code!
Instead of that you should have done this:
$(document).ready(function() {
$("SPAN.phone-now").text("your text");
});
UPDATE 5:
Now I can explain, why Javascript stops working. When you write something like body.innerHtml = body.innerHtml.replace(...) ALL the Javascript, which was there gets lost and the new one is not executed. So, nothing works! All references, which were saved in Javascript they point to not visible "old" elements.
I have a simple rotating banner javascript on the site I'm developing. It works perfectly locally, on IE, Firefox and Safari but not on Chrome. Is there something wrong with my code? I'm new to Javascript so this problem is really baffling me. Here's the relevant code:
<script language="Javascript" type="text/javascript">
adImages = new Array
("images/AMSite18.png","images/AMSite19.png","images/AMSite09b.png")
thisAd = 0
imgCt = adImages.length
function rotate() {
if (document.images) {
thisAd++
if (thisAd == imgCt) {
thisAd = 0
}
document.adBanner.src=adImages[thisAd]
setTimeout("rotate()", 3 * 1000)
}
}
</script>
</head>
<body onload="rotate()">
<div id="banner">
<img src="images/banner1.gif" name="adBanner" alt="Ad Banner" />
</div><!-- end banner -->
</body>
It looks like the reason it isn't working in Chrome is this line:
document.adBanner.src=adImages[thisAd]
You're referring to the element with the name "adBanner" via document.adBanner, but Chrome doesn't support that. You'll have to use something like this:
document.getElementsByName('adBanner')[0].src = adImages[thisAd];
Some others things that could improve code quality:
Don't use the language attribute. Not necessary.
Use the format var x = [...]; to create a new array. There's no reason to use the constructor format. None at all. Zippo. No one could possibly comment on this answer with a reason you'd use new Array(...) instead. No one.
Use the var keyword to create variables, and the semi-colon to end your statements. Although it isn't hurting anything here, if you don't use var, then JavaScript assumes you're creating/changing a global variable, when that may not necessarily be the case. (Also, the semi-colon rules may be a little convoluted, but it really helps with readability.)
Why are you checking for document.images? It's unnecessary. You don't refer to it anywhere else.
Crockford suggests using x += 1 instead of x++. Not a big deal, and a lot of people disagree, just something I noticed.
Always use strict equality (===). The kind you're using (==) doesn't take into account types; 2 == "2" will return true, but 2 === "2" will not. Again, not a big deal, and some people don't really care, but it could bite you later on, in a different project.
Never pass strings to setTimeout. The browser just evals the string, and nobody hangs out with people who eval stuff. You don't even need to pass a string, because you're using a function that doesn't need any arguments! Just use this:
setTimeout(rotate, 3 * 1000);
Try to put script tags at the bottom of the body. There are two reasons for this. First, performance. When the browser gets to your script, it stops everything to parse and execute the code. If you put it at the bottom of the body instead of the head, the page will at least appear to load faster. The second point is addressed next:
Try to avoid using onload. It's just gauche. The reason you need to is because your script is in the head, and has no access to the DOM just yet. But if that script was moved to the bottom of the body (which, for some reason, you might not be able to; no big deal), you wouldn't have to mess with onload at all:
<body>
<div id="banner">
<img ... />
</div>
<script>
// Copy all of your code exactly the same,
// and then:
rotate();
</script>
</body>
For the love of god, don't use the name attribute. For forms, who cares? But when you're manipulating elements with JavaScript, use the id. It's immediately obvious what you're doing, and document.getElementById('adBanner') is way faster than document.getElementsByName('adBanner')[0].
You should start by fixing the syntax problems.
Lines should end with a semi-colon ;, variable should be declared with var and you should use [] rather than new array, pass a function to setTimeout rather than a string
var adImages = ['images/AMSite18.png','images/AMSite19.png','images/AMSite09b.png'];
var thisAd = 0;
var imgCt = adImages.length;
function rotate() {
if (document.images) {
thisAd++;
if (thisAd == imgCt) {
thisAd = 0;
}
document.adBanner.src=adImages[thisAd];
setTimeout(function(){
rotate();
}, 3 * 1000);
}
}
This may not fix it, but you you should do it anyway :)
I just ran you code on Chrome 11 on a Mac and it worked. Even with the syntax errors. But Paul is right you should always write valid JavaScript.
Also this is a better way of passing functions
setTimeout(rotate, 3 * 1000);
I copied this code from an example. I've read it 100 times.
Array.prototype.map = function(fn) {
var r = [];
var l = this.length;
for(var i = 0; i < l; i++) {
r.push(fn(this[i]));
}
return r;
};
Why does Firefox say:
not well-formed
file:///some/path.html Line: 5
for(var i = 0; i < l; i++) {
-------------------^
UPDATE
The error is only shown when Firebug is turned on for the page.
You are using Javascript code in an HTML page claiming to be fully XHTML-compliant. Therefore, the < character cannot appear in the Javascript, as it would be interpreted as the beginning of an XHTML tag.
There are a number of ways to fix this.
You could change the DOCTYPE and make it not XHTML.
You could enclose the Javascript in a <![CDATA[ section.
You could move the Javascript into a separate .js file.
You could escape every occurrence of < with < and every & with &. I do not recommend this option; it'll make your code unreadable and will almost definitely not work in IE.
Likely your error isn't in this code, but something above it trickling errors down. So, instead of finding an error in this code, look above for malformed HTML or javascript that could be causing this error instead.
If I use the following HTML and your text as "test.js", I too get no errors in Firebug.
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
test
</body>
</html>
Works for me. Please post the full file, and make sure you are using script tags.
I posted a validating pastebin file (Chetan's was technically not valid), and it works fine with Firebug. So I suggest you come back with a full page of validating code that doesn't work.