Jquery - Unterminated String Constant - javascript

I have a page with jquery on it. It works fine in Firefox, Chrome etc but if I load it in IE, none of the Jquery functions run, and IE's script debugger shows:
Error
A Runtime Error has occurred.
Do you wish to Debug?
Line: 269
Error: Unterminated string constant
Yes No
The line in question is in my (unmodified) jquery.js that is causing the error is
style.left = ret || 0;
It also shows:
Error
A Runtime Error has occurred.
Do you wish to Debug?
Line: 835
Error: Invalid argument.
Yes No
With the line in question being:
ret = style.pixelLeft + "px";
Any ideas?
EDIT:
Seems I may have been looking in the wrong place for the error. If I take this out, it works:
$(".middlebox").children("p").hide();
$(".middlebox").addClass("middlebox_closed", "fast");

The error is not necessarily in the jQuery code, but the argument value being passed as a parameter into a function in jQuery i.e. the step before.
EDIT:
This line is incorrect
$(".middlebox").addClass("middlebox_closed", "fast");
addClass() does not take 2 arguments, just one which is a string for the class that you wish to add. Change it to
$(".middlebox").addClass("middlebox_closed");
and it will work. Or maybe you wanted to add 2 classes, in which case this will work too
$(".middlebox").addClass("middlebox_closed").addClass("fast");
// or this for brevity
$(".middlebox").addClass("middlebox_closed fast");

(maybe) Try using style.left instead of pixelLeft
Also check that style is initialised properly.
What are you trying to achieve by this line? style.left = ret || 0;
Maybe you wanted something like style.left = parseInt(ret)

Related

Strange trouble with javascript code

I have one simple code :
$(document).ready(function(){
$(".button").click(function(){
var f = $(this).closest('form');
if(f != null){
$(f).append('<div class="loadmask"></div>');
}
});
});
as you can see, I want to append a div with class 'loadmask' to the parent form. The strange thing here $(f).append('<div class="loadmask"></div>'); had been encoded to $(f).append("<div class="loadmask"></div>"); and throws a javascript error.
UPDATE:
I have change my code to
$(document).ready(function(){
$(".button").click(function(){
$(this).parent('form').append("<div class='loadmask'></div>");
});
});
still get javascript error:
SyntaxError: missing ) after argument list
[Break On This Error]
$(this).parent('form').append("<div class="loadmask"></div>");
and at eclipse console:
00:57:17,593 ERROR [MinifierUtil:108] 22: 65: missing ) after argument list
00:57:17,593 ERROR [MinifierUtil:108] 22: 79: unterminated string literal
00:57:17,593 ERROR [MinifierUtil:108] 1: 0: Compilation produced 2 syntax errors.
00:57:17,593 ERROR [MinifierUtil:74] JavaScript Minifier failed for
$(document).ready(function(){
$(".button").click(function(){
$(this).parent('form').append("<div class="loadmask"></div>");
});
});
I use eclipse Juno (ecoding project with UTF-8), liferay 6.1 ga-1 and jsf-2.0, icefaces-3 ....
I cannot reproduce your problem. What I suspect is that for some reason there is an additional character encoded in your JavaScript file that gets represented as " by jQuery. &#34 happens to be the entity for quotation mark (") so make sure you don't have that as an extra in your code. Try cleaning your JavaScript source file and try again.
Also note that closest never returns null. If form element is not found, an empty list is returned (this can be easily verified by running the code on a formless page). Thus you could safely write your code simply as:
$(document).ready(function(){
$(".button").click(function(){
$(this).closest('form').append('<div class="loadmask"></div>');
});
});
See this Fiddle for a proof: http://jsfiddle.net/p48Rb/3/
Try using if (f.length), because $(this).closest('form') returns a jQuery object which either has length > 0 (form is the first element) or not (length 0 evaluates to falsy). In other words, f is never null.
I really dont know why, but it seem that my xhtml (jsf2.0) can not decode html char inside script code.
(& symbol on && operator will raise the same error)
just change
$(this).parent('form').append("<div class="loadmask"></div>"); to $(this).parent('form').append("div").addClass("loadmask");
and with &, use a child if statement instead of && will solve its issue.

Illegal Character error in jQuery - regardless of function content

First of all, I've done my research and I did find a bunch of simialr questions. However, I didn't find an answer that applies to my problem. All the examples I found were related to unescaped characters, single/double quote mishaps and the like. I on the other hand am getting this error on the following function:
$('.seq_input').blur(function(){
//var id = $(this).data('id');
//var index = parseInt($(this).val()),
//element = $("#test-list li").eq(id).remove();
//$("#test-list li").eq(index - 1).before(element); // -1 because users like 1 based indices
alert('what?');
})​​​;
As you see I commented out everything and just left an alert, and I'm still getting the error, pointing to the last line of the function. It couldn't have anything to do with other functions because I just added this one alone at the end of my current Javascript.
Can someone please tell me what's going on here? Why on Earth would a function that just alerts something (or even if it doesn't do anything) give an error?
NOTE: error is shown as soon as the page is loaded
There are invisible characters between the trailing semicolon and the parenthesis. I concatenated your code, put it in a string, and called a non-existent function in order to trigger a error (using this method).
'})​​​;'.l()
>>> TypeError: "})\u200B\u200B\u200B;".l is not a function
$('.seq_input') may used on the other functions, try using new id to do that function.

"SCRIPT438: Object doesn't support property or method 'url' " in IE only

I am getting the following error in IE (but not Firefox):
SCRIPT438: Object doesn't support property or method 'url'
AjaxSetup.js?version=7b8dcb65-17d1-437f-9594-0621c779427c, line 28 character 2
There are several other posts with errors like this (for other objects besides url), but all of them seem to have answers along the lines of "such a function doesn't exist in jquery" or "such a function is invalid to use in this context", and neither seems to apply to my situation at least as far as I can tell.
The function containing the line number that the error is referring to is:
function redirectToLogin() {
var redirUrl = $.url().attr("path");
if ($.url().attr("query").length > 0) {
redirUrl += "?" + $.url().attr("query");
}
top.window.location = "/Shared/Logout?redir=" + encodeURIComponent(redirUrl);
return;
}
where line 28 is the second line of the function above.
More strangely, while on the offending page (from which the above function gets called), when I type $.url() or $.url().attr("path") into the IE Developer Tools console, it returns the correct object and string, respectively. The values also seem to stay correct if I "watch" them.
Any help would be much appreciated!
EDIT:
I found a workaround:
function redirectToLogin() {
top.window.location = "/Shared/Logout?redir=" + encodeURIComponent(location.pathname + location.search);
return;
}
This seems to work and achieve the same thing, so I'm posting it in case it helps someone. However, I would still be curious to find out why the original code using jquery was not working.
I would guess if you say it works in the console that the code is trying to use it before $.url() is initialized. Is the url JavaScript included before the AjaxSetup file?

Unexpected call to method or property access in IE 7

For work, I need to get our site working in IE7. Because, as we all know, the corporate world can't upgrade.
I am using IE8's IE7 emulation mode to test the site, and using IE8's wonderful debugger has been a nightmare.
My most recent problem is the following error:
Unexpected call to method or property access. jquery.js, line 113 character 460
I've put console.log commands on every line of my function, and figured out the line that's causing the error.
var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').html('Loading...');
This line works fine in Firefox and Chrome. Oh, and it works fine when entering it into IE8's JavaScript console.
Why would this line give Unexpected call to method or property access? I think the call to the method or property was totally expected.
UPDATE: As per #Pointy's suggestion I broke that line into 3 lines.
var $loading = $('<span/>');
$loading.addClass('span-icon icon-ajax-loader');
$loading.html('Loading...');
Now I'm getting the error on this call $loading.html('Loading...');. Again, if I paste this code into IE8's developer tools and run it, it works fine.
Where are you injecting the content? Have you looked at this question and answer?
Javascript IE error: unexpected call to method or property access
Thanks to #daniellmb and #yoavmatchulsky for helping me fix this issue.
There are actually 3 separate solutions.
Use .text() instead of .html().
var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').text('Loading...');
Wrap the .html() in span tags.
var $loading = $('<span/>').addClass('span-icon icon-ajax-loader').html('<span>Loading...</span>');
Or replace $('<span/>') with $('<span></span>').
var $loading = $('<span></span>').addClass('span-icon icon-ajax-loader').html('Loading...');

Possible cases for Javascript error: "Expected identifier, string or number"

Some users are reporting occasional JS errors on my site. The error message says "Expected identifier, string or number" and the line number is 423725915, which is just an arbitrary number and changes for each report when this occurs.
This mostly happens with IE7/ Mozilla 4.0 browsers.
I scanned my code a bunch of times and ran jslint but it didn't pick anything up - anyone know of the general type of JS problems that lead to this error message?
The cause of this type of error can often be a misplaced comma in an object or array definition:
var obj = {
id: 23,
name: "test", <--
}
If it appears at a random line, maybe it's part of an object defintion you are creating dynamically.
Using the word class as a key in a Javascript dictionary can also trigger the dreaded "Expected identifier, string or number" error because class is a reserved keyword in Internet Explorer.
BAD
{ class : 'overlay'} // ERROR: Expected identifier, string or number
GOOD
{'class': 'overlay'}
When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.
Hope this hint saves you a day of debugging hell.
Actually I got something like that on IE recently and it was related to JavaScript syntax "errors". I say error in quotes because it was fine everywhere but on IE. This was under IE6. The problem was related to JSON object creation and an extra comma, such as
{ one:1, two:2, three:3, }
IE6 really doesn't like that comma after 3. You might look for something like that, touchy little syntax formality issues.
Yeah, I thought the multi-million line number in my 25 line JavaScript was interesting too.
Good luck.
This is a definitive un-answer: eliminating a tempting-but-wrong answer to help others navigate toward correct answers.
It might seem like debugging would highlight the problem. However, the only browser the problem occurs in is IE, and in IE you can only debug code that was part of the original document. For dynamically added code, the debugger just shows the body element as the current instruction, and IE claims the error happened on a huge line number.
Here's a sample web page that will demonstrate this problem in IE:
<html>
<head>
<title>javascript debug test</title>
</head>
<body onload="attachScript();">
<script type="text/javascript">
function attachScript() {
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
document.body.appendChild(s);
s.text = "var a = document.getElementById('nonexistent'); alert(a.tagName);"
}
</script>
</body>
This yielded for me the following error:
Line: 54654408
Error: Object required
Just saw the bug in one of my applications, as a catch-all, remember to enclose the name of all javascript properties that are the same as keyword.
Found this bug after attending to a bug where an object such as:
var x = { class: 'myClass', function: 'myFunction'};
generated the error (class and function are keywords)
this was fixed by adding quotes
var x = { 'class': 'myClass', 'function': 'myFunction'};
I hope to save you some time
http://closure-compiler.appspot.com/home will pick this error up with an accurate reference to the actual line number in the offending script.
As noted previously, having an extra comma threw an error.
Also in IE 7.0, not having a semicolon at the end of a line caused an error. It works fine in Safari and Chrome (with no errors in console).
IE7 is much less forgiving than newer browsers, especially Chrome. I like to use JSLint to find these bugs. It will find these improperly placed commas, among other things. You will probably want to activate the option to ignore improper whitespace.
In addition to improperly placed commas, at this blog in the comments someone reported:
I've been hunting down an error that only said "Expected identifier"
only in IE (7). My research led me to this page. After some
frustration, it turned out that the problem that I used a reserved
word as a function name ("switch"). THe error wasn't clear and it
pointed to the wrong line number.
Remove the unwanted , sign in the function. you will get the solution.
Refer this
http://blog.favrik.com/2007/11/29/ie7-error-expected-identifier-string-or-number/
This error occurs when we add or missed to remove a comma at the end of array or in function code. It is necessary to observe the entire code of a web page for such error.
I got it in a Facebook app code while I was coding for a Facebook API.
<div id='fb-root'>
<script type='text/javascript' src='http://connect.facebook.net/en_US/all.js'</script>
<script type='text/javascript'>
window.fbAsyncInit = function() {
FB.init({appId:'".$appid."', status: true, cookie: true, xfbml: true});
FB.Canvas.setSize({ width: 800 , height: 860 , });
// ^ extra comma here
};
</script>
This sounds to me like a script that was pulled in with src, and loaded just halfway, causing a syntax error sine the remainder is not loaded.
IE7 has problems with arrays of objects
columns: [
{
field: "id",
header: "ID"
},
{
field: "name",
header: "Name" , /* this comma was the problem*/
},
...
Another variation of this bug: I had a function named 'continue' and since it's a reserved word it threw this error. I had to rename my function 'continueClick'
Maybe you've got an object having a method 'constructor' and try to invoke that one.
You may hit this problem while using Knockout JS. If you try setting class attribute like the example below it will fail:
<span data-bind="attr: { class: something() }"></span>
Escape the class string like this:
<span data-bind="attr: { 'class': something() }"></span>
My 2 cents.
I too had come across this issue. I found below two solutions.
1). Same as mentioned by others above, remove extra comma from JSON object.
2). Also, My JSP/HTML was having . Because of this it was triggering browser's old mode which was giving JS error for extra comma. When used it triggers browser's HTML5 mode(If supported) and it works fine even with Extra Comma just like any other browsers FF, Chrome etc.
Here is a easy technique to debug the problem:
echo out the script/code to the console.
Copy the code from the console into your IDE.
Most IDE's perform error checking on the code and highlight errors.
You should be able to see the error almost immediately in your JavaScript/HTML editor.
Had the same issue with a different configuration. This was in an angular factory definition, but I assume it could happen elsewhere as well:
angular.module("myModule").factory("myFactory", function(){
return
{
myMethod : function() // <--- error showing up here
{
// method definition
}
}
});
Fix is very exotic:
angular.module("myModule").factory("myFactory", function(){
return { // <--- notice the absence of the return line
myMethod : function()
{
// method definition
}
}
});
This can also happen in Typescript if you call a function in middle of nowhere inside a class. For example
class Dojo implements Sensei {
console.log('Hi'); // ERROR Identifier expected.
constructor(){}
}
Function calls, like console.log() must be inside functions. Not in the area where you should be declaring class fields.
Typescript for Windows issue
This works in IE, chrome, FF
export const OTP_CLOSE = { 'outcomeCode': 'OTP_CLOSE' };
This works in chrome, FF, Does not work in IE 11
export const OTP_CLOSE = { outcomeCode: 'OTP_CLOSE' };
I guess it somehow related to Windows reserved words

Categories

Resources