Archive for the ‘Javascript / JQuery’ Category

Only First External Javascript File Loads

March 14, 2011

Spent this morning chasing my tail on this one.

We use SexyLightBox as our preferred overlay in all our Web Apps. I was instructed to go to the code vault, disinter a never released app., hose it off, put a new pair of trousers on it and otherwise make it presentable for release, which meant incorporating SexyLightBox v2.2 into it. SexyLightBox 2.2 which is a JQuery PlugIn has a dependency on another Plugin called ‘Easing’..

The sick thing was, I could only get one of these Plugins to load into the browser at any one time. If I put jquery.easing.1.3.js first in the head tag, then it would load, but not sexylightbox.v2.2.jquery.js and if I put sexylightbox first then jquery.easing would not load.

The solution, so simple it makes my teeth ache, was that I had closed my script tags using the shorthand notion , simply using / instead of longhand using /script as beautifully described here, at the Brain Of Dave.

That’s all there is to it. All homage to the Brain Of Dave.

HTTPS Mixed Content Warning: Mootools 1.2 and SexyLightBox

January 17, 2011

Though my Victorian sensibilities make it awkward for me to publicly discuss something called SexyLightBox, I will endure the embarassment for you, my semi-devoted readership.

In TEST we got a HTTP Mixed Content Warning on one of our pages. This is the well-known pop-up that says:

“This page contains both secure and nonsecure items. Do you want to display the non secure items”

.

Since this was a Journey Of Pain I undertook last year, I have healed/suppressed the horrible memories somewhat (along with the ones where I have been abducted by aliens) but the email trail from my outbox allows us to sketchily reconstruct the events.

So I was visited by a vicious UAT tester who, for the purposes of this JOP, was dressed as Lord Monster Raving Loony and carrying a wheelbarrow full of freshly slain ferrets. “The page contains contains both secure and nonsecure items.”, it salivated with disarming charm, “Care For A Ferrett ??”.

“Certainly”, I said lighting one up. “Isn’t that simply due to stochastic fluctuation in maximum latewood density, otherwise known as The Divergence Problem and hence not my fault ?”.

LMRL narrowed twenty-seven of its available fourty-six grotesque eyeballs, forcing them into a reptilian version of the Mexican Wave. “UAT FAIL” it hissed, drew heavily on the ferrett, incinerating it to its toenails and prompty vanished in a cloud of sulphur.

Awfully alone, I started a forensic examination of THINGS DOWNLOADED BY OUR PROBLEM PAGE i.e. images and javascript files. I did indeed find a few images accessed by http instead of https and found the problem went away if I did this AND ALSO commented out mootools 1.2 javascript file. Somewhere in the wild, the ZenPhoto support blog to be exact, I found an article which did indeed appear to nail the uncompressed version of Mootools as a source of Mixed Content Warnings.

Since I could not find an uncompressed version of Mootools 1.2, I downloaded v1.2.5 uncompressed, whacked it in and acheived temporary relief, except that now (blush) AttractiveLightBox.js issued js errors. Curses that pernicious little flirt, let me be direct, SexyLightBox has a dependence on Mootools 1.2.

So I investigated further and found that NaughtyLightBox ignored the document protocol for its image download. Here she is in all her wanton shame:

if(Browser.Engine.trident4)
this.strBG = this.options.imagesdir+’/’+this.options.color+’/’+this.options.backgroundIE;
else
this.strBG = this.options.imagesdir+’/’+this.options.color+’/’+this.options.background;

The Fix

I fixed this by adding a dynamic call for the page protocol to the image path like so:

if(Browser.Engine.trident4)
this.strBG = document.location.protocol + this.options.imagesdir+’/’+this.options.color+’/’+this.options.backgroundIE;
else
this.strBG = document.location.protocol + this.options.imagesdir+’/’+this.options.color+’/’+this.options.background;

Mootools.js was not the issue, though commenting out caused the mixed-content warning to go away because there is a dependence on Mootools from censoredlightbox.

Moral Of The Story
Beware of javascript files that ignore document protocol for image download.

Now if you’ll excuse me I must go cover some table legs with a very long tablecloth.

WebForms Validation Summary Use StartUpScript to Generate Error Message Box Without Using Client-Side Validation

May 4, 2010

Scenario

I wanted to use ValidationSummary.ShowMessageBox to show a popup containing the error message from all failed validations but I had some CustomValidator controls and didn’t want to write complex client-side validation function for each one of them.

I needed a way to get the ErrorMessages from each CustomValidator and all my other Validators into a MessageBox without writing any custom client-side validation routines

Solution

The solution is to collect all the error messages from the Validators into a string and use ClientScript.RegisterStartUpScript to show the errors. This solution comes via a semi-genius post from the well-known Missourian Programming legend bdukes. All I have done is translate it into VB.NET. Here’s the C# original from Stack Overflow thread Elegant way to make CustomValidator work with ValidationSummary Messagebox

”’ Registers a javascript to display error messages from validation as the Page loads from a postback.
Private Sub RegisterServerValidationMessageScript()
If (Page.IsPostBack) Then
Page.Validate()
If (Not Page.IsValid) Then
‘errormessage holds the script
Dim errorMessage As StringBuilder = _
New StringBuilder(“alert(‘Validation Error. \r\n\r\n”)
Dim i As Integer
‘ Add error message from all failed validators
For i = 0 To Page.Validators.Count – 1
Dim validator As IValidator = Page.Validators(i)
If (Not validator.IsValid) Then
If Not errorMessage.ToString().Contains(validator.ErrorMessage) Then
errorMessage.Append(“- ” + validator.ErrorMessage)
If (i < Page.Validators.Count – 1) Then
errorMessage.Append("\r\n")
End If
End If
End If
Next

errorMessage.Append("');”)
If Not Page.ClientScript.IsStartupScriptRegistered(“validationAlert”) Then
Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), _
“validationAlert”, errorMessage.ToString(), False)
End If
End If
End If
End Sub

I just call the above function from Page_PreRender Event Handler.

Almost No Known Side Effects
The side-effect to the above code is that it is called on every Postback, so you will get the alert popup appearing on every Postback while you have validation errors. But what I like about it is that any time I add a new Validator, its error message is automagically added to the alert popup. So that’s less maintenance for me.

Hope that rings your bells.

Javascript Error: Expected ‘)’ Code 0 Line xxx Character xxx IE Only

April 14, 2010

Are You Receiving Me ?

Our corporate website is rendered in about 8 different languages across maybe 30 different domains (thus 30 websites), so our content is multi-lingual ranging from Thai to Arabic to English. A DropDownBox on the HomePage for each website gives the user the option to see the page in any language available to that domain.

Our Sources Of Javascript
The content itself is stored in a massive DataSet keyed to Page/Section/SubSection/Language/Domain. The Pages are rendered dynamically with each SubSection (can be as small as a few HTML-styled words) doing a look up to the DataSet from Markup in order to retrieve its Language/Domain specific content. The content can include any HTML including inline Javascript

Here’s an example from our Markup (i.e.aspx Page)
div id="OtherServiceBanner"
h4 %=WebContentDictionary.OtherServiceBannerTitle% /h4

Apart from inline Javascript we have the usual external js files.

Error Time

So our Web Designers report a JS error occurring on our French Language websites only. The error only occurs in IE.

I excluded the external JS files but the error still occurred, so then, using faithful old Divide and Conquer I progressively commented out all the calls to our Content DataSet until the error disappeared.

It didn’t take too long. The error was in some inline Javascript inserted by our Web Content Management Team whose understanding of HTML and Javascript is not immense.

Here’s the bad Javascript:
a id="ColContent" onclick="return myJSFunction('Visite virtuelle d’un bureau équipé',this.href);"

You will notice that the onclick attribute includes an embedded single quote character in d’un, so IE parsed this as return myJSFunction(‘Visite virtuelle d’ and complained about the ‘missing’ right parenthesis “)”

To correct the issue, the onclick attribute was edited like so :
onclick=”return myJSFunction(‘Visite virtuelle d&aposun bureau équipé’,this.href);”>

That &apos is the way you use an embedded apostophe (single-quote) in Javascript

Bottom line: when you get Expected ‘)’ in your Javascript error, look for improperly terminated string literals and make sure you account for all your sources of Javascript. Then use Divide and Conquer to find the culprit. You’ll probably find you need to use &apos., if not you’ll have to make other plans for Nigel.

External Javascript Source File Syntax Error Code 0 Line 1 Char 1

March 2, 2010

Our maniacally thorough Web Designers found a bug on one of our Web Pages related to a Javascript file. In IE with ‘Show All Errors’ checked in Internet Options it reported blah.js syntax error code 0 line 1 char 1.

Looking into the error I determined that it only occurred on our PROD Web Server, which meant that there was no real problem with the Javascript file. Just to see if it was a cross-browser issue I loaded the offending page in Firefox and was immediately rewarded with a whole truckload of additional information via Tools -> Error Console

Lesson #1 – Debug your Web Page in Firefox. You get much better and much more debug information out of it.

The Firefox Error Console told me that the offending URL was http://www.mypage.com/scripts/blah.js and that the offending line of source code was a DOCTYPE definition, like so: !DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”

But the rest of the source file was not the blah.js file, but our Custom 404 (File Not Found) Page from the Web Server. So, looks like blah.js could not be found.

Examining the aspx page, blah.js was being loaded as an external javascript file:
script src=”/script/blah.js” type=”text/javascript”.

Now, I don’t have access to the live Web Server, but the Engies confirmed for me that there was no folder named ‘script’ in the IIS Directory for http://www.mypage.com, so naturally src=”/script/blah.js” did not exist. I asked them to edit the external script reference for blah.js to a Hotlink I knew was valid, like so
script src=”http://www.myscriptlibrary.com/script/blah.js&#8221; type=”text/javascript”.

Tomorrow, after they do it, I’ll tell you if that fixes the problem. I’ll bet you one slightly damaged Ferrett that it works.

This Condition Is Caused By…

The path to the external blah.js in the src attribute of the script tag on the aspx page was non-existent, giving a bad URL. The HTTP Request that served the script returned 404 for http://www.mypage.com/scripts/blah.js giving back our Custom 404 Page. The first line of that page is DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”. That line is not valid javascript hence the syntax error reported by both IE and Firefox.

This Stack Overflow thread, Doctype Error With Google Maps put it all together for me, many thanks to Stack Overflow User #176492 Mike Williams You are much more than a number to me.

Update 3-Mar-2010: Firebug Rocks

I’m a little closer to solving the whole puzzle now.

Using the amazingly useful Firebug I was able to inspect the HTTP Result Codes in its Net Panel. This showed me that /scripts/blah.js got a 404 on our DEV server but a 200 (OK) on our PROD Server. That 200 is not a real 200 of course, but a Soft 404.

Checking Web.Config I found that customErrors is set to On and that it returns our custom Page “custom404.aspx” for a 404 error. The first line of that page is !DOCTYPE etc. Below is a sample customErrors entry so you know what I mean. More info from Milan Negovin here at ASP.NET Resources

customErrors mode="On" defaultRedirect="~/errors/GeneralError.aspx"
error statusCode="404" redirect="~/errors/custom404.aspx" /
/customErrors

Didn’t check DEV Web.Config yet. I’ll bet customErrors are off or 404.aspx does not exist on that server. Double or nothinng on the Ferretts ?

And just for fun here’s Google’s list of best 404 pages.

JQuery Toggle Visibility Of A Div

November 26, 2008

“The longest journey begins with but a single step” – Probably Not Confucius

This was my first ever JQuery script and, though it be just one line long, I still learned something from it.

script
function setProgressBarVisible()
{
$('[id$=progressBar]').css('visibility', 'visible');
}
/script


This is the div that I wanted to hide/unhide:

div id="progressBar" style="position: fixed; left: 0; top: 0; background: orange;
visibility:hidden; padding: 10px; font-size: small;"
Update In Progress...
/div


Here’s the Link Button that calls the JQuery:

asp:LinkButton ID="reIssueLinkButton" runat="server"
Text='Reissue' OnClientClick="setProgressBarVisible();"
OnClick="reissueLinkButton_Click" /

All that code above works. If you copy and paste it into a JQuery-enabled project, an Orange rectangle will appear in the top-left corner of the browser when you click reissueLinkButton and automatically go away when the page reloads after the postback.

What I learnt along the way was that you have to use visibility=”hidden” in the Style attribute and not Visible=false in the Visible attribute.

Visible=false will not be toggled by the JQuery script because Visible can only be set if you make the div an ASP.NET Server control i.e. runat=”server”. If you do that then the ID property of the div will not be ‘progressbar’ but an ASP variable based on its container e.g ctl00_progressbar, so the setProgressBarVisible function cannot work.

So there you go. A single step. FWIW.

Here’s the page I Googled to get started.

For Advanced Students
The immortal DDK has a great post on Using jQuery to toggle visibility of an ASP.NET textbox based on an ASP.NET DropDownList Control

TabContainer LoadClientState Failed

October 24, 2008

We have a set of small Javascript functions that retain the ActiveIndex of an ASP Ajax Toolkit TabContainer control and restores it on postback. Sometimes, perhaps due to increased sunspot activity, our TabContainer ClientState disappears. Resulting in the intruiging and quite humorous error “When casting from a number, the value must be a number less than infinity.”

To this day I have no idea what causes TabContainer to lose its state, but courtesy of a fellow traveller in pain, I can present a workaround.

Meet The Javascripts

Here’s our happy little Javascript family from the picturesque village of MarkUp

In Head


function saveCurrentTabIndex()
{
var tabcontainer = $get('').control;
var tabIndex = $get('');
if (tabcontainer != null)
{
tabIndex.value = tabcontainer.get_activeTabIndex();
}
}

function restoreCurrentTabIndex()
{
var tabIndex = $get('tabIndexHidden');
if (tabIndex.value > -1)
{
var tabcontainer = $find( '');
var index = tabcontainer.get_activeTabIndex();
if (index != tabIndex.value)
{
tabcontainer.set_activeTabIndex(tabIndex.value);
}
}
}

In Body
input type=”hidden” id=”tabIndexHidden” runat=”server”

Last thing in markup:


function pageLoad(sender,e)
{
restoreCurrentTabIndex();
}

Family Dysfunction

So, like I said, sometimes TabContainer ClientState is null causing the bizarre ‘number must be less than infinity’ error message, I assume because null is not less than infinity. To work around it use the Javascript parseInt function to make sure TabContainer has an ActiveTabIndex it can grok.

Resolving Our Little Differences

In saveCurrentTabIndex:
tabcontainer.set_activeTabIndex(parseInt(tabIndex.value));

Now the ActiveTabIndex will be less than Infinity to the relief of all concerned with the possible exception of Buzz Lightyear.

Our Family Counsellor can be located here.. Thanks djs25uk 🙂