Re: [jQuery] Same-site Restrictions on Ajax: Does $.getScript help?
I want to make a remote request to a different server than the current page is hosted on, in order to get JSON data (padded with a callback). This is typically handled by inserting script elements on the current page with the src as the remote URL, (Right?), but I couldn't find an easy way to do this on jQuery. I looked at $.getScript; but it's more a way to use XmlHTTPConnect(), and eval the results as a script. Does anyone have any ideas as to how one may go about this? The code to do this is really simple. In fact, the very first jQuery plugin was this one that I wrote a year ago: http://mg.to/2006/01/25/json-for-jquery Be sure to read the comments for some IE memory issues and other notes. Also, the code uses (new Date).getTime() to generate a unique callback function name. This was a really bad idea! Besides not always being unique (if you make two JSON calls in quick succession), it wreaks havoc with caching, since each JSON call will have a different URL. The code I'm currently using takes a callback function name as an argument to the $.json() call. A server-side proxy like the one Jake posted is also a great way to do this, if that approach works for you. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] json deserialization
This works for me: $.ajax({ url: 'email.pl', type: post, data: { rm: 'deleteLetter', ID: myForm.letterSelect.value }, dataType: 'json', success: function( ret ) { alert( ret.a ); } }); I believe the order in which you pass the params to $.ajax matters. There's only one argument being passed to $.ajax, a single object literal. To illustrate, you could write the code like this: var args = { url: 'email.pl', type: post, data: { rm: 'deleteLetter', ID: myForm.letterSelect.value }, dataType: 'json', success: function( ret ) { alert( ret.a ); } }; $.ajax( args ); The order of properties in an object literal doesn't matter, except possibly in a couple of pathological cases [1] [2] that don't apply here. -Mike [1] If a property name is used twice in the same object literal - which one wins? [2] If the receiving code does for( name in argobject ) and assumes a particular order of enumeration (which is undefined behavior anyway). ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] window.undefined = undefinedundefined?
I was poking around the DOM looking for incorrectly scoped variables and I found the following node: window.undefined = undefinedundefined What is this for? The window object has a property named undefined whose value is the undefined value. IOW, when you run code like this: if( foo === undefined ) alert( 'foo is undefined' ); What you are really doing is the same as: if( foo === window.undefined ) alert( 'foo is undefined' ); I don't know what tool you are using to view the DOM or why it says that window.undefined has a value of undefinedundefined. That sounds like a bug in the DOM viewer, unless this code has been executed, which seems unlikely: window.undefined = undefinedundefined; -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Advantages of adding functions to jQuery
I'm having trouble seeing the advantage of adding static functions to jQuery as in: jQuery.log = { error : function() { ... }, warning : function() { ... }, debug : function() { ... }, }; as opposed to: function log() { ... } log.prototype.error = function() { ... } log.prototype.warning = function() { ... } log.prototype.debug = function() { ... } It seems the former opens up the door to unintended closures. What are the benefits of doing it this way as opposed to the traditional non-jQuery way? I don't see any closures in that code. The jQuery.log = { ... } is not a function and doesn't introduce a closure. This object literal is just a handy way of creating some static functions. IOW, these are identical: jQuery.log = { error : function() { ... }, warning : function() { ... }, debug : function() { ... }, }; jQuery.log = {}; jQuery.log.error = function() { ... }; jQuery.log.warning = function() { ... }; jQuery.log.debug = function() { ... }; Your code with the log.prototype stuff is something different entirely. You're creating a log() constructor and giving it some methods. (BTW, by convention, you would usually call it Log() instead of log() because it's used as a constructor.) So you would need to do this to use it: var log = new Log; log.debug( ... ); The use of static functions avoids the need to construct an object. You can merely use: jQuery.log.debug( ... ); Not sure if I answered your question, but those are a few thoughts on it anyway... :-) -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Dynamically change Document title
Is there a way to change the title of a document after an ajax Call. I'm using an ajax history system and I would like to view specific document title in the back button list. I've try this but doesn't seem to work : $(title).html(Dynamic Title); I can see the change in Bugzilla but the browser didn't refresh it. Try: document.title = 'Dynamic title'; -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] compare between display and visibility when hide anelement?
Nothing to do with SEO. The display and visibility properties do two different things: http://www.w3.org/TR/CSS21/visuren.html#display-prop http://www.w3.org/TR/CSS21/visufx.html#visibility -Mike _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Microtoby Sent: Tuesday, March 06, 2007 9:59 AM To: 'jQuery Discussion.' Subject: [jQuery] compare between display and visibility when hide anelement? Hello, Guys, I'm using jQuery for a while, and like jQuery much more, But I have a question begin start using this library, YUI and some other library using visibility to hide an element, jQuery using the display css property. Any one can tell me what the difference between display and visibility is? For example, difference in SEO? Best wishes, Microtoby 2007-3-7 ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] .next() bug?
Now, my mark-up is wrong. I should have wrapped the nested ul in it's own li, but I missed it. Testing looked good in FF 2, .next() was returning the nested ul, and I didn't even notice the problem. In IE6/7 however, .next() returned the next li, and not the ul which was in fact next the next element. Wrapping the ul in it's own li/li as it should be solved the discrepancy, but the fact that there is a discrepancy in how the two browsers interpret .next() makes me think perhaps there's a bug in there. My understanding of sibling was the next element in line on the same level, but in the case of the mark-up above IE seems to interpret the next sibling as the next element in line on the same level and of the same type. Am I wrong in my understanding of sibling? When you have invalid markup, browsers take their best guess as to what you meant, and different browsers may guess differently. If you're interested in knowing exactly what happened here, use a DOM inspector in each browser and compare the DOM trees. For Firefox, that would be Firebug, and for IE, Microsoft's Developer Toolbar: http://www.microsoft.com/downloads/details.aspx?FamilyID=e59c3964-672d-4511- bb3e-2d5e1db91038 My guess is that there are differences in the DOM that explain the different results. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] KICK-BUTT javascript based Zoom feature
This is untested code, but it's one way you could do it with jQuery: $(function() { location = $('[EMAIL PROTECTED]')attr('href').replace( /_spam$/, '' ); }); _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Christopher Jordan Sent: Saturday, February 24, 2007 10:32 AM To: jQuery Discussion. Subject: Re: [jQuery] KICK-BUTT javascript based Zoom feature that url is busted. Rick Faircloth wrote: Well. anyone know how to accomplish this in jQuery? http://tinyurl.com/yubt54_spam Rick From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Matt Stith Sent: Monday, February 05, 2007 9:53 AM To: jQuery Discussion. Subject: Re: [jQuery] KICK-BUTT javascript based Zoom feature Really all that is is a image of a grid that stays aligned with the mouse, and a higher resolution image that scrolls depending on the mouse position. It doesnt even use jQuery. ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] KICK-BUTT javascript based Zoom feature
The actual code for the close-up effect would be different from that, but the code I posted may help point toward the solution. _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Rick Faircloth Sent: Saturday, February 24, 2007 11:20 AM To: 'jQuery Discussion.' Subject: Re: [jQuery] KICK-BUTT javascript based Zoom feature Wow. that looks simple. I guess the jQuery core has everything else needed to produce the close-up effect? Rick From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Michael Geary Sent: Saturday, February 24, 2007 2:07 PM To: 'jQuery Discussion.' Subject: Re: [jQuery] KICK-BUTT javascript based Zoom feature This is untested code, but it's one way you could do it with jQuery: $(function() { location = $('[EMAIL PROTECTED]')attr('href').replace( /_spam$/, '' ); }); _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Christopher Jordan Sent: Saturday, February 24, 2007 10:32 AM To: jQuery Discussion. Subject: Re: [jQuery] KICK-BUTT javascript based Zoom feature that url is busted. Rick Faircloth wrote: Well. anyone know how to accomplish this in jQuery? http://tinyurl.com/yubt54_spam Rick From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Matt Stith Sent: Monday, February 05, 2007 9:53 AM To: jQuery Discussion. Subject: Re: [jQuery] KICK-BUTT javascript based Zoom feature Really all that is is a image of a grid that stays aligned with the mouse, and a higher resolution image that scrolls depending on the mouse position. It doesnt even use jQuery. ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] KICK-BUTT javascript based Zoom feature
...and if I seem too much like a smart aleck today, my apologies! No offense intended. I was just having some fun with the juxtaposition of that URL is busted and anyone know how to accomplish this in jQuery... :-) _ From: Michael Geary The actual code for the close-up effect would be different from that, but the code I posted may help point toward the solution. ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Id of a textarea element
You may use a period in an id still being valid XHTML, but in this case you cannot use the id as a (CSS) selector, because the period is a class selector. I'm not convinced it's not a bug in jQuery because it doesn't make sense to specify a class on an Id. I'm not going to make a fuss about it unless you also think it needs to be made a fuss about. There is a situation where it can be useful: If you want to select the element with a certain ID, only if it also has a certain class. Assuming that the ID 'foo' exists, then $('#foo.bar') returns a jQuery object with a single element if the element has the class 'bar', but returns an *empty* jQuery object if the element does not have that class. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] $.show() improvement
What if I specify a div as display:inline in my css? Hiding then showing this div using the above script would change it's display to block. Good point! I was about to suggest making a list of the block level elements to avoid having to create DOM elements to test, but either approach would fall down here. Would be good if it remembered the original setting. And if the element started out hidden? :-) The real problem here is that there is *no such thing* as showing an HTML element. All you can do is set it to block or inline. This suggests that show() is a mistake: you need separate showBlock() and showInline() methods. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] $.show() improvement
It does that by having hide() remember the old element block vs. inline type in this.oldblock, and then show() uses that to decide what to do: hidden.each(function(){ this.style.display = this.oldblock ? this.oldblock : ; if ( jQuery.css(this,display) == none ) this.style.display = block; }); That is an odd little bit of code, but it looks like that is what it's doing. I think this would still fall apart in the case where you have an element that is initially hidden (you never call hide() on it) and then show it. It won't have this.oldblock to look at in that case. _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Karl Swedberg Sent: Wednesday, February 14, 2007 3:55 PM To: jQuery Discussion. Subject: Re: [jQuery] $.show() improvement I just tested using .hide() and .show() in Firebug with a elements, and .show() only makes them elem.style.display=block when there is a speed designated. Plain .show() returns them to inline. On Feb 14, 2007, at 5:37 PM, Michael Geary wrote: The real problem here is that there is *no such thing* as showing an HTML element. All you can do is set it to block or inline. This suggests that show() is a mistake: you need separate showBlock() and showInline() methods. I wonder, would it be possible to pass in another argument instead? Something like .show('slow', 'inline') ? Or would that require too much code rewriting? Would have to consider the callback function too. --Karl _ Karl Swedberg www.englishrules.com www.learningjquery.com ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Issues with non FF browsers
I'm trying to get some simple things to work using jquery, and everything currently works the way I'd like it to in Firefox. However, in Opera, Safari, and Internet Explorer, nothing works right -- and I haven't been able to figure out where the hang up is. My entire jquery code can be found here: http://www.moiph.com/javascript/index.js but a snippet is below... There's no way to tell what's wrong from the JavaScript code alone. Do you have an HTML page to try it in? -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Issues with non FF browsers
$.get(parser.php, { type: type, user: user, }, trailing commas only work in firefox! user: user, has a trailing comma! Great catch, Jake. Here's a tip - use ActiveState Komodo for your JavaScript editing, and get syntax checking as you edit. I loaded the code into Komodo, and it flagged the user: user, line with a green squiggly underline and this message: Strict warning: trailing comma is not legal in ECMA-262 object initializers And had I tried this before my first reply, I wouldn't have said it was impossible to tell what was wrong from the JavaScript code alone... :-) As of version 4.0, Komodo Edit (no debugger, but all the editor features) is free - and it runs on Mac, Windows, and Linux. By far my favorite editor for JavaScript, Ruby, Python, and PHP. http://www.activestate.com/products/komodo_edit/ http://www.activestate.com/products/komodo_ide/ -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] how to simplify this
There are several ways you could refactor that code. Here's one approach: $('#normal, #standard, #profi').click( function() { var idnums = { normal:1, standard:2, profi:3 }; $('#bereit').ScrollTo( 800 ); for( var id in idnums ) { var n = idnums[id]; var method = 'removeClass', checked = ''; if( id == this.id ) method = 'addClass', checked = 'checked'; $( '#' + id + ' dd, #label_radiobutton_' + n )[method]( 'ausgewaehlt' ); $( '#radiobutton_' + n ).attr( 'checked', checked ); } }); -Mike _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Dominik Hahn Sent: Monday, February 12, 2007 9:14 AM To: discuss@jquery.com Subject: [jQuery] how to simplify this Hello, I am looking for a way to simplify this chunk of code: $('li#normal').click(function() { $('#bereit').ScrollTo(800); $('li#normal dd').toggleClass('ausgewaehlt'); $('li#standard dd').removeClass('ausgewaehlt'); $('li#profi dd').removeClass('ausgewaehlt'); $('label#label_radiobutton_1').toggleClass('ausgewaehlt'); $('label#label_radiobutton_2').removeClass('ausgewaehlt'); $('label#label_radiobutton_3').removeClass('ausgewaehlt'); $('input#radiobutton_1').attr('checked','checked'); $('input#radiobutton_2').attr('checked',''); $('input#radiobutton_3').attr('checked',''); }); $('li#standard').click(function() { $('#bereit').ScrollTo(800); $('li#normal dd').removeClass('ausgewaehlt'); $('li#standard dd').toggleClass('ausgewaehlt'); $('li#profi dd').removeClass('ausgewaehlt'); $('label#label_radiobutton_1').removeClass('ausgewaehlt'); $('label#label_radiobutton_2').toggleClass('ausgewaehlt'); $('label#label_radiobutton_3').removeClass('ausgewaehlt'); $('input#radiobutton_1').attr('checked',''); $('input#radiobutton_2').attr('checked','checked'); $('input#radiobutton_3').attr('checked',''); }); $('li#profi').click(function() { $('#bereit').ScrollTo(800); $('li#normal dd').removeClass('ausgewaehlt'); $('li#standard dd').removeClass('ausgewaehlt'); $('li#profi dd').toggleClass('ausgewaehlt'); $('label#label_radiobutton_1').removeClass('ausgewaehlt'); $('label#label_radiobutton_2').removeClass('ausgewaehlt'); $('label#label_radiobutton_3').toggleClass('ausgewaehlt'); $('input#radiobutton_1').attr('checked',''); $('input#radiobutton_2').attr('checked',''); $('input#radiobutton_3').attr('checked','checked'); }); It controls a list, when you click on one of the three items, it scrolls down to a online form (first line), the item is highlighted (first three lines), one of three radioboxes is checked (line 6-8) and the label for the checked radiobox is also highlighted (last three lines). Can you help me? Thanks, Dominik ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] iframe and designmode
As you can see from your first (presumably working?) example, .contentWindow is a property of an HTML element. Therefore, the real question is, How do I get the HTML Element? If you are inside an $('foo').each() callback function, then this is the HTML element. So, you could use: this.contentWindow.document.designMode = on; What messed things up was doing $(this). $(this) returns a new jQuery object - but all you needed was this itself. If there is only one IFRAME in question (obviously true because you are accessing it by ID), then you can use this bit of information: document.getElementById('foo') can be directly translated to $('#foo')[0]. This means you can skip the each loop and use: $(#iframe_name)[0].contentWindow.document.designMode = on Obviously in this particular case there is little reason to prefer the jQuery code over the straight DOM code. Finally, a debugging tip. Instead of poking around trying things to see if you get lucky, use a debugger to look at the values returned by various functions. You would see, for example, that $(this) was not a DOM element and did not have a .contentWindow property. Why did some things you tried just not work and others triggered an error? Well, this code would run without triggering an error, but it wouldn't do anything useful: $(this).designMode = on; That merely added a designMode property to the jQuery object. A perfectly legal operation, but not useful. $(this).contentWindow.document.designMode = on; That causes an error, which you would discover by breaking it down step by step: console.debug( $(this) ); console.debug( $(this).contentWindow ); console.debug( $(this).contentWindow.document ); The first console.debug call would show a jQuery object. The second would show undefined, because a jQuery object does not contain a .contentWindow property. The third would throw an exception, because $(this).contentWindow is undefined, and undefined of course does not have a .document property. -Mike I need to use the following command to activate designmode in an iFrame (designmode is when you can use an iFrame like it was a text editor, think Word or when you compose an email in Gmail): document.getElementById(iframe_name).contentWindow.document.designMode = on I've tried to jQuerify the sentence in a variety of manners but it never works. Sometime the command wont work and other times they trigger an error. So far I've tried with (I use the reserved word each cause I'm working inside a plugin): $(this).contentWindow.document.designMode = on; $(this).document.designMode = on; $(this).designMode = on; and $(this).attr(contentWindow.document.designMode, on) $(this).attr(document.designMode, on) $(this).attr(designMode, on) nothing worked. I wouldn't mind sticking to pure javascript for once, but the thing is that this doesn't work either, wich is driving me crazy: document.getElementById($(this).attr(id)).contentWindow.document.designMod e = on Has anyone here used designMode for an iFrame with good results? Why doesn't jQuery support it? Thanks. ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Finding parent iframe?
I have a quandary. I open an iframe with some arbitrary content in it. I want to be able to click on something within the iframe to cause the iframe (and the div tag that contains the iframe) to go away. I am having trouble getting to the iframe. I know it's possible as I've seen it elsewhere, I just can't find the proper path to it. I basically have this structure: html body div iframe html body any tag /body /html /iframe /div /body /html It's not exactly accurate but it gives a good idea what I'm looking to do I've tried: // This should as far as I can get to the div tag which is where I want to be $('#any tag').parents('html').parent().parent(); But when I alert the length of this, I get 0. I've also tried a pure DOM way any_tag.ownerDocument.parent.parent.parent but again, I get nothing. You're mixing up two different kinds of parents - parent *node/element* and parent *window*. Assuming that anyTag is a valid reference to your any tag, then this code should work (it's based on tested code that I use): var frameDoc = anyTag.ownerDocument; var frameWindow = frameDoc.parentWindow || frameDoc.defaultView; var frameElement = frameWindow.frameElement; var outerDiv = frameElement.parentNode; -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Finding parent iframe?
I was able to take what you sent me and simplify it down to this: var frameWindow = document.parentWindow || document.defaultView; var outerDiv = $(frameWindow.frameElement.parentNode); cls = $('div.tb_close', outerDiv).get(0); Because I actually want to operate on a child of the outer div (which I didn't specify as it wasn't relevant). And I figured out that I could use document because when I am executing the javascript, I don't need the link, merely the link's document, and document is what I need. Works in both FF and IE as well. It sounds like your code is actually running inside the IFRAME, is that correct? It sounded like you only had a reference to an element inside the iframe, thus the ownerDocument/parentWindow/defaultView stuff to find the frame window. But if your code is running in the IFRAME, then window is already the frame window. So you can simplify even further: var outerDiv = $(frameElement.parentNode); cls = $('div.tb_close', outerDiv).get(0); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] jQuery and Object Notation... confused with this
Recently I've been trying to use ON with jQuery. I met with obstacle. I couldn't use this keyword in certain cases to get my main object reference... var myObject = { layout: { 'align': '' }, start: function() { $('form').bind('submit', this.buildLayout); //WORKS }, buildLayout: function() { this.layout.align = $('#elem').attr('value'); //DOESN'T WORK } } function initialize() { myObject.start(); } $().ready(initialize); Nate's solution is a good one, but personally I would probably do this: $(function() { var layout = { 'align': '' }; $('form').bind( 'submit', function() { layout.align = $('#elem').attr( 'value' ); }); }); Of course, it's hard to tell from a stripped-down example whether that approach would fit with the rest of the code in your application, but it's always worth looking at a couple of different ways to tackle a problem. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] rewriting the browser address (without refresh)?
If you change only the hash, it won't reload the page - but it won't create a unique URL for search engines. If you change anything else in the URL, it will reload the page. Changing the hash does get you a URL get people can copy and bookmark. But Google won't see the hash. It really is a case of not being able to have your cake and eat it too. I'm wondering if there is a way to rewrite the url in the browser bar without refreshing the page. I'm using Jquery/ajax to do something but unless I can rewrite that url I don't think we can do this. I could use an anchor (#...) but the problem here is that they links need to be accessible to Google. People need to be able to cut, paste, bookmark whatever they are looking at. I'm hoping this is somehow possible...OR...is there some other logical solution that might be considered? ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Animate font weight
I'm trying to get animate() to fade font-weight but it's not working. I've tried the following: $('a').mouseover(function() { $(this).animate({fontWeight: 'bold'}, 'slow'); }); But that doesn't work - I've also tried to put quotes around the fontWeight and tried font-weight. I get the following error: e[prop[p]] is not a function (line 1582) Can anyone tell me if/how animating font-weight is possible? What would it mean? Are you trying to have a font gradually change from normal to bold? Browsers don't generally support a range of font weights. They support normal and bold, and for most fonts that is it. Sorry! -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Custom borders
$.fn.border = function(prefix){ var classNames = [ 'north', 'east', 'south', 'west', 'northeast', 'southeast', 'southwest', 'northwest']; return this.each(function(){ for (var index in classNames){ className = (prefix || '')+ classNames[index]; $(this).wrap(div class=' + className + block'/div) } }) }; Danger warning! Don't use for..in on an array! Use a C-style loop instead. ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] I broke it - Why is it doing this?
When you create a named function is is basically a static object stored in funcname of the scope it was defined in. when you declare a var in a function it is also a static object attached to the function object. As such mydata is a single static object and effectively a single object in the global space of objects. So repeated calls to funcname that set mydata will result in the last calls values be stored into mydata. With the anon function, you are actually creating multiple functions each with its own mydata variable defined within each anon function. The var statement DOES NOT work like it does in C where the variable is created on the stack and is unique to that function call at runtime. Does this sound right? No, not at all. (Sorry!) The var statement DOES work just like a variable declaration in C. A variable declared in a function is not attached to the function object. It is created when the function is *called*, the same as in C, and free for garbage collection when the function returns - unless there is an outstanding reference to it as in the case of a closure. Even when there is a closure, a variable is still specific to a single invocation of the function in which it is declared. Also, it makes no difference if a function is named or anonymous. The scope rules are identical for either kind of function. I'll go look at the original problem, but I just wanted to correct this first. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] External or anonymous function - which is best?
$(document).ready(function(){ function resizeDiv(that){ var x = $(that); if(x.height() 600){ x.css(height,600px); } }; $(#mydiv).each(function(){resizeDiv(this)}); }); My question: is it better to define this function as above and pass this or to define an anonymous function within the .each statement? I read that the above method only has to compile the function once, as opposed to a re-compile each time the (anonymous) function runs. Functions are compiled to bytecode once, not each time they are executed. Maybe someone was talking about the Function constructor which takes a string argument and does compile the function each time you execute the constructor? What is the recommend way of doing this? Well, there's certainly no reason to use *two* functions here. You could write the code either with a single anonymous function or a single named function, as shown in Jörn's two examples, whichever you prefer. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] JQuery in Google Maps Info Windows
I'm not very familiar with InnerFade, but wouldn't you do this inside your marker click handler, right after you call marker.openInfoWindowHtml? That's when you have the list items available. I'm new to jQuery and am trying to figure this out, but was wondering if anyone has had any luck embedding jQuery code inside Google Maps info windows? I have an existing google map that parses coordinates and descriptions for points from an xml file and have tried using Innerfade ( http://medienfreunde.com/lab/innerfade/ http://medienfreunde.com/lab/innerfade/ ) to rotate through a list of images inside the info windows that appear when points on the map are clicked. The points are created when the map is loaded (during page loading) but I am unsure when/how to make the call to innerfade? Right now, I'm still calling the innerfade function inside document.ready(), but I've tried placing that code in various positions inside the load function. Any ideas? Here is a link to my site... http://www.derekandsarah.net/travel/chicago.php http://www.derekandsarah.net/travel/chicago.php ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] OT: CSS Conditional Comments
!-- ... - is an HTML comment, not a CSS comment. So, conditional comments go in your HTML code, not in CSS code. div.SiteHeader{ border: 1px solid #336566; /*AA*/ width: 850px; background-color: #E3F0D6; /*D5F0D5,CDD9E5*/ height: 60px; text-align: left; margin: auto; !--[if IE 6] line-height: 60px; ![endif]-- } ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] OT: CSS Conditional Comments
!-- ... - is an HTML comment, not a CSS comment. So, conditional comments go in your HTML code, not in CSS code. Michael, so that only works with inline styles? You can use them with any HTML code. Inline style tags, link tags, script tags, whatever. Do a View Source on www.zvents.com for an example that uses a link tag to load a .css file for IE only. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] What tools should I use to troubleshoot jquery problems? (John Resig, jquery team, other gurus please share your tricks...)
Is there a way to just return the jquery object (so I could see it in firebug's watch section) then pass it to another jquery function then join them all up when I know everything works? $('#test :textarea').before('Current length:nbsp;span id='+ this.id +'_len'+this.value.length+'/spannbsp;characters').keypress( function() { $('#'+this.id + '_len').css('color', ((this.value.length parseInt(this.id.split()[1]))?'red':'green')).html(this.value.length) }); Yes, breaking up your chains is one of the first things do do when you're having trouble. For example: var $test = $('#test :textarea'); $test.before('Current length:nbsp;span id='+ this.id +'_len'+this.value.length+'/spannbsp;characters'); $test.keypress( function() { var $len = $('#'+this.id + '_len'); $len.css('color', ((this.value.length parseInt(this.id.split()[1]))?'red':'green')); $len.html(this.value.length); }); Now you'll find it easier to debug. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Trivial use
The DOM updates immediately when you add new elements. But updating the DOM does not mean copying event handlers from deleted DOM elements to newly added DOM elements. That appears to be the problem here: You need to assign the click handler again after replacing the DOM element, because the click handler was attached to a DOM element that you are deleting. If the DOM have been modified, the DOM should be refresh (or the part of the modified DOM), it sound logical. How to force jQuery to do it ? let me illustrate : If I update the content of my page using a jQuery method, I can't access the new elements using jQuery. document.getElementById works, document.getElementsByName works, prototype' $() works, firebug list the new DOM elements, but jQuery considers thoses elements does not exists... I can understand that jQuery needs the document to be ready to trigger any event, but the event has already been declared and the DOM is up-to-date so, the DOM as jQuery listed it is supposed to be up to date too, isn't it ? Is there a reload DOM method I can call without having to redeclare each handler I need ? 2007/1/23, Joel Birch [EMAIL PROTECTED]: What I said about the handler being attached more than once really only applied to the example we were working with. Considering you are emptying the content now the previous .test will not exist by the time you load the new one. Also, Jörn's advise about using find() is good practice and will ensure that the handler is attached only to the .test elements it finds within the string you just appended. You should be ok with something like: functiontestHandler() { $(.test).change(function(){ alert(this.options[this.selectedIndex].text); }); } $(document).ready(function(){ testHandler(); $(.trigger.fruits).click(function(){ $(#content).empty(); $(#content).append('select name=fruits class=testoption value=firstapple/optionoption value=secondorange/optionoption value=thirdpeach/option/select') .find(.test).each(testHandler); return false; }); $(.trigger.vegetables).click(function(){ $(#content).empty(); $(#content).append('select name=vegetables class=testoption value=firsttomato/optionoption value=secondpotatoe/optionoption value=thirdcarrot/option/select') .find(.test).each(testHandler); return false; }); }); I'm pretty sure that code can be optimised better than this though. Also, about the parsing of the HTML - jQuery does do this for you so don't worry about that. Good luck Joel. On 24/01/2007, at 12:34 AM, Laurent Goussard wrote: If I well understood Joel and Jörn, I am suppose to declare my event handler each time I switch the #content's content, but this will result to increment the alert() number each time the event is declared... What a pity... I cannot really understand why jQuery does not add the content newly loaded to the existing DOM. I mean jQuery should parse and update the DOM foreach .html method used (in append*, load, etc...), shouldn't it ? I can't imagine I'm the only one who wanted to add jQuery events on html content loaded with jQuery. Am I ? ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] What tools should I use to troubleshoot jqueryproblems? (John Resig, jquery team, other gurus please share your tricks...)
That's a nice trick, Jake - thanks for posting it! Both approaches have their use. Your log plugin is great for console logging, while breaking up the chain is great for interactive debugging because you can set a breakpoint between lines. -Mike Mike, I don't like breaking the chains... I just insert a debug in the middle of the chain... I use this for my debug: jQuery.fn.debug = function(message) { return this.log('debug:' + (message || '') +[).each(function(){jQuery.log(this);}).log(]); } jQuery.fn.log = jQuery.log = function(message) { if (!message) message = 'UNDEFINED' if (typeof message == object) message = jsO(message) if(window.console window.console.log) //safari window.console.log(message) else if(window.console window.console.debug) //firebug window.console.debug(message) else jQuery(body).prepend(message+ br/) return this } ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Proper OOP paradigm / please be friendly
// this is .n much too complicated! Guys, I don't appreciate the profanity. My 10 and 11 year old daughters are learning JavaScript. I don't want them to be subjected to language like that. When you've offended some people already, offending more is probably not the best way to fix it. :-) Still friends, just please keep the language clean, -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Proper OOP paradigm / please be friendly
Guys, I don't appreciate the profanity. My 10 and 11 year old daughters are learning JavaScript. I don't want them to be subjected to language like that. Just to clarify, my daughters don't actually read the jQuery list - yet. Their goal is to make an online computer game for some of their friends to play. Right now they're just learning about variables and loops and a bit of HTML and CSS. Hopefully they will be among the youngest jQuery users soon. :-) -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
[jQuery] Junior Programmers (RE: Proper OOP paradigm / please be friendly)
From: Michael Geary Just to clarify, my daughters don't actually read the jQuery list - yet. Their goal is to make an online computer game for some of their friends to play. Right now they're just learning about variables and loops and a bit of HTML and CSS. Hopefully they will be among the youngest jQuery users soon. From: Mike Alsup Jeez Mike, way to make me feel even older. My eleven year olds haven't a clue what JavaScript is, but they're pretty good at linerider! (http://www.linerider.com/) Mike, not to worry, there are good odds that I'm older than you! Never saw Linerider before, that is really cute. Will have to try it on the tablet PC. From: Christopher Jordan How old are they Mike? I hope someday that I have kids who dig this stuff as much as I do. It'll be neat to see where they could take it. :o) They're 10 and 11. We will see if they actually stick with it; they've only done a little bit so far. What amazed me was that they actually took an interest themselves. So far so good... -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] what's the difference between document.getElementById('id') and $('#id') ?
(If there is a better way to look at the Object, please post here) The very best way to understand what JavaScript code is going and explore objects is to use any JavaScript debugger, such as Firebug or Venkman for Firefox, or the Microsoft Script Editor for IE. If you don't have a JavaScript debugger that you are comfortable with, you're working too hard! :-) -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] what's the difference betweendocument.getElementById('id') and $('#id') ?
Now that it is laid out in front of me it's pretty obvious, but when you come into the thing cold, these things are not obvious. I think it would be a good idea to explicitly state what the object is, and that $ refers to it (I think that's right ... now I mention it I'm not quite sure if $ is an object reference or an operator ... ) - anyhow just a bit of clarification of the basics. It's neither of the above. :-) $ is not an operator. In JavaScript, the $ character can be used in names in the same way as a letter. $ is also not a jQuery object or a reference to one. at all. It is a *function* that returns a jQuery object. A good way to think of the $ function is that it's just like a constructor function (e.g. Date or Array), except you don't use the new operator with it, you just call it. Consider this code: // Give the $ function a more self-explanatory name var createQueryObject = $; // Create a query object for a specified query string var myQueryObject = createQueryObject('#test'); // Call a method of the query object myQueryObject.hide(); That is the same as: $('#test').hide(); Note also that $ and jQuery (used as a name in JavaScript code) are the same thing. So you could also write this code as: jQuery('#test').hide(); Or: var myQueryObject = jQuery('#test'); myQueryObject.hide(); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] 1 Function, Multiple Events?
if have some thing like this that is called by document.ready(): function init_top_level() { $(.top_folder).click(function(i) { // Do a ton of stuff here }); } I not only want to assign the click event to my .top_folder elements, but assign dblclick as well. I know I could always break my Do a ton of stuff here out as a separate function and assign it from 2 separate $(.top_folder).click and $(.top_folder).dblclick. Is there an easier way to do this? Something like: function init_top_level() { $(.top_folder).click AND $(.top_folder).dblclick(function(i) { // Do a ton of stuff here }); } I don't understand what you want to do. Jörn's answer assigns the exact same function to the click and dblclick events. Surely that is not what you want, is it - having click and dblclick do the same thing? Keep in mind especially that every dblclick event is preceded by a click event, so you'd be calling the function twice. So can you explain in a little more detail what you want to do here? -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] List of jQuery-Powered Sites
Forgot to add us to the list... Zvents: http://www.zvents.com/ This is a Rails site and we completely replaced prototype.js with jQuery and our own code. We're using thickbox, a homegrown autocompleter, my DOM plugin, and lots of custom code. This also puts jQuery on our partner sites: The Boston Globe: http://calendar.boston.com/ The Denver Post: http://denverpost.zvents.com/ Contra Costa Times: http://contracostatimes.zvents.com/ San Jose Mercury News: http://mercurynews.zvents.com/ -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] 1 Function, Multiple Events?
Thanks for the assistance. Yes, I was basically trying to assign a click and dblclick to the same function (to prevent users from double-clicking and firing the func twice). Hmm... If you assigned both click and dblclick to the same function, then the function *would* be called twice on each double click. Remember, a journey of two clicks begins with a single click. However, after looking into it a bit more, i think that the $(p).one(click, fun.is a better fit here. Sure thing, if that's what you want to do: run on the first click inside any p tag, and never again. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] How to get element when it's ID contains bank space.
Scripting on top of an invalid HTML document won't make your life easier (obviously). I'd try to replace spaces given by the user to _ in the backend. And then do what with underscores given by the user? Come on, that was just an idea. You can leave underscores the way they are for example. Or you could also just remove the blanks instead. But if you're able to change the backend anyway, it would be better to simply not allow white-space and validate the user input. I like it when visitors put quote marks and angle brackets and stuff in these ID fields. It makes for a much more interactive environment when they can run their own code! -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] IDs of all checked checkboxes
var a[]; $(':checkbox').each(function() { if (this.id) a.push(this.id); }); I get this error: missing ; before statement var a[]; (curse my rudimentary javascript skills!) OK... It says there is a missing ; before the statement var a[];. What is before the var a[];? Ah, forget my question. I wasn't paying attention! Should be var a = [];, of course. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Passing values to a custom function
Do you want getPost to be called during the execution of initialiseForm, or later in response to the 'submit' event? For the latter, use this (added code in red): function initialiseForm(formId) { $(formId).bind('submit', function() { getPost(formId) } ); } -Mike _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Dan Eastwell Sent: Monday, January 08, 2007 4:24 AM To: jQuery Discussion. Subject: [jQuery] Passing values to a custom function Hi again, following up my previous post where I was trying to bind a function to a submit event, I'm now trying to pass values from the function that returns a function to the bound submit event. I've a number of forms on a page, that perform a variety of functions, some similar. I'm trying to create a custom function that posts a checkbox variable, but within the context of the function that returns a function, I can't pass the variables across. If I put an alert(formName); etc, in the postCheckbox function, it confirms the values are being passed across, but alert(document.formName.tagName); , for example, gives 'undefined'. Why does the function not abstract out in this case? Many thanks, Dan. $(document).ready(function(){ initialiseForm(#PollX); initialiseForm(#PollY); initialiseForm(#RateX); }); function initialiseForm(formId) { $(formId).bind('submit', getPost(formId)); } function getPost(formId) { return function() { switch(formId){ case #PollX: postCheckbox(PollX, PollXGroup, div#PollXDiv, PollXresults.php?PollXRadio=) return false; break; case #PollY: //do something else return false; break; case #RateX: // do more things postCheckbox(RateX, RateXGroup, div#RateXDiv, RateXresults.php?RateXRadio=) return false; break; default: return false; } }; } function postCheckbox(formName, radioGroupName, replacementBlock, postURL){ for (var i=0; i document.formName.radioGroupName.length; i++) { if (document.formName.radioGroupName[i].checked){ var radioValue = document.formName.radioGroupName[i].value; } } if(radioValue){ $(replacementBlock).load(postURL + radioValue).fadeIn(slow); } } -- Daniel Eastwell Portfolio and articles: http://www.thoughtballoon.co.uk Blog: http://www.thoughtballoon.co.uk/blog ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] setting an attribute... I *thought* this was how to doit...
$(function(){ $(div.OrderEntryListRow).not(.Selected).each(function(i){ alert(before: + $(this).attr(id)); $(this).attr(id, Row_ + (i+1)); $(this).html($(this).html() + ': ' + (i+1)); alert(after: + $(this).attr(id)); }); }); Any time you see that much repetition in a piece of code, you should think, That might be expensive - let's do it once instead of many times. So the first response would be to call $(this) only once: $(div.OrderEntryListRow).not(.Selected).each(function(i){ var $this = $(this); alert( before: + $this.attr(id) ); $this.attr( id, Row_ + (i+1) ); $this.html( $this.html() + ': ' + (i+1) ); alert( after: + $this.attr(id) ); }); But we can do even better here. There's no reason to use .attr() and .html() at all: $(div.OrderEntryListRow).not(.Selected).each(function(i){ alert( before: + this.id ); this.id = Row_ + (i+1); this.innerHTML += ': ' + (i+1); alert( after: + this.id ); }); That is both faster and much simpler. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] setting an attribute... I *thought* this was how to doit...
Chris, it's like this... ;-) $() returns a jQuery object, which is an array of DOM elements with jQuery methods that apply either to the entire array or to the first element in the array, depending on the method. One of those methods is .each(), which loops through the DOM element array and calls your function on each one, setting this to the individual DOM element. So, inside a $().each( ... ) function, this refers to a specific DOM element. You can call DOM methods on that element and access its attributes and properties using ordinary JavaScript. You can wrap a DOM element with $(element) to get a jQuery object containing that single DOM element. You can then call jQuery methods on that object. In many cases, you can use either one interchangeably. Inside an each() function, these would do the same thing: alert( this.innerHTML ); alert( $(this).html() ); as would these: alert( this.id ); alert( $(this).attr('id') ); Naturally, the first one of each of these pairs is faster and is recommended in most cases. -Mike Mike, thanks so much for the advice! :o) I guess I'm still fuzzy on when I can use 'this' as opposed to '$(this)'. I would love to use this.myAttr, but didn't think I could. I really, really appreciate you re-writing my code snippet to show me what you're talking about. I know that the 'this' vs. '$(this)' discussion was had not too long ago, but I didn't (or couldn't) pay too much attention at the time. If you'd rehash it for me, or point me to the old thread, I'd appreciate that too! :o) Cheers, Chris ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] break in $.each
Done a test (requires Firebug - or Firebug lite (which I presume would also work)). var foo = [one, 2, three, new Date()]; $.each(foo, function() { if(this === 2) return false; console.log(typeof this); } ) This logs: [o, n, e] 2 [t, h, r, e, e] Thu Jan 04 2007 13:09:12 GMT+ (GMT Standard Time) To the console, rather than just: one typeof(this) within $.each always returns 'object', so identity comparison doesn't work (you have to use == instead of ===) $.each() uses Function.apply() to set this for the callback function. Function.apply() converts its first argument to Object. That's why === doesn't work. Also, why does a string get returned as an array instead of a string? It's not being passed as an array, it's being passed as an Object. Firebug sees that the Object has a .length property and assumes it's an array. If you use alert() instead of console.log() you'll see something closer to what you expect. Would you like an Array iterator that works the way you'd expect? Here is a simple one: Array.prototype.each = function( yields ) { for( var i = 0, n = this.length; i n; i++ ) { if( yields( this[i], i ) === false ) break; } }; Then you can code: [ one, 2, three, new Date() ].each( function( value ) { if( value === 2 ) return false; console.debug( value ); }); No this, no monkey business with Object. If you don't want to extend Array.prototype, you can code a similar standalone function. It's really a very simple function, so there's no real reason to compromise with one that doesn't work the way you want. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] break in $.each
Would you like an Array iterator that works the way you'd expect? Here is a simple one: Array.prototype.each = function( yields ) { for( var i = 0, n = this.length; i n; i++ ) { if( yields( this[i], i ) === false ) break; } }; Then you can code: [ one, 2, three, new Date() ].each( function( value ) { if( value === 2 ) return false; console.debug( value ); }); No this, no monkey business with Object. If you don't want to extend Array.prototype, you can code a similar standalone function. It's really a very simple function, so there's no real reason to compromise with one that doesn't work the way you want. Speaking of which, here are standalone functions with test cases for objects and arrays: function objectEach( obj, fn ) { for( var name in obj ) if( fn( obj[name], name ) === false ) break; } function arrayEach( ary, fn ) { for( var i = 0, n = ary.length; i n; i++ ) if( fn( ary[i], i ) === false ) break; } objectEach( { a:'ay', b:'bee', c:'see' }, function( value, name ) { return confirm( name + ': ' + value ); } ); arrayEach( [ 'ay', 'bee', 'see' ], function( value, index ) { return confirm( index + ': ' + value ); } ); Click the Cancel button in any of the confirm() message boxes to return false and stop the iteration. Why are the callback function arguments in the order ( value, name/index ) instead of the seemingly more intuitive ( name/index, value )? It's because in the case of an array, you often want only the array values, so you can code the callback as function( value ) { ... }. These functions use simple argument passing instead of apply() and this, which makes them easier to code and much easier to understand. That also avoids the problem we saw earlier where this in the $.each callback is converted to an Object, and it means they work in any version of JavaScript. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] dynamic loading of jquery.js into my web page
I'm afraid that I simply don't take Safari users into account. Hardly a great thing, but I focus on three browsers: Firefox and IE7, and then IE6. In that order. The work I do is targetted at corporate users who run Windows 2000 and Firefox, and all the JS work I do is for those users. Then your solution is almost OK for you. Here is a usable version ;-) (function() { var addScriptCounter = 0; function addScript( url, callback ) { var script = document.createElement( 'script' ); script.myLoadHandler = callback; script.id = 'dynamicallyLoadedScript_'+addScriptCounter; script.type = 'text/javascript'; script.charset = 'utf-8'; script.src = url; var script2 = document.createElement( 'script' ); script2.type = 'text/javascript'; script2.charset = 'utf-8'; script2.appendChild( document.createTextNode( '(function(){'+ 'document.getElementById(\'dynamicallyLoadedScript_'+ addScriptCounter+'\').myLoadHandler();})()'; )); var head = document.getElementsByTagName('head')[0]; head.appendChild( script ); head.appendChild( script2 ); addScriptCounter++; } })() Usage: addScript('jquery.js', function() { alert('horay, jQuery is available'); }); alert('jQuery is not necessarily available here'); The second script tag will be evaluated after the first one has been loaded and evaluated. At least that works for all browsers I have tested with, except those Safari versions and very old browsers without a usable DOM implementation. That looks really dodgy, sorry. What if the browser downloads script and script2 at the same time, and script2 finishes first? Instead, simply edit your copy of jquery.js and add one like of code at the end of the file, to call a ready function that you've defined in your already-running code. If you have jQuery plugins that your code depends on, merge them all into jquery.js and add that function call at the very end. Hmm... This would make a nice patch for jQuery itself - when it concatenates all the files to make the various dist versions, add this line to the end of the merged code: window.jQuery_onload jQuery_onload(); John et al, what do you think? -Mike -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] break in $.each
Andreas, if I remember correctly, the following should work: $.each(object, function() { return false; }); That isn't supported. The necessary code was removed due to unsolved problems. Actually the stuff that Michael just posted would help a lot to solve it, though I'm not sure if it is even possible, due to the Function.apply usage. The code I posted does solve this problem completely - simply use objectEach instead of $.each, and change your callback function to take explicit parameters instead of using this. Using this in an object iterator doesn't make much sense anyway. You need two arguments (name and value) regardless, and the code is much more understandable when they are both named parameters. $.each should be regarded as a jQuery internal function only - there's no reason to use it when it's so easy to write your own, more straightforward iterator. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Another simple question...
this.id = 'NewValue'; alert( this.id ); I've got another simple question. Is this not how you set an element's attribute? [from inside an .each()] ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Having an issue accessing a node.
...since the spec requires name and ID to be identical, it's technically illegal to have a name with [ and an ID as well (since IDs cannot contain [). Um, where does it say the name and id have to be the same? -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] dynamic plugin loading
If you're just trying to load a stylesheet dynamically, all you need to do is this: function addSheet( url, doc ) { doc = doc || document; var link = doc.createElement( 'link' ); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = url; doc.getElementsByTagName('head')[0].appendChild( link ); } Similarly, you can load a script with: function addScript( url, doc ) { doc = doc || document; var script = doc.createElement( 'script' ); script.type = 'text/javascript'; script.charset = 'utf-8'; script.src = url; doc.getElementsByTagName('head')[0].appendChild( script ); } -Mike I'm trying to develope a small piece for dynamic loading in jquery, wich loads the .js and .css source files on the fly without any special markup in the html page. For .js files you can use jspax (www.jspax.org). I use it to load jQuery and plugins on demand (actually I made it for that purpouse at the beginning). For .css I just had that question from a friend of mine and made a small set of jsPax-packages for him: ---cssloader.js $using('xBrowser.simulateXMLHttpRequest',function() { $package('cssloader', { base: '/', load: function(css) { var x = new XMLHttpRequest(); x.open('GET',cssloader.base+css+'.css'); x.onload = function() { var e = document.createElement(style); e.type=text/css; e.appendChild(document.createTextNode(x.responseText)); document.getElementsByTagName(head) [0].appendChild(e); }; x.send(''); } }); }); --- ---xBrowser/simulateXMLHttpRequest.js var impl = 'native'; if( !window.XMLHttpRequest ) impl = (window.ActiveX)?'activex':'iframe'; $using('xBrowser.simulateXMLHttpRequest.'+impl,function() {}); --- ---xBrowser/simulateXMLHttpRequest/native.js: $package('xBrowser.simulateXMLHttpRequest.native',{}); --- ---xBrowser/simulateXMLHttpRequest/activex.js: var lib = /MSIE 5/.test(navigator.userAgent) ? Microsoft : Msxml2; window.XMLHttpRequest = function() { var rval = new ActiveXObject(lib + .XMLHTTP); rval.onreadystatechange = function() { if(x.readystate == 4) rval.onload(); }; return rval; }; $package('xBrowser.simulateXMLHttpRequest.activex',{}); --- use them like this: $using('cssloader', function(){ cssloader.base='https://www.example.com/styles/'; cssloader.load('mywonderfull'); ... }); I have not tested the code, but he did not complain up to now ;-) The problem is that it seems that the browser doesn't wait until the script (the plugin) is finished loading Yes, you are using assynchronous XMLHttpRequests. JsPax does that as well, but it can cope with that by usein callback functions. JSAN does use synchronous XMLHttpRequests to circumvent that problem. ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] dynamic plugin loading
From: Michael Geary If you're just trying to load a stylesheet dynamically, all you need to do is this... Just to be clear, I wasn't disparaging jsPax! It just depends on whether you need a full-featured package system or a simple loading function. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] msie closures syntax
Not only not related to jQuery, but not related to closures either. :-) The problem is that setTimeout doesn't accept the additional arguments you are passing it. Is there any reason you can't do this: setTimeout( function() { doStuff( stuff, 1, 2 ); }, 100 ); That would work in any browser. -Mike i hope someone on this list can help me here, even tho my question is not directly related to jquery (duck). i have trouble getting my closures to work in ie: --snip // // A) this doesn't work in ie (ff opera grok it) // setTimeout( function( a,b,c ) { doStuff( a,b,c ) }, 100, stuff, 1, 2 ); // // B) this works in IE // var fref = iehelper( stuff, 1, 2 ); setTimeout( fref, 100 ); function iehelper( a,b,c ) { return ( function() { doStuff( a,b,c ); }); } --snap anyone know how to feed that to ie without the nasty helper function? ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] msie closures syntax
this doesn't work like a local variable. Inside a nested function, this is not the same as in the outer function. That's what is messing things up. If I understand your code, you can write it more simply like this: (function($) { $.fn.Tooltip = function(settings) { var $all = this; settings = $.extend($.extend({}, arguments.callee.defaults), settings || {}); $all.filter('[EMAIL PROTECTED]').bind( settings.event, onmouseover ); return this; function onmouseover( event ) { //... setTimeout( function() { on( $all.attr('id'), $all.attr('ttbody'), event.pageX + settings.xoffset, event.pageY + settings.yoffset ); }, settings.ondelay ); //... } function on( mysrcid, body, x, y ) { // do stuff... } }; })(jQuery); But now that it's simple enough for me to understand, one question comes to mind: Do you use this plugin only with a single element, e.g. $('#foo').Tooltip(), or can it use multiple elements, e.g. $('.foo').Tooltip()? The two attr() calls inside the setTimeout don't look right for multple elements. -Mike well, i need to pass some arguments to doStuff() that seem to be out of scope when it fires. to clarify, below is the relevant snippet of my real code with your variant applied: snip (function($) { $.fn.Tooltip = function(settings) { settings = $.extend($.extend({}, arguments.callee.defaults), settings || {}); $(this).filter('[EMAIL PROTECTED]') .each(function() { this.tSettings = settings; }) .bind( settings.event, onmouseover ); return this; }; //... function onmouseover( event ) { //... // // firebug throws this.tSettings has no properties on the next line // (when the timeout fires) // setTimeout( function() { on( $(this).attr('id'), $(this).attr('ttbody'), event.pageX + this.tSettings.xoffset,event.pageY + this.tSettings.yoffset ); }, this.tSettings.ondelay ); //... } function on( mysrcid, body, x, y ) { // do stuff... } //... })(jQuery); snap as you may have guessed i'm tampering with the tooltip plugin and am probably missing something obvious... ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] (no subject)
Try this (untested): $(function() { $('.y').html( (new Date).getFullYear() ); }); -Mike p.s. Could we avoid profanity on the mailing list? Thanks. _ From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Kristaps Ancans Sent: Tuesday, December 19, 2006 12:44 AM To: discuss@jquery.com Subject: [jQuery] (no subject) Ok i'm a newbie in jquery and i'm trying to write function that will replace all span class=y!-- --/span element's content with current year. My function looks like this: $(function(){ $(.y).ready(function() { var today = new Date(); var year = today.getFullYear(); document.write(year); }); }); but when i run it - it replaces all the document with current year. In which place my mistake is ? -- FYFI - for your fucking information ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Remove from JSON
I suppose this touches on off topic, but ... is it possible to remove an entry completely from a JSON hash? say I have { firstString: 'first', secondString: 'second' } and evaluate this into a json object, and I want to remove firstString, could I do something like json.remove(json.firstString); I think json.firstString = null or delete json.firstString work (although IIRC delete is not supported by IE 5.5 or earlier). json.firstString = null does not delete the property. It merely sets its value to null. delete json.firstString actually deletes the property. It is supported by every browser that jQuery supports. For IE, the delete operator goes back to JScript 3.0, which was implemented in IE 4.0. Here is a handy chart that shows IE version support for JavaScript features: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/ht ml/440f4924-f7a9-48e0-873e-bd599a93b437.asp -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Remove from JSON
I suppose this touches on off topic, but ... is it possible to remove an entry completely from a JSON hash? say I have { firstString: 'first', secondString: 'second' } and evaluate this into a json object, and I want to remove firstString, could I do something like json.remove(json.firstString); ? Well, JSON is just a notation. Once you evaluate it, it's not JSON any more. It's a JavaScript object. It doesn't matter whether the object started out as JSON notation, or was built up using other JavaScript code, it works the same either way. Those entries in the object are called properties. So that means the question is really, How do I delete a property from a JavaScript object. That leads to a useful search: http://www.google.com/search?q=remove+property+from+javascript+object -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Dynamically added click registration always returns the last value added
You're using the variable j to hold a reference to each element of the jobs array as you go through the loop. After the loop finishes, j is a reference to the last element of that array. Later, when the click function gets called, j still refers to that last element - regardless of which element triggers the event. You need to keep track of each of those elements separately. The easiest way to do that is with a closure. Also, you don't want to use for in to iterate over an array. Use a C-style loop instead. So, you could code this: for( var i = 0, n = json.jobs.length; i n; i++ ) { (function( job ) { // ... $(#editJob + job.jobID).click(function() { alert(job.jobID); }); })( json.jobs[i] ); } The inner function captures a separate job variable for each instance of the loop, so when the click function gets called later, it will have the correct reference. (I took the liberty of changing the name from j to job just to make the example more clear - I always think of j as an index variable like i.) Even better, jQuery has an iterator function you can use to simplify the code: $.each( json.jobs, function( i, job ) { // ... $(#editJob + job.jobID).click(function() { alert(job.jobID); }); }); Again, each click function will use its own copy of the job variable - not because of any jQuery magic, but simply because of the use of the inner function. $.each just runs the loop for you. -Mike The a tag that was in the var div line got rendered as an actual link. Here it is again with spaces to prevent it from being rendered as a link: var div = div id='job + j.jobID + 'h1 id='jobTitle + j.jobID + ' style='display:inline;font-weight:normal' + j.companyName + /h1nbsp;| a href='#' id='editJob + j.jobID + 'edit / a; I'm parsing this JSON: {result:success,successText:Your changes have been saved successfully.,errorText:,memberID:49,mode:edit,jobs:[{ jobID:1,companyName:SAIC},{jobID:2,companyName:Aspentech },{jobID:3,companyName:Cardinal Health}]} ...with this Javascript: $(#panelManageJobView).empty(); for (var i in json.jobs) { var j = json.jobs[i]; var div = div id='job + j.jobID + 'h1 id='jobTitle + j.jobID + ' style='display:inline;font-weight:normal' + j.companyName + /h1nbsp;| # edit ; div += div style='padding-top:10px;display:none' id='jobEdit + j.jobID + '/div/div; if (i 0) { div = div class='padLine'nbsp;/div + div; } $(#panelManageJobView).append(div); //now register click event on edit link $(#editJob + j.jobID).click(function() { alert(j.jobID); }); } Everything works fine, and is added to the page correctly. I even viewed the generated HTML and confirmed that the ID's are correct on each div that gets appended. However, when I click on the edit link next to each item, the alert always shows the last jobID that was received in the JSON - 3 in this example. I'm expecting to get 1 if I click the first edit link, 2 if I click the second, and so on. Any ideas what I'm doing wrong? ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Trouble with $(expr, context) and iframe documents
From: Adam Skinner I'm trying to reference an element from within an iframe. The following normal javascript code works: var iframeDoc = window.frames[iframeName].document; var data = iframeDoc.getElementById(iframeElement); I'm trying to jqueryize the data variable as follows (using the actual element id name for the time being): var d2 = $(#inside_iframe_element,iframeDoc); This just yields [], however. How do I refer to an element within the iframe? Take a look at the code that handles the # selector in jQuery and you will see why this doesn't work: if ( m[1] == # ) { // Ummm, should make this work in all XML docs var oid = document.getElementById(m[2]); r = ret = oid ? [oid] : []; t = t.replace( re2, ); } else { It's using a hard coded document.getElementById() instead of using the document you provide. The best way to work around this for the moment would be to continue to use your own iframeDoc.getElementById() call but simply wrap the result in a jQuery object: var d2 = $( iframeDoc.getElementById(iframeElement) ); If you're doing a lot of these, of course it would make sense to wrap it up in a function: function $frame( doc, id ) { return $( doc.getElementById(id) ); } And then you could use: var d2 = $frame( iframeDoc, iframeElement ); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] passing functions
I had to do something similar today, and I did something like function myfunction(f){ $(element).click(function(){eval(f+(););}); } that was off the cuff, but that should work. That would be the ticket if f is a string containing the name of a function. But why not just pass a function reference around directly? Then you could simply do: function myfunction(f){ $(element).click(f); } -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] [OT] Firefox 2.0 Annoying Errors
This has nothing to do with jQuery, but I'm hoping that some of you might have seen this and figured out how to make it go away. I have googled for it, but nothing helpful showed up. not jquery. I get a bunch of errors each time I start up ff 2... they don't recur. do yours? Did you try this: Uninstall FF2, kill any remaining Firefox processes in Task Manager, and reinstall FF2. I had a bunch of problems when I upgraded and that fixed them. One of the other problems I had was missing bookmarks, which led me to this page where I found the reinstall tip: http://kb.mozillazine.org/Lost_bookmarks -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] closure and name conflict
I really have no idea what is the correct name(I'm not a javascript guru), handle is a function in function(or jQuery?) scope? You know , i just copy your code structure. xD Demo page: http://61.191.26.228/jQuery/plugins/modal/test.html Your functions named plugin, modal_handle, modal_parse, modal_display, modal_load, modal_after_load, modal_error, modal_resize, parseQuery, and modal_close are all defined like this: theName = function() { ... }, There are two mistakes there. The functions are globals, when you probably want them to be local. The fact that they are global is what was causing one to overwrite another with the same name. Also, that comma after the } shouldn't be there. It looks like you picked up the use of the comma from object literals such as: var foo = { oneFunction: function() { ... }, anotherFunction: function() { ... }, andAnother: function() { ... } }; These functions should be defined with either: var whatever = function() { ... }; Or: function whatever() { ... } The latter is probably a better choice because it's simpler. Finally, you're missing a semicolon after settings in the var list at the top. That won't affect anything unless you try to run the code through a packer to compress it - then you may have errors. I didn't look at the code in any great detail other than that. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] closure and name conflict
From: Michael Geary Also, that comma after the } shouldn't be there. It looks like you picked up the use of the comma from object literals... From: Jörn Zaefferer Actually there is a single var at the top, therefore the problem must be somewhere else... My fault, I should remove that stuff from the tooltip. Ah! I missed that. So the whole thing is one long var statement. Interesting approach, and it explains what really went wrong in epaulin's code. Note my other comment: Finally, you're missing a semicolon after settings in the var list at the top. That won't affect anything unless you try to run the code through a packer to compress it - then you may have errors. Here's a stripped down version of the entire plugin: (function($) { var ... modalCloseBtn, settings /* missing semicolon, I thought */ plugin = $.fn.Modal = function(defaultSettings) { ... }, modal_handle = function(event) { ... }, modal_parse = function() { ... }, ... modal_close = function(event) { ... }; plugin.defaults = { event: , after: null, ... shadowOffset: 5 }; })(jQuery); So what was *really* missing here was a comma, not a semicolon - because the function definitions were all supposed to be part of that one var statement. Instead, the JavaScript interpeter sees that it can't parse the code as is, and it inserts a semicolon after settings - thus cutting off the function definitions from the var statement. The code still runs, but all those assignments have become globals instead of locals. Oops! I think I would change it to this: (function($) { var ... modalCloseBtn, settings; var plugin = $.fn.Modal = function(defaultSettings) { ... }; function modal_handle(event) { ... } function modal_parse() { ... } ... function modal_close(event) { ... } plugin.defaults = { event: , after: null, ... shadowOffset: 5 }; })(jQuery); Or maybe just: (function($) { var ... modalCloseBtn, settings; $.fn.Modal = function(defaultSettings) { ... }; function modal_handle(event) { ... } function modal_parse() { ... } ... function modal_close(event) { ... } $.fn.Modal.defaults = { event: , after: null, ... shadowOffset: 5 }; })(jQuery); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] getScript error
Why not use document.createElement(script) !? Because we want jQuery to wait until the script is loaded and evaluated, so it's possible to do something upon completion, like continuing the normal flow of the program. This is necessary for example for writing a require like the one in PHP. You can't do that, and you wouldn't want to if you could. JavaScript doesn't work that way. If you were successful in getting JavaScript to wait until a script is loaded, the entire browser would be locked up in the meantime. What you *could* do is something like this: require( script, completion ); e.g. require( 'test.js', function() { // This code runs when the script is loaded }); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Off topic: which programming language for webdevelopment
Our company is looking for a way for 'quick' web-development. Small webapps consisting of a few webpages with some minimal database interaction. We currently develop everything in Java (including webapps), but I find the whole cycle of developing, compiling (java class files, EJBs etc), deploying, JNDI setup, db resource setup and recompilation (of the jsps) too heavy. Additionally, for applications with a limited number of users (50 would be a huge userbase in this case), I think that a clustered multitier application server (our current deployment platform) is w too complex. I would like to propose a (any?) scripting language as alternative. Since you're currently a Java shop, it may be helpful to read about what some leading Java developers (Bruce Tate, David Geary, etc.) are doing. http://www.google.com/search?num=100q=java+ruby+rails+tate+geary -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] jQuery 1.1 by the end of Nov
But, I would be sad to see .click, .hover, and .toggle go away, if they are among the helper functions you plan to put into a an external plugin. They just make so much more sense than bind to people new to programming/javascript/jQuery. I am not a fan of bind either, I'm sure it was inherited from the other frameworks that use it. I would prefer .on() and .un() (or perhaps .no()? ) because they're short and a bit more intuitive. .on() sounds like a winner to me. Not sure about .un(), but I don't have a better idea - and .un() is certainly better than .no(). To me, click is a verb and it's not intuitive to be setting a click handler with the word click. Same here. Especially when the function is overloaded so that .click() [with no args] *is* a verb, i.e. it triggers the click event. Nasty! -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] parsing JSON with $.each
From: Kevin Old I'm parsing some json successfully below, but I'd like to be able access the contents of the json object like this.[id] or this.[name]. function processData(json) { $.each(json, function(i) { $(#names).append(ID: + this[0] + Name: + this[1] + Passwd: + this[2] + Url: + this[3] + br ); } ); } Just wondering if anyone knows how to do it that way. Well, you don't really parse JSON. By the time you look at it, it's just a JavaScript object, so you have to access it using whatever JavaScript corresponds to the way that object is structured. It sounds like your json object is an array of arrays, e.g. [ [ my id, my name, my password, my url ], [ your id, your name, your password, your url ] ] Is that correct? To use it the way you want, it needs to be an array of objects instead: [ { id: my id, name: my name, password: my password, url: my url }, { id: your id, name: your name, password: your password, url: your url } ] Then your code could read: function processData(json) { $.each(json, function() { $(#names).append( ID: + this.id + Name: + this.name + Passwd: + this.password + Url: + this.url + br / ); }); } Or, for better performance in most browsers: function processData(json) { $.each(json, function() { $(#names).append( [ ID:, this.id, Name:, this.name, Passwd:, this.password, Url:, this.url, br / ].join(' ') ); }); } If you can't change the format of the JSON data you're receiving, but you still want to use the more convenient this.id instead of this[0], you can convert it to an array of objects yourself. Let me know if you'd like sample code for that. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Object vs. Array looping
In the .css method an array is created by: d = [Top,Bottom,Right,Left]; Then it is looped through using object looping: for ( var i in d ) { This probably isn't a problem for most people, but we have added functions to the Array prototype, so whenever the .css method is used it dumps the text of all those functions into the CSS and bloats the code considerably. I made the following patch and tested it. It seems to work fine: Index: jquery.js === --- jquery.js(revision 575) +++ jquery.js(working copy) @@ -1472,7 +1472,7 @@ if ( p == height || p == width ) { var old = {}, oHeight, oWidth, d = [Top,Bottom,Right,Left]; -for ( var i in d ) { +for ( var i = 0; i d.length; i++ ) { old[padding + d[i]] = 0; old[border + d[i] + Width] = 0; } Yeah, I noticed that a while ago too. I was going to commit a fix but never have had much luck with svn on jquery.com. I like doing it this way, but either one would work the same: if ( p == height || p == width ) { var old = {}, oHeight, oWidth, d = { Top:1, Bottom:1, Right:1, Left:1 }; for ( var w in d ) { old[padding + w] = 0; old[border + w + Width] = 0; } -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] How do I add a js array of jquery objects toajqueryobject?
From: Michael Geary Yeah, all that DOM creation will take a while - especially if you use a convenience plugin like mine. I get much better performance across browsers with [].join('') and innerHTML. From: Dave Methvin There don't seem to be that many situations where DOM creation is the performance bottleneck though. Probably the one one where I've seen a real difference is using ajax to fill a large table. Even in this case it turned out to be a $(.class) selector in a loop and not DOM creation. One trick I've used that speeds up DOM creation is to create an element and then use .cloneNode on it rather than create a new one each time. Good point. The first thing to look for when optimizing jQuery code is $() selectors being needlessly called in a loop. That is probably by far the most common problem. It was funny that in my whole discussion of building HTML strings and using innerHTML, I mentioned save a reference and that turned out to be the solution, completely unrelated to all the other stuff I was suggesting. OTOH, in my own code, even after I optimized all the jQuery stuff, innerHTML performed much better than DOM creation - it was several times faster for a day picker widget with a lot of nested elements. In my case, much of the overhead was actually my DOM creation plugin. When I first experimented with innerHTML, I changed the DOM creation plugin to generate HTML instead of DOM elements, and it was hardly any faster! Then I went to straight HTML text with [].join('') and it was several times faster. Most of the comparisons between innerHTML and DOM are inherently unfair because the innerHTML examples don't guard against malformed HTML strings. If a user enters a special character like a quote, the string doesn't parse properly. With innerHTML there's the risk of cross-site scripting attacks as well if input is being accepted from the user, the URL, or unfiltered database results. Ah! Good reminder! I'd better check over my code with a fine-tooth comb! :-) -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Why won't this work?
So...the lesson is...the jquery.js file always has to be included for the jQuery code to work and it has to be referenced first...correct? It doesn't have to be *first*, but it does have to be before any code that uses jQuery. Think about it this way... Would this code work: alert( x ); var x = 1; Probably not! :-) Script files are loaded in the order they appear in the code, so just as that example wouldn't work, trying to use jQuery functions before they are loaded won't work either. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Element tagName
From: Truppe Steven my view of the things is a big different. I think jquery should stay as small as possible so adding functions for basic dom attributes is a bit overhead i think .. I agree. How do you decide which of the many DOM attributes to turn into jQuery methods? All of them? Especially if they have different names than the DOM attributes. That is just confusing, unless the idea is that someone should be able to program only in jQuery and never have to touch the actual DOM. If you compare these: $(foo).tag() $(foo)[0].tagName The first looks shorter, but if we make it fair and use the same name: $(foo).tagName() $(foo)[0].tagName Then it's not much of a win. Hmm... Using the same name makes it confusing. Do I use parens after tagName or not? But using two different names makes it confusing too. Do I spell it tag or tagName? Is tag the same as tagName, just a passthrough, or does it do some actual processing ala .html()? I just don't see the value here. (No offense to anyone who likes it!) -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Elements aren't expanding when appending new children
When you have a problem like this, your first thought should be to look at the generated HTML using Microsoft's DevToolBar in IE or either FireBug or View Source Chart for Firefox. I moved Testnode up and then moved it to the right, then used FireBug's Inspect tool to reveal the generated HTML. This is what I saw: div id=main ul id=nodes class=sortable li id=node5 class=sortableitem /li li id=node1 class=sortableitem style=overflow: visible; height: 164px; display: block; width: 472px; opacity: 0.; ul id=nodes1 class=sortable li id=node3 class=sortableitem /li ... Do you see what went wrong? :-) -Mike My problem is that, when moving elements right (iow creating a new ul as a child to an existing li), the parent element is not expanding, so the newly created ul is overlapping with other elements. Just look at my example page: http://xcite-online.de/tests/jquery1/ http://xcite-online.de/tests/jquery1/ . The code is http://snipplr.com/view/1649/jquery-and-uls-on-the-flow/ here , the important part is this: $(../..,this).next().append(ul class='sortable'li class='item'foo/li/ul); ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Elements aren't expanding when appending new children
I moved Testnode up and then moved it to the right, then used FireBug's Inspect tool to reveal the generated HTML. This is what I saw: Actually I left out part of it by mistake. Here's the entire UL: ul id=nodes class=sortable li id=node5 class=sortableitem/li li id=node1 class=sortableitem style=overflow: visible; height: 164px; display: block; width: 472px; opacity: 0.; ul id=nodes1 class=sortable li id=node3 class=sortableitem/li li id=node4 class=sortableitem/li li id=node2 class=sortableitem style=overflow: visible; height: 30px; display: block; width: 472px; opacity: 0.; span class=icons a class=moveup/a a class=movedown img src=img/go-down.png//a a class=moveleft img src=img/go-previous.png//a /span/li /ul span class=icons /span/li /ul node2 is the one I moved up and then to the right. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Elements aren't expanding when appending new children
One more comment... As you probably figured out from looking at the generated source, the culprit is likely to be the animation code, which sets those unwanted attributes when it animates an item. So one good test would be to remove all animation and see if it generates better code. It will also make the interface more usable. The animation that's there now doesn't serve any purpose, and it's confusing. The elements shouldn't be zooming down to a point and then re-expanding. When I move a physical object it doesn't do that. Instead, if you want some useful animation, show the element moving from its old position to its new one, without any unnecessary size changes. -Mike In other words, the animation should help show what is actually happening, My problem is that, when moving elements right (iow creating a new ul as a child to an existing li), the parent element is not expanding, so the newly created ul is overlapping with other elements. Just look at my example page: http://xcite-online.de/tests/jquery1/ http://xcite-online.de/tests/jquery1/ . ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] How do I add a js array of jquery objects to a jqueryobject?
From: Andrea Ercolino I have got an array of 50 urls templates, and want to make a proper url out of each one, adding also a special click, and then append all these urls to a div in a specific position. All this should be done many times in a page, many could be 50, just to say something that could be possible, but it's really an unpredictable number of times. (well, less than a 100 is a good guess) I think the problem lies in the dom creation. Each link is inside 4 nested divs, so this could mean 80 bytes each (adding structure and data). At only 3 divs ( x 50 = 150 appends ) I'm experimenting a delay of a couple of seconds for reloading the page, and for this test the page has no content other than those divs! Yeah, all that DOM creation will take a while - especially if you use a convenience plugin like mine. I get much better performance across browsers with [].join('') and innerHTML. Here's a design pattern I use all the time. I threw in some arbitrary divs and spans to show how the nesting works out. // Return HTML rendering for an array of strings function renderAll( array ) { var inner = []; for( var i = 0, len = array.length; i len; i++ ) { inner[inner.length] = renderOne( array[i], i ); } return [ 'div id=wrap1', 'div id=wrap2', inner.join(''), '/div', '/div' ].join(''); } // Return HTML rendering for a string item function renderOne( item, i ) { return [ 'div id=myitem', i, '', 'span class=myitem', item, 'span', '/div' ].join(''); } A test call could be: $('#testdiv').html( renderAll( [ 'one', 'two', 'three' ] ) ); This same basic pattern works for tables, or anything where you have nested and repeated elements. It works in just about any browser - even very old ones, thanks to the use of inner[inner.length] instead of inner.push(). And it's very fast - much faster than the same DOM operations. Obviously you could replace the [].join('') with ordinary string concatenation, but the array join is faster on most browsers. The one big drawback is that you don't automatically get references to the objects you're creating. With DOM creation, you can save references to your objects, making it very fast to get to those objects later. To make up for this, you can assign unique IDs in the HTML code as the example does. Obviously you could extend this all sorts of ways. In my actual code, the item is usually an object and not a string, and the renderOne function builds up HTML from that object's properties. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Since updating to 1.0.3 converting to getJSON
And to make it valid JSON, you have to quote all keys anyway (using double quotes): { asJSON: 1, class: jlink, id: htmlDoc } http://json.org/ Naw, that wouldn't be valid JSON. JSON doesn't allow named references like htmlDoc. But this object doesn't need to be JSON anyway. It's just an object literal being passed into a JavaScript function call. From the original message: $.getJSON( ./ajax/json.php, { asJSON: 1, class: jlink, id: htmlDoc }, function(json) { }); Quote the class and it should be good. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] OO programming is confusing to old functional programmers
I don't think this approach will work quite the way you'd like. In your example: // I access my plugin via: $(#myMap).Map({ options hash }); // later I can access a public function on this object like: $(#myMap).Map.recenter(x, y, dxy); Those two $(#myMap) calls are going to result in different jQuery objects. How does the recenter() method know it applies to the Map object you created earlier? OTOH, you could easily get this to work: // Create a map object for an element var map = $(#myMap).Map({ options hash }); // later I can access a public function on this object like: map.recenter(x, y, dxy); But before I make any more specific suggestions, does your Map object always relate to a single map as in your example, or could one Map object relate to multiple maps, e.g. // Get a Map object that controls every map with class anyMap var maps = $('.anyMap').Map(); // Recenter all the maps maps.recenter( x, y, dxy ); -Mike From: Stephen Woodbridge OK, How much of this is right? jQuery.Map = { // this is a public global attribute? // ie: global across all instances of jQuery.Map whatever : null, // a public function init : function(options) { // this is the jQuery search collection // self is a private pointer to the collection var self = this; // another private variable scoped to the function var _maph = 0; // an public attribute, accessed via $(#map).Map._maph this._maph= 0; // a method, accessed via $(#map).Map.recenter(x,y,dxy) this.recenter = function(x, y, dxy) { console.log(calling recenter()); }; return this.each( function(options) { // this is each respective object in the collection // this is a DOM object not a jQuery object // here I can modify the DOM, bind events, etc }; }; // This extends jQuery with my plugin jQuery.fn.extend( { Map : jQuery.Map.init } ); // I access my plugin via: $(#myMap).Map({ options hash }); // later I can access a public function on this object like: $(#myMap).Map.recenter(x, y, dxy); Is this right? I probably have some terminology mixed up. -Steve ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/ ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Plugin Release: Tooltip
From: Michael Geary (function($) { // plugin code here })(jQuery); From: Sam Collett I've seen that used before, but can it have memory leak or other issues? Sorry about the very slow reply, Sam. That's a good point. The use of the closure could result in memory leaks depending on what the rest of the code does. They should be fixable - closures in and of themselves don't cause leaks, but they can result in circular references to DOM objects in IE. It would be good to test this and make sure it doesn't cause a leak. Does it work on all modern browsers (and not so modern - IE 5), included those on PDA's etc (not that jQuery supports portable devices). Yes, closures are standard JavaScript and work in every version of JavaScript since 1.1 or 1.2, I forget which. What happens if 'jQuery' is undefined? Then you'll get an error when it tries to call the closure function with the jQuery argument. Of course, the same thing would occur if you coded a plugin the traditional way: jQuery.fn.foobar = function() {}; -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Element tagName
From: Laurent Yaish I couldn't find a way using jQuery to get the tagName of an element. Let's say I have this: divspantest/span/div $('span').parent().tag() would return 'div' From: Brandon Aaron You could do two things ... write yourself a plugin that would look something like this: jQuery.fn.tag = function() { return this[0] ? this[0].tagName : null; }; That would certainly do the trick. I can't resist a little code optimization... :-) jQuery.fn.tag = function() { return this[0] this[0].tagName; }; or you could just do it like this: $('span').parent().get(0).tagName Or: $('span').parent()[0].tagName Although here I can see where one might prefer the .get(0) for clarity - not sure which I like better. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Plugin Release: Tooltip
From: Jörn Zaefferer I actually managed to release my first official and documented jQuery plugin, a Tooltip implementation. It doesn't use AJAX, nor extra markup, only title and href attributes and some styles. You can customize the delay after which it should be displayed, default is instant display when hovering something. More details and examples can be found here: http://bassistance.de/index.php/jquery-plugins/jquery-plugin-tooltip/ Comments are welcome! Very nice! It doesn't behave the same as a standard tooltip, though. Tooltips don't usually track the mouse - once a tooltip is displayed it doesn't move. It would be nice to have that option. In fact, instead of the defaults being no delay and mouse tracking, I'd suggest making the defaults follow the most common tooltip behavior - a short delay and no mouse tracking. Whatever you make the defaults, it would be more flexible to change the delay argument to an args object with properties like delay and track and whatever else comes up later. Then you could code like this: $(foo).Tooltip({ delay:250, track:true }); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Plugin Release: Tooltip
http://bassistance.de/index.php/jquery-plugins/jquery-plugin-tooltip/ A suggestion - perhaps you should use 'jQuery' instead of '$' as isn't that the convention for plugin authoring? The code does use jQuery instead of $. Jörn used the trick I suggested a while back to get the best of both worlds - convenient coding with $ but not using the global $. Note the function wrapper: (function($) { // plugin code here })(jQuery); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Plugin Release: Tooltip
From: Paul McLanahan The only suggestion I have deals with displaying the tips close to the right side of the screen. You do an excellent job of handling the width of the tip when it is close to the right edge of the window, but if a word is too long inside of the tip it will push outside of the viewable area and cause the horizontal scroll bar to appear. I would suggest that you attempt to detect that situation and flip the tip so that it shows to the left of the pointer when it is too wide to be completely within the window. Great idea, and it's not too hard to do, like on this page for example: http://denverpost.zvents.com/venues/show/13197 When you hover over any of the map pins, a tooltip-like window appears. If there isn't room on the right, it goes on the left instead. Similarly, if there isn't enough room below the pin, the tip moves up. (But I just noticed a bug - I meant to move the tip so that its bottom lines up with the bottom of the little box around the pin, like the way the top of the tip lines up with the top of the box normally - but it's badly misaligned. It works OK in the horizontal direction.) All I had to do to make this work was first generate the tip in its normal bottom-right position and then see if it overflows the visible area of the window. If it does, then I move it to the left or up. The tip window's offsetHeight and offsetWidth are available at this point, and the browser won't actually render the tip window until the JavaScript code stops executing - so it does no harm to first generate it in one position and then move it to another. I use this code to get the viewport (visible rectangle of the window). I think I saw similar code in one of the jQuery plugins: viewport: function() { var e = document.documentElement || {}, b = document.body || {}, w = window; return { x: w.pageXOffset || e.scrollLeft || b.scrollLeft || 0, y: w.pageYOffset || e.scrollTop || b.scrollTop || 0, cx: min( e.clientWidth, b.clientWidth, w.innerWidth ), cy: min( e.clientHeight, b.clientHeight, w.innerHeight ) }; function min() { var v = Infinity; for( var i = 0; i arguments.length; i++ ) { var n = arguments[i]; if( n n v ) v = n; } return v; } } In the returned viewport, cx and cy are the width and height (old habit of using Windows naming conventions here!), and x and y are of course the left and top. Then, after generating the popup window, I compare its offsetLeft, offsetTop, offsetWidth, and offsetHeight against the viewport and move it as needed. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] return this.each
From: Simon Corless Thanks for the help Mike, it's starting to come together. I've been testing it just now. If I do use return this.each() then how do I reference the jQuery methods? without this.hover() etc? Obviously as this is no longer what I am expecting this.hover (as you say) fails. So do I use my 'self' variable or another way? If you are calling each(), that means your plugin may operate on more than one element, right? If you do var self = this; outside the each() call, that is a reference to the entire jQuery object - an array of all the DOM elements. The reason you would call each() is to operate on those elements one by one. So in most cases that 'self' isn't what you want inside the each() inner function. In that inner function 'this' is the individual DOM element, so if you want a jQuery object for that element, use $(this). Let's try some more descriptive names instead of self and this: (function( $ ) { $.fn.twiddle = function() { var $all = this; $all.each( function() { var element = this, $element = $(element); // Now we have: // $all - jQuery obect for all matching elements // $element - jQuery obect for a single element // element - a single element itself }); }; })( jQuery ); Now you can write the entire plugin using meaningful names. In practice, I tend to use shorter names like e and $e instead of element and $element, but I used the longer ones here to make it more descriptive. Remember that if the plugin doesn't need to work on the individual DOM elements but only uses jQuery methods on the whole collection, then you don't need an each() loop at all. Contrast a plugin that sets all matching elements to the same random color: (function( $ ) { $.fn.twiddle = function() { var $all = this; $all.background( randomColor() ); }; })( jQuery ); vs. a plugin that sets each matching element to a different random color: (function( $ ) { $.fn.twiddle = function() { $all.each( function() { var element = this, $element = $(element); $element.background( randomColor() ); }); }; })( jQuery ); Note the use of the $ prefix to indicate that a variable is a jQuery object, and the use of matching names with and without the $ when you have both a DOM element and a matching jQuery object for that element only. A similar use of this pattern is: var $foo = $('.foo'), foo = $foo[0]; This is for typical non-plugin code where you're starting with a query. Instead of writing code like this: $('.foo').zip(); // more code $('.foo').zoom(); // more code $('.foo').fly(); You'd write: var $foo = $('.foo'); $foo.zip(); // more code $foo.zoom(); // more code $foo.fly(); In this case we're not using any DOM methods, so we only use $foo and not foo. I thought I saw someone just using .hover() (without any prefix) but this just fails. You probably saw code like: $('.foo') .zip() .zoom() .fly(); That's a single line of code split into multiple lines. It's the same as: $('.foo').zip().zoom().fly(); I don't fully understand the difference, currently I don't use any dom methods I just use jQuery (I partly thought that was the point of it? - Although I realise sometimes you need to go deeper). jQuery doesn't try to provide its own equivalent of every possible DOM property and method, so it's pretty handy to be able to mix and match when you need to. Basically I have 3 internal functions defined in two ways as: nextItem = function () or function pause() Am I right in thinking that nextItem() could be called through a jQuery chain and that pause() can only be called internally from my plugin? Or are they both the same just written differently? Those are just different ways of writing functions - they have little or nothing to do with how a function can be used. For example, these are essentially identical, creating functions in the current scope: var foo = function(){}; function foo(){} If I left off the var, the first one would create a global function: foo = function(){}; That is usually a mistake, as it is in your code - your nextItem should be either: var nextItem = function()... or: function nextItem()... The latter would be more consistent with the rest of your code, so that's what I'd use. Another coding tip or two... You have several places with code like this: settings['blank'] That's OK, but you can substitute the simpler: settings.blank I would change this code: if (items[i]['link']) { self.html(a href=\\ + items[i]['item'] + /a); } else { self.html(items[i]['item']); } to: var item = items[i]; if (item.link) {
Re: [jQuery] this.name
why doesn't this work: $('#text-field').val(this.name); What is this? You haven't given it a value. So it depends on the context of this code. If the code is not in an object method, then this is the window object. when this does: $('#text-field).click( function() { alert(this.name); } ); ? did i find a bug? also: what does 'this' refer to? the jquery object, right? Now your reference to this is inside a function, specifically an event handler. jQuery follows the same practice as the native DOM: inside an event handler, this is the DOM element associated with the event. That's why you can do this.name. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] return this.each
Simon, you've run into one of the more confusing things about jQuery. I think it's safe to say that jQuery code would be easier to understand if it used explicit function arguments everywhere instead of this. (There are other advantages of using this, but it is definitely a mixed blessing.) Every time you call a function in JavaScript (any JS code, jQuery or not), this is set specifically for that function. Normally it works this way: If the function is a method of some object, then this is a reference to that object. In a function that isn't a method, this is a reference to the window object. (More precisely, this is a reference to JavaScript's global object, which in a browser happens to be the window object.) JavaScript code can also use the apply() or call() methods to call a function and explicitly set this to any specific object. jQuery uses apply() to set this to different things for different kinds of functions. Inside a plugin method itself, this is a reference to the jQuery object the method is operating on. When a plugin calls this.each(), that iterates over the jQuery object and calls a function for each DOM element in that object. Inside that callback function, this is the DOM element itself. That's why your code works when you comment out the this.each() call. Your this.html() and this.hover() calls are calling jQuery methods, not DOM methods. So you need this to be the jQuery object - which it is when you don't use this.each(). With the this.each() call in the code, those two innermost lines are instead executing as part of each's callback function. Therefore, this is the DOM element itself. DOM elements don't have html() and hover() methods (but you could use this.innerHTML for example). If you are only using other jQuery calls inside your plugin method, and you aren't directly manipulating the DOM elements themselves., then you don't need to call this.each() at all. In that case you need to put return this; at the end of your method (and if you have any other return statements, make them return this; as well). Your method will work the same with or without, but if you leave out return this; it will break the chain: $('.foo').mycoolplugin().show(); The show() call will fail if you don't return this;. OTOH, if you are writing code that uses DOM methods and properties, then you'd use this.each() in the plugin to iterate through the DOM elements. You still need to return this; in such a method, but because it's a common pattern, you can say return this.each(...); - the return value from the each() call is this, so you will be returning the right value this way. Regarding the var self = this; that you see a lot of, that's needed when an inner function needs to reach out to the outer function and see its this object. For example, a plugin may use this.each() to do some work on the DOM elements, but inside the function nested inside this.each(), it may still need to reference the jQuery object. By setting var self = this; in the outer function, the inner function can then use self to get to that jQuery object. BTW, there's nothing special about the name self - any variable name could be used instead. I know that's a lot to chew on (or should I say this is a lot to chew on!), so feel free to follow up with any other questions... -Mike From: Simon Corless Hi, I am new to jQuery and have just started working with it, got to say it's brilliant! However I have had a bit of trouble getting my head around the tutorials especially when it comes to making a plugin. It doesn't help having only a basic understanding of Javascript! Anyway I cracked most of it today, but I still don't understand the significance of the subject aka: //return this.each(function() { this.html(); this.hover(pause,resume); //}); Now the above works without the return this.each so what exactly does it do, I have yet to find a clear explanation! (Ignore the script itself there's more too it. Basically it creates a news ticker (fading out each item then fading in a new one) so it's only used one call per page). Also is the 'this' keyword gloabl? or am I right to set my own variable var self = this;? ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] [Fwd: jquery bug 164] (explanation)
To answer my own thought, I remembered it's a problem with the way many external COM controls work because they're not native Javascript objects. This post explains the situation a bit: http://blogs.msdn.com/ericlippert/archive/2004/09/20/231852.aspx Although IE cooperates with Javascript, it seems like MSXML does not. As a result, Javascript ends up trying to call the method rather than just seeing if it exists. Hmm... That's not what Eric's blog post says: - - - - - So here's what happens when you say foo = document.write; First, JScript attempts to resolve document. It can't find a local or global variable called that, so it asks the global window object for the document property. IE gives back the document object. JScript then asks the document object to give back the value of the write property. IE creates an object which has a default method. The default method calls the write function, but no one calls the method yet -- we just have an object which, when invoked, will call the mehtod. JScript assigns the object to foo. Then when you call foo(hello); JScript invokes the default method on the object, which calls the write method. The WSH object model was not designed with this in mind. It does not make a distinction between naming a function and calling it, so you can't use this trick. WScript.Echo; does not give back a function object that can be invoked later. - - - - - In other words, in *WSH* you can't just take a reference to a function like WScript.Echo without actually calling it. But IE creates a shim object just for this purpose - so you can save a reference to document.write and similar methods without calling them. The take-away for jQuery: When checking for a method in a non-native COM object (MSXML, XMLHTTPRequest, others?) use typeof(x.method)==undefined and not x.method==undefined . In a quick search I didn't find any other cases of this in jQuery.js, as long as you don't jQuery.extend() a non-native COM object--and you shouldn't! I wasn't following the discussion, so I'm not saying your conclusion isn't valid - just that Eric's article doesn't seem to indicate that this would be required. Perhaps this case is different from the document.write example he gave? -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] moddify the title tag
humpf, I don't understand why I can't modify the title tag with jquery... I want to input some data after its loaded. For example, $(title).append(test); How come this does not work? You can't change the title tag's innerHTML once the tag has been encountered in the HTML code. This isn't a jQuery limitation; it's a browser limitation. I don't know if it is true for every browser, but it is for the ones I tested when I implemented dynamic titles a while ago. If you want a title programmed from JavaScript, you have to do it differently. Remove the title tag from the document entirely, and replace it with a document.writeln that writes out the title tag you want. You get only one chance at this - you can't change it once the tag is written. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] moddify the title tag
You can't change the title tag's innerHTML once the tag has been encountered in the HTML code. This isn't a jQuery limitation; it's a browser limitation. I don't know if it is true for every browser, but it is for the ones I tested when I implemented dynamic titles a while ago. From: Klaus Hartl innerHTML won't work, just use document.title = 'foo'; :-) From: Mike Alsup You can do this in FF and IE: document.title = 'my new title'; Ah, call me stupid. Sorry about the misinformation. I should know better than to post before I've had breakfast! :-) I wasn't completely dreaming! The situation I was talking about was one where I had needed to use document.writeln in the HEAD for other reasons, and I found when I attempted to write a title tag to a document that already had one it didn't work. The browser only used the first title tag and ignored the second. But of course you can use document.title once the DOM is ready... -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] performance optimizations?
1) Where can I find a searchable archive of this mailing list, because I'd hate to ask questions that have already been answered. Here are a couple: http://www.google.com/search?q=site:jquery.com+optimize+OR+optimization http://www.nabble.com/JQuery-f15494.html 2) I'm getting about a 1.5 second pause when the page loads up, even when on my local system, which appears to be when my jquery commands execute. It's just a little too long, my client noticed right away. Are there any tricks to help this out? For example is it better to use xpath or css type searches for better performance? It's better to not do the searches at all - or rather do them only once. I see a lot of code where the same jQuery expression is repeated over and over again - whether it's inside a loop or simply repeated in the code. Instead of: $('.foo').something(); // other code here $('.foo').somethingElse(); // how about a loop for( var i = 0; i 42; i++ ) { $('.foo').andSomethingElse(); } Write: var $foo = $('.foo'); $foo.something(); // other code here $foo.somethingElse(); // how about a loop for( var i = 0; i 42; i++ ) { $foo.andSomethingElse(); } That code will be a LOT fater than the first. I like to use the $ prefix on the variable name when I save a reference to a jQuery object - it makes the code still look like jQuery code to me. :-) For a single element, it can be useful to save references to both the jQuery object and the underlying DOM element. I like to use the same variable name for both, with the $ prefix on the jQuery object. This makes it easy to see their relation in the code: var $moo = $('#moo'), moo = $moo[0]; $moo.jQueryMethod(); moo.domMethod(); I know this is a pretty open ended question please let me know if I can help clarify it. If I can get this performance thing fixed up a bit I hope some of my plugins can be useful to the community. If you're going to be releasing your code anyway, just post it somewhere and we can all take a look at it. Otherwise you'll just get general suggestions like these. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] jQuery and OOP
Do you really need an object at all? This (pun intended) would do the same thing as all the code you listed: $(function() { var $btn = $('#btnCounter'), nr = 0; $btn.click( function() { $btn.attr( 'value', nr++ ); }); }); -Mike From: Kolman Nándor I am new to jQuery, and I have a question concerning object oriented programming. I have created a sample scenario. In the HTML code I add a button: input type=button value=Count id=btnCounter / In js, I create a class called Counter. In the constructor I add an event handler to the click event of the button. The function I specify as the handler is a method of the Counter class. I also store the button and the nr (the current value of the counter) as an object property. function Counter() { $('#btnCounter').click(this.count); this.button = $('#btnCounter'); this.nr = 0; } In the count method I set the incremented value of the counter to the text of the button. Counter.prototype = { count: function() { this.button.attr('value', this.nr++); } } And I need to create the object in the load event: $(window).load(function() { new Counter(); }); If I try to run the code I get: 'this.button has no properties'. I know that the 'this' in the count method will be the target of the event (the button). But that is not what I need, it is the reference of the Counter object. If I rewrite the constructor I can make it work: function Counter() { var oThis = this; $('#btnCounter').click( function() { oThis.count(); } ); this.button = $('#btnCounter'); this.nr = 0; } But this is quite ugly :(. Is there a nicer way to achieve this? ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] triggering an event
I was wondering having done: $(.foo).click(function (e) {alert (foo);}); Can I force the click event to fire manually, or do I resort to var x = function (e) {alert (foo);} $(#foo).click(x); ele = $(#foo).get(0) x.call( ele, {target:ele}); You can use either of these (they do the same thing): $(#foo).click(); $(#foo).trigger(click); -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Is there a way to dynamically load jquery plugins
From: Klaus Hartl Just wanted to note, that dynamic script elements are not supported in Safari 2.0. Support for that was added in Safari 2.01. Hmm... It works in older versions of Safari. I just tested it in 1.2. Are you saying the support was removed (or broken) in 2.0 and put back in with 2.01? Don't know about document.write... I don't think there's a browser out there that supports JavaScript but does not support document.write - with the exception of modern browsers when rendering a page with the text/xml MIME type. Then the XML parser is used and document.write is not allowed. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Off topic : javascript css
$(function(){ $('head').append('link rel=stylesheet href=jquery.css type=text/css'); }); That's pretty dangerous. The CSS file will load asynchronously, and you won't know when it's done. In the meantime, any content in the page may render unstyled. You are likely to get a flash of unstyled content which is then reformatted when your CSS file finishes loading. If you want to load CSS dynamically, it's much better to do it with document.writeln from code running in the document HEAD: document.writeln( 'link rel=stylesheet href=jquery.css type=text/css' ); This way the CSS file behaves just like any other CSS file loaded directly from HEAD: no content will be rendered until the CSS is ready. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Is there a way to dynamically load jquery plugins
I would like to be able to load my jquery plugins dynamically as this would reduce the number of scripts in my document head. You can easily load any .js file dynamically, for example with code like this: function addScript( url ) { var script = document.createElement( 'script' ); script.type = 'text/javascript'; script.charset = 'utf-8'; script.src = url; document.getElementsByTagName('head')[0].appendChild( script ); }; That's just basic JavaScript code that doesn't require jQuery or anything. Or, using jQuery and my DOM plugin, you could do this: function addScript( url ) { $('head',document).append( $.SCRIPT({ type:'text/javascript', charset:'utf-8', src:url }) ); }; There are other similar ways of doing this as well. However, it may or may not be a good idea. Loading your plugin scripts dynamically will reduce the number of files loaded in HEAD, but the overall load time won't be any better. Loading a number of different scripts will take time however you do it. In many cases, a better approach is to simply concatenate your scripts into a single file. You don't increase the overall download size at all this way, but you can greatly reduce the *number* of scripts that are loaded. The Dojo Toolkit folks have a lot of experience with this. Dojo will load any number of scripts dynamically, but to gain performance, you create a build which is simply a single .js file containing all of the Dojo scripts you are using. It makes a big improvement in page load time. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Expressions: Search for children within context
how do I search for a children within a context? In other words, how to translate this: $(context).children(dt)... into something like this: $(/dt, context) The latter one does unfortuanetely not work... I'm confused - could you give an example with some HTML code and show exactly what result you're looking for? My first reaction would be to use $( 'dt', context ) to get all DT elements within the context element. But are you looking for first-level children only instead of all DT elements, or something like that? -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] method/plugin for getting query string vars?
In Jörn's version of the code, you wouldn't call $.query() at all. Instead, $.query would be the resulting object that you would then use directly. Note that jQuery and $ are references to the same object, so jQuery.query and $.query are the same thing. I'm not sure I like this idea since it means the query parsing would be done whether you need it or not. But maybe it doesn't take enough time to worry about. If it does run all the time, it would be worth optimizing the code by using a conventional for loop instead of jQuery.each and combining the repeated split calls. I'd also remove the code that does the float conversion and ignores empty values. Consider this URL: http://www.example.com/test?special=zip=00125 I may want to know about that special parameter, and I probably don't want the Zip code turned into the number 125. Here's how I would code it... For the jQuery.query is an object version: (function() { var r = jQuery.query = {}; var params = location.search.replace(/^\?/,'').split(''); for( var i = params.length-1; i = 0; i-- ) { var p = params[i].split('='), key = p[0]; if( key ) r[key] = p[1]; } })(); For the jQuery.query is a function: jQuery.query = function() { var r = {}; var params = location.search.replace(/^\?/,'').split(''); for( var i = params.length-1; i = 0; i-- ) { var p = params[i].split('='), key = p[0]; if( key ) r[key] = p[1]; } return r; }; All untested, of course. :-) -Mike From: Stephen Woodbridge I seem to be missing something (so much to learn!). Your note creates an anonymous function that assigns its result to jQuery.query, but where does the function get attached and how does it get invoked, like in Luke's example. Jörn Zaefferer wrote: In that case, you should just assign the result to jQuery.query, eg: (function() { jQuery.query = r = {}; var q = location.search; q = q.replace(/^\?/,''); // remove the leading ? q = q.replace(/\$/,''); // remove the trailing jQuery.each(q.split(''), function(){ var key = this.split('=')[0]; var val = this.split('=')[1]; // convert floats if(/^[0-9.]+$/.test(val)) val = parseFloat(val); // ingnore empty values if(val) r[key] = val; }); })(); Considering that location.search does not change. I hope I'm not confusing something. ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Bug in Firefox with e.target?
From: Klaus Hartl I wanted to add the normalization for e.target as discussed earlier. But I came across a strange bug in Firefox. Have a look at the following page: http://stilbuero.de/demo/jquery/etarget.html If you click on the link the target of the click event (attached to p) is alerted. In that case it is an strong element, but Firefox reports an HTMLSpanElement. Safari is ok. Does anyone know what is going on? Firefox has the correct strong element there, it's just the way it reports it when you do an alert. Forget the event handling for the moment and try these in the FireBug console: $('strong')[0] $('strong')[0].tagName alert( $('strong')[0] ) alert( $('strong')[0].tagName ) -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] jquery snapshots
Use the SVN version if you want to do that sort of thing. http://jquery.com/src/ - Shows you the SVN access address. AFAIK this has to be built first before it is usable. I am looking for readily built snapshot. No, it doesn't have to be built. The svn code is usable right out of the box. The only difference is that it's bigger because it isn't packed and still has all the comments, and it comes in separate files (jquery.js, event.js, etc.) instead of one concatenated file. For development and testing it works fine. -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] Using javascript variable for HASH
I imagine that it must be some way to use javascript variable for HASH... Is it possible? I show you the code that I'm using (and it show me an error in FireBug (Firefox):reference to undefined property imts): function LoadAjax(t,d,id){ var itms itms='{url: GetValues'+t+'.asp, type: POST, '; itms+='data: '+d+''; itms+='success: function(req) {AjaxOk(req,'+id+');},'; imts+='error: AjaxError}'; $.ajax(itms); } It looks like this is what you are trying to do: function LoadAjax( t, d, id ) { var itms = { url: 'GetValues' + t + '.asp', type: 'POST', data: d, success: function( req ) { AjaxOk( req, id ); }, error: AjaxError }; $.ajax( itms ); } -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/
Re: [jQuery] ThickBox in Filemanager
Well, as I've already said, you won't be able to show the PDF in a thickbox, because the OS/browser will catch the link and try to open it using the default action set in the browser or OS, and there's nothing that you can do to override it. If no default action is set, then you -might- be able to open it in the browser. But let's be honest, the percentage of users without a PDF reader is pretty small (probably the same percentage as those browsing the web on an Amiga 1200. :-) As far as I know, there is no ability to read PDF's inline like you're trying to do, and trying to force PDFs to open in a small window just isn't practical, and users won't like it if you force it upon them. If you can load HTML into the thickbox, you can easily load a PDF file. Simply use an iframe or object tag. For some examples: http://www.google.com/search?num=100q=pdf+iframe http://www.google.com/search?num=100q=pdf+%22object+tag%22 -Mike ___ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/