Re: [jQuery] Re: A different approach to parsing XML, and a little help on processing attributes more efficiently
No worries on the XML vs. JSON. It's been interesting to watch your progress in refactoring the code. I hope it's useful for other people too. A few notes on the latest version... * Avoid using ALLCAPS or PARTIALcaps in a variable name. Many JavaScript programmers will think you intend such variables to be used as constants. (That is, a variable whose content is not intended to be changed.) * You don't need all those makeArray calls. * It's a bit confusing to mix the use of $ and jQuery in the same code. Use one or the other consistently. * Stop appending to $('div') Very bad habit! What happens when you add another DIV to your page? Use a $('#container') selector instead. * Even though you're still doing XML parsing, you will get much faster performance by building an HTML string, and make sure the entire HTML content is enclosed in one wrapper DIV. * Watch out for all the duplicate $(something) selectors. If you use the same $(something) more than once, than do this instead: var $something = $(something); $something.whatever(); // instead of $(something).whatever(); Putting those tips together, you get something like this: function parseXml( xml ) { var html = []; html.push( 'div' ); $(xml).find('sites').each( function() { $(this).find('element').each( function( i, parent ) { var $parent = $(parent); html.push( 'br/', $parent.attr('label'), i + 1, 'br/' ); $parent.find('element').each( function( j, child ) { var $child = $(child); html.push( $child.attr('label'), 'br/' ); $child.find('element').each( function( k, inner ) { var $inner = $(inner); html.push( $inner.attr('label'), ': ', $inner.text(), 'br/' ); }); }); }); }); html.push( '/div' ); $('#container').append( html.join('') ); } -Mike On Tue, Feb 2, 2010 at 4:10 PM, augur 312...@gmail.com wrote: function parseXml(xml) { $(xml).find('sites').each(function(){ var PARENTarr = jQuery.makeArray($(this).find('element')); $(PARENTarr).each(function(i){ $(div).append(br/+ $(this).attr(label)+(i+1) +br/); var CHILDarr = jQuery.makeArray($(PARENTarr[i]).find ('element')); $(CHILDarr).each(function(p){ $(div).append($(this).attr(label) +br/); var CHILDattrs = jQuery.makeArray($(CHILDarr[p]).find ('element')); $(CHILDattrs).each(function(){ var CHILDid = $(this).attr('label') +: + $(this).text(); $(div).append(CHILDid +br/); p=0; }); }); }); }); } });
Re: [jQuery] Re: A different approach to parsing XML, and a little help on processing attributes more efficiently
Cool, it will be good to see your continued work. We may be among the last holdouts in this mailing list - but I figure since the thread started here we can carry on. BTW you may notice one bit of annoying repeated boilerplate in that last version. See how the callback functions for all the .each() loops begin with something like: var $foobar = $(foobar); Why don't we extend jQuery with a better version of .each() that does that for us? Let's call it .$each() as a reminder that it gives the callback a DOM element that's already been wrapped with a $(). It would look like this: jQuery.fn.$each = function( callback ) { for( var element, i = -1; element = this[++i]; ) callback( jQuery(element), i ); }; Note that in addition to calling jQuery(element), it also reverses the callback arguments - in most cases you only need the element inside the callback - it's much less often that you need the index. (In your code, only one of the four loops uses the index.) So, using that function, the code can be written as: function parseXml( xml ) { var html = []; html.push( 'div' ); $(xml).find('sites').$each( function( $site ) { $site.find('element').$each( function( $parent, i ) { html.push( 'br/', $parent.attr('label'), i + 1, 'br/' ); $parent.find('element').$each( function( $child ) { html.push( $child.attr('label'), 'br/' ); $child.find('element').$each( function( $inner ) { html.push( $inner.attr('label'), ': ', $inner.text(), 'br/' ); }); }); }); }); html.push( '/div' ); $('#container').append( html.join('') ); } That's getting pretty clean! Note that the code still uses the naming convention of $foobar for a jQuery object - it helps make it clear which variables are jQuery objects. -Mike On Tue, Feb 2, 2010 at 10:27 PM, augur 312...@gmail.com wrote: OK, so this is much better than a lesson in parsing XML. Showing the errors that I had made in my process, you have also shown sound jQuery which I was having a hard time picking up from the documentation. I tend to learn best by doing and getting feedback. Mike, thank you. I am going to keep this chain going with my mods as I make them.
Re: [jQuery] Re: A different approach to parsing XML, and a little help on processing attributes more efficiently
I don't know why Google Groups keeps inserting those semi-random blank lines in the code! Now I'm curious, so I'm trying something a bit different - let's see what happens.. function parseXml( xml ) { var html = []; html.push( 'div' ); $(xml).find('sites').$each( function( $site ) { $site.find('element').$each( function( $parent, i ) { html.push( 'br/', $parent.attr('label'), i + 1, 'br/' ); $parent.find('element').$each( function( $child ) { html.push( $child.attr('label'), 'br/' ); $child.find('element').$each( function( $inner ) { html.push( $inner.attr('label'), ': ', $inner.text(), 'br/' ); }); }); }); }); html.push( '/div' ); $('#container').append( html.join('') ); } On Tue, Feb 2, 2010 at 10:54 PM, Michael Geary m...@mg.to wrote: Cool, it will be good to see your continued work. We may be among the last holdouts in this mailing list - but I figure since the thread started here we can carry on. BTW you may notice one bit of annoying repeated boilerplate in that last version. See how the callback functions for all the .each() loops begin with something like: var $foobar = $(foobar); Why don't we extend jQuery with a better version of .each() that does that for us? Let's call it .$each() as a reminder that it gives the callback a DOM element that's already been wrapped with a $(). It would look like this: jQuery.fn.$each = function( callback ) { for( var element, i = -1; element = this[++i]; ) callback( jQuery(element), i ); }; Note that in addition to calling jQuery(element), it also reverses the callback arguments - in most cases you only need the element inside the callback - it's much less often that you need the index. (In your code, only one of the four loops uses the index.) So, using that function, the code can be written as: function parseXml( xml ) { var html = []; html.push( 'div' ); $(xml).find('sites').$each( function( $site ) { $site.find('element').$each( function( $parent, i ) { html.push( 'br/', $parent.attr('label'), i + 1, 'br/' ); $parent.find('element').$each( function( $child ) { html.push( $child.attr('label'), 'br/' ); $child.find('element').$each( function( $inner ) { html.push( $inner.attr('label'), ': ', $inner.text(), 'br/' ); }); }); }); }); html.push( '/div' ); $('#container').append( html.join('') ); } That's getting pretty clean! Note that the code still uses the naming convention of $foobar for a jQuery object - it helps make it clear which variables are jQuery objects. -Mike On Tue, Feb 2, 2010 at 10:27 PM, augur 312...@gmail.com wrote: OK, so this is much better than a lesson in parsing XML. Showing the errors that I had made in my process, you have also shown sound jQuery which I was having a hard time picking up from the documentation. I tend to learn best by doing and getting feedback. Mike, thank you. I am going to keep this chain going with my mods as I make them.
Re: [jQuery] A different approach to parsing XML, and a little help on processing attributes more efficiently
Are you required to use XML? Why not use JSON and avoid all the parsing? If you have to use XML I can make some suggestions to speed up the code a bit. But let's see if that is a requirement or not first. -Mike On Thu, Jan 28, 2010 at 10:32 AM, augur 312...@gmail.com wrote: I spent a couple days looking all over the web for how to do this well. I did some picking and choosing of methods, and I came up with this. It works best in Safari, then FireFox, and then Chrome. I have not tested in IE (do I have to?). It runs up to just over 20,000 lines of XML well, over that memory is working too hard. It is a very linear parser that descends from parent to child nodes as it goes. I commented my code heavily so that it should be pretty understandable. The one place that I could be a bit more efficient is in the processing of the node attributes at each level. I would like to parse out node attributes without specifying them (label and id are pretty acceptable I guess), so any suggestions there would be great. :The FrameWork:: jquery-1.4.min.js :The code $(function(){ $.ajax({ type: GET, url: sites.xml, dataType: xml, success: parseXml }); function parseXml(xml) { //get root element // $(xml).find('sites').each(function(){ //get descentdent element = element/element // $(this).find('element').each(function(){ //set variable as this item to pass to the next function // var PARENT = $(this); //get a bunch of attributes of the PARENT element. THIS COULD BE MORE EFFICIENT // parentLabel = $(this).attr('label'); parentID = $(this).attr('id'); siteLAT = $(this).attr('lat'); siteLNG = $(this).attr('lng'); //set variable as string of PARENT variables// var parentBLOCK = br/ +parentLabel + + parentID + br/; //set variable to post parentBLOCK// var siteBLOCK = $(div).append(parentBLOCK); //get descentdent element of PARENT // $(PARENT).find('element').each(function(){ //set variable as this item to pass to the next function // var THISis = $(this); //get attributes of the THISis element. THIS COULD BE MORE EFFICIENT // thisLabel = $(this).attr('label'); //set variable as string of THISis variables// var thisBLOCK = thisLabel +: Has this latitude + siteLAT + this Longitude +siteLNG; //set variable to post thisBLOCK// siteBLOCK = $(div).append(thisBLOCK + br/); //get descentdent element = THISis// $(THISis).find('element').each(function(){ //get a bunch of attributes of the child elements. THIS COULD BE MORE EFFICIENT // childLabel = $(this).attr('label'); //get text from nodes of THISis chlidren elements // childCopy = $(this).text(); //set variable as string of THISis child variables// var childBLOCK = childLabel + : + childCopy + br/; //set variable to post childBLOCK// siteBLOCK = $(div).append(childBLOCK); }); }); }); }); } }); :The XML ?xml version=1.0 encoding=UTF-8? sites element label=site id=1 lat=66 lng=104 element label=Location element label=citySF/element element label=stateCA/element element label=regionWest Coast/element /element /element element label=site id=2 lat=27 lng=305 element label=Location element label=cityLas Vegas/element element label=stateNV/element element label=regionWest/element /element /element element label=site id=3 lat=106 lng=35 element
Re: [jQuery] Re: A different approach to parsing XML, and a little help on processing attributes more efficiently
No offense, but that code is really frightening. Not your fault though. JSON is not only much faster than all this XML/DOM garbage, but it is *much* easier to understand and use too! If you're coding JavaScript, you need to know how to use ordinary JavaScript objects and arrays, yes? If you know how to work with those, then you *already know JSON*. Because JSON is just JavaScript objects. (D'oh! JavaScript Object Notation!) So here's your XML file transcribed fairly faithfully into JSON: { sites: [ { label: site, id: 2, lat: 27, lng: 305, location: { city: Las Vegas, state: NV, region: West } }, { label: site, id: 3, lat: 106, lng: 35, location: { city: Pittsburgh, state: Penn, region: North East } } ] } I only included a couple of the entries to keep the example short. As you can see, that's just a JavaScript object. This JavaScript object contains a single property called 'sites'. That property is an array of objects, each one representing a single site. Those site objects have the same properties as your XML file. So here's how you use it. I didn't try to exactly duplicate what your code is doing - I wasn't sure what it was trying to do with all the $('div') calls. Wouldn't those append to every DIV in your page? Oh - is there only a single DIV that you're appending everything to? You should give it an ID and reference it that way instead. Also I realized I didn't quite duplicate what you're doing with those label=Location elements. It looks like you might have other kinds of label=Something elements as well? I didn't notice that, but tell you what, here's the code as I understood it: $.getJSON( 'sites.json', function( json ) { var html = []; html.push( 'div' ); var sites = json.sites; for( var site, i = -1; site = sites[++i]; ) { var location = site.location; html.push( site.label, ' ', site.id, 'br/', 'Lat: ', site.lat, ' Lng: ', site.lng, 'br/', location.city, ', ', location.state, 'br/', location.region ); } html.push( '/div' ); $('#container').html( html.join('') ); }); As you can see, that is many times simpler - and *much* easier to understand - than the XML parsing. Some other speed notes... * The for loop uses a slightly unusual form that is faster than the usual numeric incrementing. * Instead of appending elements to the HTML DOM as we go, we construct a single HTML string and append it in one operation. * That HTML string has an outermost DIV that wraps all the elements inside it. * We construct the HTML string not with += but by pushing the elements onto an array and joining it at the end. There is actually a way to speed this up a slight bit more in IE, but let's leave that for the next installment. :-) As it is now, this code will be many times faster than the XML code - at least one order of magnitude faster, and maybe two. Let me know what the real deal is with those label=location elements and I can suggest how to handle them. -Mike On Thu, Jan 28, 2010 at 11:31 AM, augur 312...@gmail.com wrote: Funny thing is, my lead engineer said the same thing... Mostly this was an experiment to gain a better understanding of DOM outside of HTML. This is about as exciting as a SAX parser when it comes to speed (5sec in safari for 20K lines, slightly longer in FireFox, and noticeably longer in Chrome), though it is fairly efficient, and gives me exactly the results I was wanting to see. There are some practical applications. Realizing that there is only so much memory out there more efficiency is what I am going for, so any input on this script is helpful. I have approached it this way because I get XML and DOM, and I am getting decent at jQuery. Thus this method was in my range of current understanding. JSON is something that I am just now becoming more familiar with.
Re: [jQuery] how to get href value
But that would give you the href for the first A element in the document, not necessarily the one you clicked. Going back to the OP's code, this.href would be the easiest way to get it: $(document).ready(function() { $(a).click(function(event) { alert( You clicked http://jquery.com/a link to + this.href ); return false; }); }); -Mike On Tue, Jan 19, 2010 at 9:14 PM, Matt Quackenbush quackfu...@gmail.comwrote: $(a).attr(href);
Re: [jQuery] Passing in a parameter
If your current code in the body tag is literally: onload=getStuff(data) then 'data' must be a global variable. You can reference this global variable directly in any of your JavaScript code. For example: $(document).ready( function() { getStuff( data ); }); If that's not exactly what your code looks like, give a more specific example and it will be easy to come up with some suggestions. -Mike On Sat, Jan 16, 2010 at 8:57 PM, Patrick kenned...@gmail.com wrote: Hi all, I have a newbie question. You know how you can pass a variable to a JavaScript function like this: onload=getStuff(data) Which is done via the BODY tag. Now, jQuery uses $(document).ready (function() }); My problem is simple: I want to pass in a variable to the ready (function(). When the page is first loaded, how can I pass in a variable to this function, or what strategy should I imploy to do such? Thanks for the pointers. Pat
Re: [jQuery] jQuery 1.4 cross domain post bug?
You can't do a cross-domain POST, nor a cross-domain GET either. It doesn't matter what kind of data it returns, you can't do a POST at all. It's not a jQuery limitation; the browser won't allow it for any JavaScript code. Cross-domain JSONP works because it uses a dynamic script element, not a GET or POST. -Mike On Fri, Jan 15, 2010 at 5:14 PM, David P dpio...@gmail.com wrote: I have a webservice sitting on my https server that accepts the POST verb and responds with some JSON. If I build a simple html form like form method=post action=https://myserver.com/myWS; input type=submit/ input type=hidden name=emailAddress value=a...@a.com / input type=hidden name=password value=uk / /form it will return the correct json data, with content type application/ json, and the browser will ask to save the result. When I look at the data it is 100% correct if I try to access it with jquery using $.post(https://myserver.com/myWS;, { emailAddress: a...@a.com, password: uk }, function(data) { alert(hi!); }, json); the call back will never execute. When I check firebug, in the net panel, I can see the call go out (first the OPTIONS call which completes successfully, then the POST) however I cannot view the actual results. In the Console panel, the call is in red so firebug thinks there is some kind of error. Is there something I'm missing with how to handle cross domain POSTs that return json data?
Re: [jQuery] Actually deleting instead of .remove
.remove() does remove the element from the document head or body, but that doesn't destroy it. It just makes it available for garbage collection - if there are no other references to the element. For example: var $div = $('divtest/div'); $div.appendTo('body'); $div.remove(); Here we've created a new DIV element, appended it to the body, and then removed it. It is no longer a part of the document body. But the element still exists in memory! After all, somewhere later we may repeat this code: $div.appendTo('body'); // re-use the same DIV Jeff, perhaps there are other references outstanding to the elements that are being .remove()'d, preventing them from being garbage collected. -Mike On Wed, Jan 13, 2010 at 8:46 AM, Karl Swedberg k...@englishrules.comwrote: Hmm. .remove() doesn't just hide an element; It removes it: if ( this.parentNode ) { this.parentNode.removeChild( this ); } (from the source) To prevent memory leaks, it also removes event handlers associated with it. As of jQuery 1.4, it also removes data associated with it. Maybe something else is going on? Or maybe something isn't being caught. In any case, it might help to see a test case that shows the memory leak. If you can reproduce the problem with a minimal test case and post it publicly, send a note to the jquery-dev google group so the devs can have a look. thanks, --Karl Karl Swedberg www.englishrules.com www.learningjquery.com On Jan 12, 2010, at 6:52 PM, sophos707 wrote: Hi everyone, I'm running a script that processes text messages people send in, and then it displays them on a screen. It will loop the text messages when there are too many to show on one screen. To accomplish this I add DIVs with a new ID for each new message. The new messages push the old ones off the screen eventually. But when this is the case the memory in the browser just keeps increasing to a frightening load! I tried using $(#MyDivId).remove() to get rid of the DIVs no longer on the screen. Memory keeps increasing. Found out in this forum that .remove() just hides an element in the DOM and makes in inaccessible rather than actually deleting it. How can we actually delete elements? Thanks! - Jeff
Re: [jQuery] javascript loaded via ajax
Removing a script element just removes the script's *source code* from the DOM. It doesn't undo any actions that the script has already performed, such as defining functions or variables or creating other DOM elements. It doesn't change their availability for garbage collection at all. In your example, the hello function will never be garbage collected, because the window object has a property named 'hello' that holds a reference to the function. As Ami mentioned you can null out that window.hello property or use the delete operator on it, or better, use the (function() { /* code here */ })(); wrapper to avoid setting global properties. -Mike On Wed, Jan 13, 2010 at 2:40 PM, Nathan Klatt n8kl...@gmail.com wrote: On Wed, Jan 13, 2010 at 1:53 PM, nihal nihal.c...@gmail.com wrote: is there anyway to remove the newly added function from the dom? Wrap the code you want to be removeable in its own script element, give it an id, then remove it just like any other element. As has been discussed today, removing it doesn't mean *poof* it's gone, just that it could be removed by the garbage collector, so you'll likely be able to continue calling the function after it's been removed. See: http://jsbin.com/ixite/edit script id=removeMe type=text/javascript function hello(msg) { alert(msg); } /script script type=text/javascript $().ready(function() { hello(one); $(#removeMe).remove(); hello(two); setTimeout(hello('three'), 2500); }); /script The code gets removed from the DOM (verified using Firebug) but the function still works 2.5 seconds later. Nathan
Re: [jQuery] Re: Ajax forms help
The JSON part of your server response looks fine if you take out the two line breaks - I assume those are just an artifact of posting with Outlook, and your actual JSON response is all on one line. But why does it have the HTML content repeated after the last } that closes the JSON data? You don't want that. Also: Is response.html saying to display it as html? No! response.html says take the object named 'response' and give me its property named 'html'. It has nothing to do with displaying anything or specifying its format. Here, let's take your JSON output and paste it into www.jsonlint.com so it's easier to read: { data: { title: , year_rec: { year: 2010 }, description: , id: 0936d6115e4, profile_id: 4b40eea7-2608-4a3b-9c24-7cb04adcd75b }, status: true, html: pthis is a good test\/p\r\n } You see, it's an object with three properties, named 'data', 'status', and 'html'. The 'data' property is itself an object with properties of its own. So if you have a variable named 'response' (as in Ibatex's example), then you can get to these various properties like so: response.html (the HTML code) response.data.id (the id) response.data.year_rec.year (the year) What you do with those is then up to you, as in Ibatex's earlier example. BTW do you have the Fiddler debugging proxy server and its JSON plugin (and standalone JSON viewer)? For the work you're doing now, you *need* these. http://www.fiddler2.com/ http://www.fiddler2.com/Fiddler2/extensions.asp -Mike On Mon, Jan 11, 2010 at 11:41 AM, Dave Maharaj :: WidePixels.com d...@widepixels.com wrote: My response comes back from the server looking like this: (don’t think its right to begin with) {data:{title:,year_rec:{year:2010},description:,id:0936d6 115e4,profile_id:4b40eea7-2608-4a3b-9c24-7cb04adcd75b},status:true,h tml:pthis is a good test\/p\r\n}pthis is a good test/p But how would I display only the html section and clean it so its not all slashed and escaped? Thanks Dave -Original Message- From: MorningZ [mailto:morni...@gmail.com] Sent: January-11-10 11:44 AM To: jQuery (English) Subject: [jQuery] Re: Ajax forms help But if I am returning json I cant return my normal html I don't understand why... I pretty much exclusively use JSON back and forth in my jQuery AJAX calls and have a standard JSON object i return: { HasError: boolean, Message: string. Data: object, Count: integer } Many times i'll return HTML on the data property there i think the problem you are having is how you are creating the JSON return string, maybe that's not the right way to do it in PHP ?? (to note, i'm a .NET guy, i don't know what the PHP way is) On Jan 11, 10:06 am, Dave Maharaj :: WidePixels.com d...@widepixels.com wrote: Right on...looks easy enough. Is response.html saying to display it as html? I tried making an array to pass as json from php then json_encode it so my arrr was $response = array('status' = true , 'view' = 'all my html code went here') But when I returned my view data from the array it was all slahsed // // / / / like that. -Original Message- From: Ibatex [mailto:mjgris...@gmail.com] Sent: January-11-10 4:35 AM To: jQuery (English) Subject: [jQuery] Re: Ajax forms help The beauty of json is that you can transfer alot of different data in an organized way. You can very easily send back success/failure status along with the html. success: function(response) { // Response was a success if (response.status) { //update my target div $('#target_div').html(response.html); // Response contains errors } else { // return the form with the errors } On Jan 10, 5:00 pm, Dave Maharaj :: WidePixels.com d...@widepixels.com wrote: I need some help with a form. I submit the form fine, my problem is depending on the success or failure of the form being saved. I will try to explain as simple as possible form is in its own div form here . div target saved data will appear here/div So what I need is i guess json success true or false response from the form being saved or not then in my success success: function(response) { // Response was a success if (response) { //update my target div // Response contains errors } else { // return the form with the errors } But if I am returning json I cant return my normal html after the successful save, and if I return my response as html there is no way
Re: [jQuery] Accessing REST API via JQUERY?
The remote XML API is not on the same domain as your page, is it? Then you can't do it. Browser cross-domain restrictions will not permit it. The only reason you can use getJSON for cross-domain requests is that it actually downloads executable JavaScript code with a dynamic script element, i.e. the JSONP format - and that only works with servers that support JSONP. To use an XML REST API from another domain in your JavaScript code, you will need to put a proxy of some sort on your server, so that you can make the request to your own domain. This can be as simple as a few lines of PHP code - search for something like php proxy for some examples. -Mike On Mon, Jan 4, 2010 at 1:06 PM, Simon simon@rewardstream.com wrote: Hi there. I'd like to use jQuery to access a remote website that has a REST API which returns XML data. Should I be able to use the jQuery.getJSON request to do it or is there another command since it's returning XML. Example Request Details (HTTP GET): https://{username}:{passwo...@api.opsourcecloud.net/oec/0.9/myaccounthttp://username%7D:%7bpassword...@api.opsourcecloud.net/oec/0.9/myaccount Example Response Details: ?xml version=1.0 encoding=UTF-8 standalone=yes? ns3:Account xmlns:ns2=http://oec.api.opsource.net/schemas/ organization .. ns3:userNamerdyer/ns3:userName ns3:fullNameJoe Public/ns3:fullName ns3:firstNameJoe/ns3:firstName ns3:lastNamePublic/ns3:lastName ns3:emailAddressjpublic24...@pop.net/ns3:emailAddress ns3:orgId1831c1a9-9c03-44df-a5a4-f2a4662d6bde/ns3:orgId ns3:roles ns3:role ns3:nameprimary administrator/ns3:name /ns3:role /ns3:roles /ns3:Account
Re: [jQuery] Not working for me in IE7, but works in IE8
If I tell you the (possible) answer, will you turn off the music on the home page? :-) Karl Swedberg mentioned in another thread today that you may have trouble in IE6 if you try to set a background color on a TR. It has to be on the TD's instead. Maybe this is the case for IE7 too. So I would try changing this part of your CSS: tr { background-color: #fff; } .alt { background-color: #B7FFB7 !important; } to: td { background-color: #fff; } .alt td { background-color: #B7FFB7 !important; } -Mike On Fri, Jan 1, 2010 at 11:45 PM, cybervigilante cybervigila...@gmail.comwrote: I just tried a simple alternate colored table rows in jQuery 1.3.2. It works fine in the good browsers, works in IE8, but doesn't in IE7. I thought jQuery worked in IE7. I'm using the IE multitester suite. (It doesn't work in IE6 either, but I stopped thinking about IE6 except in the dead sense ;') Here's the site - it's a table of religious days on the front page. http://celestialchurchqueens.org Here's the code - very basic. The alt class gives a light green color in IE8. I thought maybe my testing suite is off so I'd like to know if anyone else sees a lack of color bands in IE7. jQuery(document).ready(function() { jQuery('tr:odd').addClass('alt'); }); This is a Joomla site, and since Joomla has an ancient version of MooTools embedded, I'm using jQuery instead of $ in compatibility mode.
Re: [jQuery] Not working for me in IE7, but works in IE8
Just to clarify that thought, I really like the music a lot! I just don't like having it start playing automatically when I visit the home page. -Mike On Sat, Jan 2, 2010 at 1:56 AM, Michael Geary m...@mg.to wrote: If I tell you the (possible) answer, will you turn off the music on the home page? :-)
Re: [jQuery] Re: Table striping still not working in IE7
jQuery does have its own selector engine that is used in *jQuery selectors*. However, it does not add any capabilities that are not already there in *CSS selectors*. This is a jQuery selector: $('.foobar').whatever(); This is a CSS selector: style type=text/css .foobar { whatever } /style In your code you are using *CSS selectors*. You're using jQuery to add a class to some elements, and then you are using a CSS selector to do something with that class. In this situation, jQuery doesn't add anything beyond what the native CSS selector engine provides, because the CSS selector is not interpreted by jQuery. Your jQuery code is working fine. If you load your page in IE8, then hit F12 and choose IE7 mode, you'll see that it fails to stripe your table. However, if you then use the DOM inspector in IE8 to look at your table elements, you'll see that they do have the 'alt' class that you're adding. This is all working perfectly. In fact, if you didn't use jQuery at all, but generated the HTML code from your server with the 'alt' class on alternate rows, I'm sure you would see exactly the same result in all browsers that you see now. This suggests another way to approach the problem. For test purposes, don't use jQuery at all. Simply hand-code a simple HTML page that has all of the CSS classes you want to use. Then you can fiddle with your HTML and CSS all you want, without having to worry about whether the problem lies in jQuery or elsewhere. Did you see my reply to your other post, where I mentioned that Karl had pointed out that you can't set the background color of a TR in IE6, but have to set it on the TD elements instead? I wonder if IE7 has the same problem. In any case, that's where you should begin investigating. Along the same lines, if you wonder whether your jQuery code is working as expected, do not rely simply on the visual effect. Use the DOM inspector and see if your DOM elements have the attributes you expect. Then you'll know where to continue troubleshooting. -Mike On Sat, Jan 2, 2010 at 3:14 PM, cybervigilante cybervigila...@gmail.comwrote: On Jan 2, 3:22 pm, audiofreak9 audiofre...@gmail.com wrote: Just an off the hip thought, IE7 may still have the pseudo issues in IE6 and earlier... I thought jQuery had its own model, so it can use stuff that isn't even in IE7, like some CSS3 selectors. Anyway, I can't even seem to get non-pseudo stuff to work. I'm using Joomla, but I don't think it's Joomla since it Does work in IE8
Re: [jQuery] Re: jQuery does not stripe visible table rows correctly
I wouldn't use either version. Instead, I would change your CSS from: tr.rowodd { background-color: #FFF; } tr.roweven { background-color: #F2F2F2; } to: tr { background-color: #FFF; } tr.roweven { background-color: #F2F2F2; } and then use just one line of jQuery code: $('#foobar tr:visible:odd').addClass('roweven'); Now you're doing only half the work and letting the CSS cacading rules take care of the rest. -Mike On Fri, Jan 1, 2010 at 10:38 AM, Paul Kim kimba...@gmail.com wrote: Thanks for your reply. Your solution works. I had a feeling that :even and :odd filters are zero-based, but found that to be odd in this situation. So now that I have 2 ways to stripe visible table rows using jQuery, which solution do you prefer? $('#foobar tbody tr:visible:even').addClass('rowodd'); $('#foobar tbody tr:visible:odd').addClass('roweven'); or $('#foobar tbody tr:visible').each(function(i) { if ((i+1) % 2 === 0) { $(this).addClass('roweven'); } else { $(this).addClass('rowodd'); } }); I guess both solutions work so it really doesn't matter, but which method would you choose? The first solution contains less code but the second solution seems more intuitive. 2010/1/1 Šime Vidas sime.vi...@gmail.com Also, you really don't need two counters (i and j) var rows = $('#foobar tbody tr:visible'); for (var i = 0; i rows.length; i++){ if ((i + 1) % 2 == 0) { rows.eq(i).addClass('roweven'); } else { rows.eq(i).addClass('rowodd'); } } However, don't use the for loop, you have jQuery's each method... $('#foobar tbody tr:visible').each(function(i) { if ((i+1) % 2 === 0) { $(this).addClass('roweven'); } else { $(this).addClass('rowodd'); } });
Re: [jQuery] Rebinding not working
That .live() code wouldn't work because what you've really written is: var temp = exp_iphone_get_trans(); $('#transactions ul li a').live('click tap', temp); Now you can probably see what the problem is with that. By adding the () after the function name, you are *calling* the function immediately and then passing its *return value* to the .live() method. Note that your other code with .bind() doesn't have the extra () after the callback funciton name. Here's a subtle thing, but I find it very helpful to put whitespace inside the parentheses of a function call. So this line of code: $('#transactions ul li a').live('click tap', exp_iphone_get_trans()); I would have written as: $('#transactions ul li a').live( 'click tap', exp_iphone_get_trans() ); Now it's become a little easier to see those extra () after the callback function name. Another subtle thing, but I also find it helpful to avoid names_with_underscores and instead use camelCaseNames. Why? The underscore is a punctuation mark, and in a language with so much significant punctuation, these extra punctuation marks detract from the meaningful ones. So I might write the code like: $('#transactions ul li a').live( 'click tap', iPhoneGetTrans() ); Now things are stuck together visually for me in a way that better highlights the significant punctuation. For me at least this helps that extra () after the iPhoneGetTrans name stand out, so hopefully I would catch on and correct it to: $('#transactions ul li a').live( 'click tap', iPhoneGetTrans ); -Mike On Sat, Dec 26, 2009 at 1:29 PM, mrtoner d...@donmorris.com wrote: Using jQ 1.3.2; I also tried $('#transactions ul li a').live('click tap', exp_iphone_get_trans()); to no avail. Any suggestions?
Re: [jQuery] Re: js function to jQuery
Unicorns are a mythical creature, and so is that use of parentheses. Could this be the syntax you were looking for? (function() { var $ = window.jQuery; $(#CollapseExpandTd).click( function() { $(#TreeviewTd).toggle(); $(#MenuBarTd).toggle(); }); })(); That puts all the code inside a function, and then immediately calls the function. Now you have all the unicornish magic you were looking for, without the mythical aspects. :-) -Mike On Tue, Dec 22, 2009 at 8:06 PM, Leonardo Balter leonardo.bal...@gmail.comwrote: Nah, make it sexier, use parenteses (tip from the new John Resig's ebook): ( var $ = window.jQuery; $(#CollapseExpandTd).click( function() { $(#TreeviewTd).toggle(); $(#MenuBarTd).toggle(); }); ); $ will be a local variable and unicorns will come to see the magic running around. 2009/12/23 jqHunter tinu.punn...@gmail.com Thanks much Sime Vidas, it worked! Since mine is an aspx with an AJAX UpdatePanel, jQuery(document).ready(function(){...}); did not work for me. So I implented it in the pageLoad as below: jQuery.noConflict(); function pageLoad() { jQuery(#CollapseExpandTd).click(function() { jQuery(#TreeviewTd).toggle(); jQuery(#MenuBarTd).toggle(); }); } Thanks again! -- At, Leo Balter http://leobalter.net Blog técnico: http://blog.leobalter.net
Re: [jQuery] Re: how to access elements with index in for-loop
Don't sweat it, dude. First off, Eric didn't post the comment you're referring to. And if he had, I'd be inclined to cut him some slack. After all, Eric's English is *much* better than my Chinese (or whatever Eric's native language is). Second, we all post something once in a while that offends another list member. I did it myself just yesterday - I offended a valuable contributor without meaning to! (Hi, MorningZ!) As the wise lyricist from High School Musical once wrote, We're all in this together! So have a very merry Christmas, and don't worry when someone writes something that doesn't quite come out the way they intended. :-) -Mike On Wed, Dec 23, 2009 at 7:01 PM, Rick Faircloth r...@whitestonemedia.comwrote: Ø this is a pretty stupid way to loop through a jQuery object Is it necessary to be insulting to be helpful, Eric? What was your code like when you first began to write JS or jQuery? Always perfect and mature, I’m sure… Rick *From:* jquery-en@googlegroups.com [mailto:jquery...@googlegroups.com] *On Behalf Of *Eric Zhong *Sent:* Wednesday, December 23, 2009 9:52 PM *To:* jquery-en@googlegroups.com *Subject:* Re: [jQuery] Re: how to access elements with index in for-loop thank you very much, your way is better than mine ! 2009/12/24 Šime Vidas sime.vi...@gmail.com First of all, the wrong code is wrong, look this is your code: $(function(){ var trs = $(#tb tr:not(:first)) for( var i=0; i$trs.length; i++ ) { //$trs[i].find(td:eq(1)).attr(style,color:red); //wrong $trs.get(i).find(td:eq(1)).attr(style,color:red); //wrong } }) 1. you forgot to put semicolons at two places. $(function(){ var trs = $(#tb tr:not(:first)); -- HERE for( var i=0; i$trs.length; i++ ) { //$trs[i].find(td:eq(1)).attr(style,color:red); //wrong $trs.get(i).find(td:eq(1)).attr(style,color:red); //wrong } }); -- HERE 2. You declared a variable named trs but you than use a varibale named $trs which of course doesn't exist because you haven't declared it... $(function(){ var $trs = $(#tb tr:not(:first)); for( var i=0; i$trs.length; i++ ) { //$trs[i].find(td:eq(1)).attr(style,color:red); //wrong $trs.get(i).find(td:eq(1)).attr(style,color:red); //wrong } }); OK, now the code should work, right? Well, no... because what the get(i) method does is it returns the DOM element at index i from the $trs jQuery obect so after you do get (i), you no longer have an jQuery object, and you cannot call the find () method because it is not a property of DOM elements What you could do is encapsulate $trs.get(i) inside $() to get a jQuery object based on the DOM element, so this code does work: $($trs.get(i)).find(td:eq(1)).attr(style, color:red); However, this is a pretty stupid way to loop through a jQuery object... a better way is to use the each() method: $trs.each(function() { $(this).find(td:eq(1)).attr(style, color:blue); });
Re: [jQuery] Re: Autosuggest breaks in ie7/8
Sorry, but that's not right at all. There is no problem with using 'row' as a function parameter name in IE. We're veering into Cargo Cult Programming here, but it's not your fault, MorningZ. The problem is that we can't see the actual code that's going wrong, so we're all reduced to guessing. GJK, could you please post a link to a test page that demonstrates the problem? That's the only way we can see the real issue and offer useful advice. -Mike On Tue, Dec 22, 2009 at 6:50 PM, MorningZ morni...@gmail.com wrote: IE has a really hard time with reserved words used as function names and/or properties try changing row to something else, even Row would be different enough, as IE *might* be thinking you mean a table row so instead of function DisplayResult(row) { var output = 'dd id='; output += 'a href=' + row['link'] + ''; output += 'p'; output += 'b' + row['title'] + '/b'; output += row['summary']; output += '/p/a/dd'; return output; } try function DisplayResult(ThisRow) { var output = 'dd id='; output += 'a href=' + ThisRow['link'] + ''; output += 'p'; output += 'b' + ThisRow['title'] + '/b'; output += row['summary']; output += '/p/a/dd'; return output; } if that doesn't work, see if the value passed in is indeed a JSON object function DisplayResult(row) { $.each(row, function(key, val) { alert(key + : + val); }); } if that doesn't work then you are not passing an object into the function (perhaps it's a string?) On Dec 22, 8:35 pm, GJK gerlofva...@gmail.com wrote: Ok thank you, Why does this code work in Firefox etc. And not in internet explorer 7/8. And how to fix this for internet explorer? Greatly appreciate it! On Dec 23, 1:38 am, MorningZ morni...@gmail.com wrote: that means that title is not a valid property of the row object On Dec 22, 5:46 pm, GJK gerlofva...@gmail.com wrote: The error was wrong, the good one from internet explorer: - Line: 158 Character: 2 Code: 0 Error Message: 'title' is null or not an object URL:http://localhost.com/js/search.js And it's coming from this function: - function DisplayResult(row) { var output = 'dd id='; output += 'a href=' + row['link'] + ''; output += 'p'; output += 'b' + row['title'] + '/b'; output += row['summary']; output += '/p/a/dd'; return output; } On Dec 22, 9:53 pm, GJK gerlofva...@gmail.com wrote: Hello, I got this code for search auto suggest and everything works fine in Firefox, Chrome, Opera etc. But it breaks in internet explorer 7 and 8. I get this error: - Line: 158 Character: 2 Code: 0 Error Message: 'fghds' is null or not an object URL:http://localhost.com/js/search.js - This is the jquery script: - var SEARCH_BOX_DEFAULT_TEXT = 'Enter the keywords:'; var AJAX_PENDING_TIMER; var CURRENT_PAGE = 1; var CURRENT_LIMIT = 5; function init() { var sTextBox = $(#search_val); sTextBox.focus(function() { if(this.value == SEARCH_BOX_DEFAULT_TEXT) { this.value = ''; } }); sTextBox.blur(function() { if(this.value == '') { this.value = SEARCH_BOX_DEFAULT_TEXT; } }); sTextBox.blur(); sTextBox.keyup(function() { var q= $(#search_val).val(); if( q == SEARCH_BOX_DEFAULT_TEXT || q == '' || q == undefined || q.length=3) { HideLiveSearch(); } else { clearTimeout(AJAX_PENDING_TIMER); CURRENT_PAGE = 1; AJAX_PENDING_TIMER = setTimeout(PerformLiveSearch(),300); } }); $(#livesearch_result_close_link).click(function() { HideLiveSearch(); }); } function NextPage(p) { if(p['has_next']) { AJAX_IS_RUNNING = false; CURRENT_PAGE++; PerformLiveSearch(); }} function PrevPage(p) { if(p['has_prev']) { AJAX_IS_RUNNING = false; CURRENT_PAGE--; PerformLiveSearch(); } } function ShowLoaders() {
Re: [jQuery] Re: Autosuggest breaks in ie7/8
I intended no offense, MorningZ, but suggesting that changing a parameter name from 'row' to 'ThisRow' may somehow fix an IE problem isn't helpful in the slightest. It's simply incorrect. It won't fix the problem, and it's only a distraction from finding the real issue. 'row' isn't a reserved word in IE or in any other browser: http://www.google.com/search?q=javascript+reserved+words We could all think of any number of possible code changes that might or might not have anything to do with the actual problem. It wouldn't be helpful if everyone jumped in suggesting those changes. I wonder if you were thinking of the issue where IE creates a read-only property on the window object for every element ID on your page? That *can* be a real problem. But it only affects global variable names (i.e. window properties), not local variables or parameter names. Now I see from your followup message that you *have* identified the real problem (or at least *a* real problem). Now that truly is helpful, and I'm sure that GJK will be grateful that you've found it. So keep up the good work! :-) -Mike On Tue, Dec 22, 2009 at 8:26 PM, MorningZ morni...@gmail.com wrote: Sorry, but that's not right at all My point was that IE does run into issue when it comes to reserved words, which row is and as you can (or obviously can't) tell from my reply, you're right, i was just taking some stabs in the dark to at least make an attempt to help. i don't think i needed a whole paragraph dedicated to me in your reply because i tried to help... lots of people makes posts on here that it's broke without any indication or why or how it could have happened... but if some of us didn't at least try to help, then this mailing list would be practically nothing but topics started with replies of post code/ link whatever i suppose On Dec 22, 11:04 pm, Michael Geary m...@mg.to wrote: Sorry, but that's not right at all. There is no problem with using 'row' as a function parameter name in IE. We're veering into Cargo Cult Programming here, but it's not your fault, MorningZ. The problem is that we can't see the actual code that's going wrong, so we're all reduced to guessing. GJK, could you please post a link to a test page that demonstrates the problem? That's the only way we can see the real issue and offer useful advice. -Mike On Tue, Dec 22, 2009 at 6:50 PM, MorningZ morni...@gmail.com wrote: IE has a really hard time with reserved words used as function names and/or properties try changing row to something else, even Row would be different enough, as IE *might* be thinking you mean a table row so instead of function DisplayResult(row) { var output = 'dd id='; output += 'a href=' + row['link'] + ''; output += 'p'; output += 'b' + row['title'] + '/b'; output += row['summary']; output += '/p/a/dd'; return output; } try function DisplayResult(ThisRow) { var output = 'dd id='; output += 'a href=' + ThisRow['link'] + ''; output += 'p'; output += 'b' + ThisRow['title'] + '/b'; output += row['summary']; output += '/p/a/dd'; return output; } if that doesn't work, see if the value passed in is indeed a JSON object function DisplayResult(row) { $.each(row, function(key, val) { alert(key + : + val); }); } if that doesn't work then you are not passing an object into the function (perhaps it's a string?) On Dec 22, 8:35 pm, GJK gerlofva...@gmail.com wrote: Ok thank you, Why does this code work in Firefox etc. And not in internet explorer 7/8. And how to fix this for internet explorer? Greatly appreciate it! On Dec 23, 1:38 am, MorningZ morni...@gmail.com wrote: that means that title is not a valid property of the row object On Dec 22, 5:46 pm, GJK gerlofva...@gmail.com wrote: The error was wrong, the good one from internet explorer: - Line: 158 Character: 2 Code: 0 Error Message: 'title' is null or not an object URL:http://localhost.com/js/search.js And it's coming from this function: - function DisplayResult(row) { var output = 'dd id='; output += 'a href=' + row['link'] + ''; output += 'p'; output += 'b' + row['title'] + '/b'; output += row['summary']; output += '/p/a/dd'; return output; } On Dec 22, 9:53 pm, GJK gerlofva...@gmail.com wrote: Hello, I got this code for search auto suggest and everything works fine in Firefox, Chrome, Opera etc. But it breaks in internet explorer 7 and 8. I get this error
Re: [jQuery] Re: Autosuggest breaks in ie7/8
BTW, just to commiserate, you're not the only one who's ever posted incorrect information here. Want to hear a whopper I posted a couple of years ago? Someone was asking how to change the title in the browser window, and I told them that they couldn't: You only get one chance at setting the title, because you can only have one title tag in a document, and once the page is loaded you can't add another title tag. Lucky for the OP, someone followed up with a comment to the effect of, Dude! Ever hear of document.title? :-) -Mike On Tue, Dec 22, 2009 at 8:48 PM, Michael Geary m...@mg.to wrote: I intended no offense, MorningZ, but suggesting that changing a parameter name from 'row' to 'ThisRow' may somehow fix an IE problem isn't helpful in the slightest. It's simply incorrect. It won't fix the problem, and it's only a distraction from finding the real issue. 'row' isn't a reserved word in IE or in any other browser: http://www.google.com/search?q=javascript+reserved+words
Re: [jQuery] setTimeout
You are calling the lengthy jQuery chain *first* and then passing its result to setTimeout. Your code is equivalent to: var temp = $(['li.',o.hoverClass].join(''),this) .add(this) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); setTimeout( temp, 1000 ); Instead, you need to pass a *function* to setTimeout: setTimeout( function() { $(['li.',o.hoverClass].join(''),this) .add(this) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); }, 1000 ); -Mike On Thu, Dec 17, 2009 at 6:47 AM, decola decola...@googlemail.com wrote: setTimeout($(['li.',o.hoverClass].join(''),this).add(this).not (not).removeClass(o.hoverClass).find('ul').css ('visibility','hidden'), 1000);
Re: [jQuery] Re: How to compare data in 2 jQuery data() elements
I think you guys are making this too complicated. Just loop through the data properties: function dataChanged( a, b ) { for( var key in a ) if( a[key] != b[key] ) return true; return false; } if( dataChanged(o,n) ) { someAJAXFunctionThatSavesTheFieldsThatChanged(); } -Mike On Thu, Dec 17, 2009 at 5:58 AM, discern cap...@gmail.com wrote: Thanks. I'll give that a go. Otherwise, I'll just write 2 different functions: one for comparison (I'll probably compare hashes using the sha1 plugin) and one for sending the data to the backend.
Re: [jQuery] Re: setTimeout
I'm sorry, I should have spotted the major bug in the code that I posted. In fact, it's particularly embarrassing, because I wrote a recipe for the jQuery Cookbook [1] on this exact topic. It's recipe 5.2, What's Wrong with $(this)? Inside the setTimeout callback function, this does not have the same value that it has outside the function. To fix it, copy your this value into another variable before calling setTimeout: var element = this; setTimeout( function() { $(['li.',o.hoverClass].join(''),element) .add(element) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); }, 1000 ); Because 'element' is an ordinary JavaScript variable, it is available to the inner nested function (the setTimeout callback). BTW, here's a suggestion for another way to code the jQuery chain. It's six of one, half a dozen of the other, but to my eyes this is a tiny bit easier to follow: var element = this; setTimeout( function() { $(element) .find( 'li.' + o.hoverClass ) .andSelf() .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); }, 1000 ); -Mike [1]: http://www.amazon.com/dp/0596159773/ On Thu, Dec 17, 2009 at 1:02 PM, decola decola...@googlemail.com wrote: thx for the quick answer, but this way i´ve tried it too. I have copied your code and test it too but it just don´t work. The function is called an a alert for example makes it output but the important code is not running like this. On 17 Dez., 18:21, Michael Geary m...@mg.to wrote: You are calling the lengthy jQuery chain *first* and then passing its result to setTimeout. Your code is equivalent to: var temp = $(['li.',o.hoverClass].join(''),this) .add(this) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); setTimeout( temp, 1000 ); Instead, you need to pass a *function* to setTimeout: setTimeout( function() { $(['li.',o.hoverClass].join(''),this) .add(this) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); }, 1000 ); -Mike On Thu, Dec 17, 2009 at 6:47 AM, decola decola...@googlemail.com wrote: setTimeout($(['li.',o.hoverClass].join(''),this).add(this).not (not).removeClass(o.hoverClass).find('ul').css ('visibility','hidden'), 1000);
Re: [jQuery] Re: setTimeout
p.s. If there are extra blank lines in my code samples, those aren't intentional (especially not that one in the middle of the chain). Gmail is adding those for some reason! On Thu, Dec 17, 2009 at 1:19 PM, Michael Geary m...@mg.to wrote: I'm sorry, I should have spotted the major bug in the code that I posted. In fact, it's particularly embarrassing, because I wrote a recipe for the jQuery Cookbook [1] on this exact topic. It's recipe 5.2, What's Wrong with $(this)? Inside the setTimeout callback function, this does not have the same value that it has outside the function. To fix it, copy your this value into another variable before calling setTimeout: var element = this; setTimeout( function() { $(['li.',o.hoverClass].join(''),element) .add(element) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); }, 1000 ); Because 'element' is an ordinary JavaScript variable, it is available to the inner nested function (the setTimeout callback). BTW, here's a suggestion for another way to code the jQuery chain. It's six of one, half a dozen of the other, but to my eyes this is a tiny bit easier to follow: var element = this; setTimeout( function() { $(element) .find( 'li.' + o.hoverClass ) .andSelf() .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); }, 1000 ); -Mike [1]: http://www.amazon.com/dp/0596159773/ On Thu, Dec 17, 2009 at 1:02 PM, decola decola...@googlemail.com wrote: thx for the quick answer, but this way i´ve tried it too. I have copied your code and test it too but it just don´t work. The function is called an a alert for example makes it output but the important code is not running like this. On 17 Dez., 18:21, Michael Geary m...@mg.to wrote: You are calling the lengthy jQuery chain *first* and then passing its result to setTimeout. Your code is equivalent to: var temp = $(['li.',o.hoverClass].join(''),this) .add(this) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); setTimeout( temp, 1000 ); Instead, you need to pass a *function* to setTimeout: setTimeout( function() { $(['li.',o.hoverClass].join(''),this) .add(this) .not(not) .removeClass(o.hoverClass) .find('ul') .css('visibility','hidden'); }, 1000 ); -Mike On Thu, Dec 17, 2009 at 6:47 AM, decola decola...@googlemail.com wrote: setTimeout($(['li.',o.hoverClass].join(''),this).add(this).not (not).removeClass(o.hoverClass).find('ul').css ('visibility','hidden'), 1000);
Re: [jQuery] jQuery FullCalendar Fetch Events Optimization
50 events should be like nothing. I suspect the problem may be that you're calling $('#calendar').fullCalendar('renderEvent', calevent, true); separately for each individual event. I'm not too familiar with the Full Calendar, but can you use the 'events' option described on this page: http://arshaw.com/fullcalendar/docs/events-and-sources.php That sounds like it should let you feed your entire events array into Full Calendar in one fell swoop. Also, the async:false option in your $.ajax call is a VERY BAD IDEA. Sorry for the shouting! But in a single-threaded browser like Firefox, that option will not only lock up the current browser tab during the download, but it will also lock up all browser tabs in all windows. If your site is slow to respond and your visitor decides to go look at another browser window while it loads, they will find that all their browser windows are locked up completely. Not a good thing. Do you need the async:false? -Mike On Thu, Dec 17, 2009 at 12:27 PM, WhoButSB whobu...@gmail.com wrote: Hello All, I was wondering if someone could give me some pointers to help optimize my jQuery Full Calendar Code. The issue i'm running into is when I fetch a lot of events through AJAX ( 25), the browser stalls and becomes unresponsive usually resulting in a message to the user to abort the script. I'm trying to avoid this error, and I was wondering if there was something I could do in my function to improve the loading time. Here is a copy of the function I'm running: //Load the Business Unit Calendar Events function ajaxBUEvents(start, end){ //Loop through the selected checked calendars $(selectBUCalendars()).each(function(i, cal){ $.ajax({ type: 'POST', data: {'startDate': start, 'endDate': end, 'buCals[]': cal}, url: '?= site_url('AJAX/calendar_ajax/get_cal_events'); ?', dataType: 'json', async: false, beforeSend: function(){ $('#loading-dialog').dialog({minHeight: 100, width: 250}).dialog ('open'); $('#loading-dialog p').text('Loading '+cal+' Calendar Events'); }, success: function(calevents){ $.each(calevents, function(i, calevent){ $('#calendar').fullCalendar('renderEvent', calevent, true); }); } }); }); $('#loading-dialog').dialog('close'); } And here is a sample of the JSON that is returned, this is only one event. Sometimes there can be 50+ events returned: [{id:4377,title:BWR - Lighting Affiliates Dinner - Actualized,start:1259874000,end:1259888400,className:BWR Actualized,allDay:false,editable:false}] Thank you for the help!
Re: [jQuery] Re: running an onload code snippet only once
$(document).ready( function() {} ) and $( function() {} ) are the same thing. The latter is just a shortcut to the former. If one is acting oddly, chances are that the other will too. Richard, $( function() {} ) should *never* call your function more than once. It definitely shouldn't call it whenever the DOM changes. That's not how it works at all. If that is happening, something must be very wrong in your page, and I wouldn't trust any JavaScript code to run correctly. I certainly wouldn't use $(window).load() as a workaround. If you can post a link to a test page that demonstrates the problem, we could take a look at it and find out what's wrong. -Mike On Wed, Dec 16, 2009 at 6:19 AM, Juan Ignacio Borda juanignaciobo...@gmail.com wrote: try using: $(document).ready(function(){ ...your code here }); this is the JQuery way Original Message Those events window.onload, in jQuery, that would be $(window).load (...), should *not* be firing at any time other than when the document loads the first time... something else has to be going on with your code to fire off that code again On Dec 15, 3:27 pm, Richard KLINDA rkli...@gmail.com rkli...@gmail.com wrote: Hello, what is a good way to run a code snippet after the page is loaded, but only just one time? I use the ready event $(function(){...}); most of the time, but sometimes it fires multiple times (when the DOM changes I think), and rarely there are stuff that I only want to run JUST ONCE per pageload. What is a good way to achieve that? Now I do window.onload = function() {...}, but I hope there is something better. Thanks in advance... -- Richard
Re: [jQuery] Re: Debugging in IE
I'm glad you fixed your problem, but I'm certain that the conclusion (IE has trouble with a chained ajax call) is wrong. In the code you posted in the other thread, the chained and non-chained versions are quite different. You didn't just cut the chain into parts: the non-chained version uses a completely different selector. That is where the problem lies, not in the chaining or lack thereof. -Mike On Tue, Dec 15, 2009 at 5:32 AM, Henjo henjohoek...@gmail.com wrote: Hi MorningZ, thanks for your thoughts. I didn't even think of that since it has been a couple of weeks ago I built this. Only IE needed to be fixed. I finally was able to get it fixed by putting alerts in to see where it stopped. Apparently IE has trouble with a chained ajax call. I cut the chain into part and then it worked. Thanks again for your thoughts, I really appreciate it and take to heart what you say! Henjo On Dec 14, 11:18 pm, MorningZ morni...@gmail.com wrote: I would *definitely* start by using the non-minified version of jQuery, as it's 1000x easier to get an idea of what's going on (i see in the source of the page you are using the min-ed version) On Dec 14, 4:31 pm, Henjo henjohoek...@gmail.com wrote: Hey Scott, thanks for posting. I will check this out and see if I can find something here... Henjo On Dec 14, 8:51 pm, Scott Stewart sstwebwo...@bellsouth.net wrote: There is a Firebug Lite which runs in IE, it's not nearly as good as Firebug, but it's better than nothing (or the developer tools in IE8 -Original Message- From: jquery-en@googlegroups.com [mailto:jquery...@googlegroups.com] On Behalf Of Henjo Sent: Monday, December 14, 2009 2:46 PM To: jQuery (English) Subject: [jQuery] Debugging in IE Hi list, I am wondering how to do debugging in IE the best way. I installed fiddler and work with ie8's dev tools. The problem is I have a script that runs perfectly in FF, Chrome, Safari but not in IE. There the dynamic form wizard. stops after 2 loads... This is the site I am talking abouthttp://bit.ly/7v8pHu Thanks in advance for your tips. Henjo
Re: [jQuery] Call from Javascript to jQuery javascript function
In fact, within a single script tag, function definitions happen first, before any code in that script tag is executed. It would be perfectly valid to write: script type=text/javascript // will be run immediately, but *after* callit is defined callit(); // will be defined immediately, and *before* the code above is excuted function callit() { alert(Hello world!); } /script I'm not saying that this code would be the same as the $(document).ready() version - it doesn't wait for DOM ready - just pointing out that function definitions are processed before code is executed. It works the same way inside a function: script type=text/javascript outer(); function outer() { inner(); function inner() { alert(Hello world!); } } /script That code will alert Hello world! even though the call to each function precedes its definition. -Mike On Wed, Dec 16, 2009 at 6:17 AM, Richard D. Worth rdwo...@gmail.com wrote: No need to add another block. As you pointed out earlier, the document ready won't run until later. By the time it does, the callit function will have been defined: script type=text/javascript $(document).ready(function() { // will be run when doc is loaded callit(); }); // will be defined immediately function callit() { alert(Hello world!); } /script - Richard
Re: [jQuery] google.load issue
Put your lines of code in separate script tags. google.load() uses document.write() to write a script tag into the document. This script tag is not executed until the current script tag exits. So your jQuery.noConflict() call is being executed before jQuery is loaded. If you break up the script tags like this, it should work fine: script type=text/javascript google.load(jquery, 1); /script script type=text/javascript jQuery.noConflict(); google.load(prototype, 1); /script -Mike On Wed, Dec 16, 2009 at 7:58 AM, speedpac...@gmail.com speedpac...@gmail.com wrote: Hi, For obvious reasons, we try using Google to load javascript libraries when we need them. We already used Prototype using google.load() function, and now we decided to add jQuery as well since we will be using some jQuery UI widgets to speed up development on a project (more specifically we need a decent date selector! Basically, what we did is: google.load(jquery, 1); jQuery.noConflict(); google.load(prototype, 1); Unfortunately, for some reason, it complains that noConflict() is no method leading me to believe tha the jQuery code isn't loaded properly prior to calling the noConflict() method... We have never had such an issue in the past, and if we link directly to the .js file hosted on google servers without using the google.load () method, it works fine as well... Does anyone know this is a known issue when working with google.load ()? Since we manage the needed libraries through a database, and use the google.load() function for all these libraries, it would be a shame if we need to include jQuery library directly without using the google.load() method :) thanks in advance for your very much appreciated feedback! David.
Re: [jQuery] Re: Return values
Looks like we have two threads going on the same topic. :-) To give you a real code example, I'd need to see the code that makes use of that 'result' variable you're setting. Where is that code and what does it look like? The bottom line is simple: whatever the code is that uses the 'result' variable, that code needs to be made into a function, and you need to call that function in the ajax success callback. Or, that function can *be* the success callback. You can't just set a variable in an asynchronous callback and expect other code somewhere else on the page to somehow know when your variable is ready for use. It's not a question of how far deep in nested functions can you return a value. Any nested function can return a value; it doesn't matter how far deeply your functions are nested. But that return value goes only to *whoever called that function*. In the case of a $.ajax callback, the return value is being passed back into the $.ajax code, which probably ignores the value completely. The real issue is *when* the code is run. Can you post a URL to a complete test page? That would make it a lot easier to suggest the right way to write your code. -Mike On Mon, Dec 14, 2009 at 5:48 AM, Jojje jojjsus_chr...@hotmail.com wrote: Hi! Yeah i got that tip before but i'm not sure i understand this. Could you perhaps give me an example with the code below :) regards George On 14 Dec, 14:27, Rick van Hoeij rickvho...@gmail.com wrote: because of the async of javascript I normally use callback functions to do the value passing. So instead of return true or return false in a ajax function, it's better to call a function with the true or false as a parameter. Just my two cents ;) On 12 dec, 20:24, Jojje jojjsus_chr...@hotmail.com wrote: How deep in the scope can you go in nested functions and still return a value? For example: $.validator.addMethod('userCheck', function (value) { $.ajax({ type: POST, url: _scripts/send_message.php, data: action=checkuser username= + value, success: function(msg) { if (msg) { return false; } else { return true; } } }); },); Why is´nt this working? If i do this: //Global var result; $.validator.addMethod('userCheck', function (value) { $.ajax({ type: POST, url: _scripts/send_message.php, data: action=checkuser username= + value, success: function(msg) { if (msg) { result = false; } else { result = true; } } }); return result; },); i get the value back but it does not work properly, It gets the value from the textfield but on keyup it's always one letter short... so i have to type one more letter to get the right value. I´m stuck on this so any help would be greatly appreciated! :) Thanks in advance George
Re: [jQuery] Re: Return values
OK, so the real question here is a bit different from the question I've been trying to answer. :-) In general JavaScript coding, what I've been saying is true: If you want to write code that uses data downloaded by a $.ajax call, you need to put that code in a function called from the $.ajax success callback - or in the callback itself. However, what you're doing is using the validation plugin to validate a form. So the question in this specific case is how do I get the validator plugin to validate based on data downloaded via an ajax call, right? The validator plugin has a specific interface built in for this. Instead of calling $.ajax yourself and trying to somehow get the validation plugin to use that data, you use the validation plugin's own 'remote' property, which will make the $.ajax call for you. Documentation and examples: http://docs.jquery.com/Plugins/Validation/Methods/remote#options Let me know if that helps! -Mike On Mon, Dec 14, 2009 at 9:33 AM, Jojje jojjsus_chr...@hotmail.com wrote: Ok, yes you can check it out at http://www.sonicconnection.se/se/index.php?site=_misc/register It´s in swedish but its the first field that uses the code to check if the username already exists, it makes a call to a php script and the response is equal to the username if it exists in the database, and if it does'nt exist it returns nothing. I put the parts of the script thats for the registration at the top and commented it. the script file is sc_functions.js Its a lot of repetetive code int there that i havent made into fuctions yet so you know haha :) Thanks again :) George On 14 Dec, 18:15, Michael Geary m...@mg.to wrote: Looks like we have two threads going on the same topic. :-) To give you a real code example, I'd need to see the code that makes use of that 'result' variable you're setting. Where is that code and what does it look like? The bottom line is simple: whatever the code is that uses the 'result' variable, that code needs to be made into a function, and you need to call that function in the ajax success callback. Or, that function can *be* the success callback. You can't just set a variable in an asynchronous callback and expect other code somewhere else on the page to somehow know when your variable is ready for use. It's not a question of how far deep in nested functions can you return a value. Any nested function can return a value; it doesn't matter how far deeply your functions are nested. But that return value goes only to *whoever called that function*. In the case of a $.ajax callback, the return value is being passed back into the $.ajax code, which probably ignores the value completely. The real issue is *when* the code is run. Can you post a URL to a complete test page? That would make it a lot easier to suggest the right way to write your code. -Mike On Mon, Dec 14, 2009 at 5:48 AM, Jojje jojjsus_chr...@hotmail.com wrote: Hi! Yeah i got that tip before but i'm not sure i understand this. Could you perhaps give me an example with the code below :) regards George On 14 Dec, 14:27, Rick van Hoeij rickvho...@gmail.com wrote: because of the async of javascript I normally use callback functions to do the value passing. So instead of return true or return false in a ajax function, it's better to call a function with the true or false as a parameter. Just my two cents ;) On 12 dec, 20:24, Jojje jojjsus_chr...@hotmail.com wrote: How deep in the scope can you go in nested functions and still return a value? For example: $.validator.addMethod('userCheck', function (value) { $.ajax({ type: POST, url: _scripts/send_message.php, data: action=checkuser username= + value, success: function(msg) { if (msg) { return false; } else { return true; } } }); },); Why is´nt this working? If i do this: //Global var result; $.validator.addMethod('userCheck', function (value) { $.ajax({ type: POST, url: _scripts/send_message.php, data: action=checkuser username= + value, success: function(msg) { if (msg) { result = false; } else { result = true; } } }); return result; },); i get the value back but it does not work properly, It gets the value from the textfield but on keyup it's always one letter short... so i have to type one more letter to get the right value. I´m stuck on this so any help would be greatly appreciated! :) Thanks in advance George
Re: [jQuery] Re: Can't get a block of HTML added to the DOM
T.J., I think you're right on the money. Joseph, no need to wonder whether you've run into an issue with the .append() method. Instead, verify whether you actually have the right data on hand or not. Where you had this code: $('#somediv').append(html); Change it to: alert( html ); and see what the alert shows. It may well say something like undefined. If you try T.J.'s suggestion, you may find something more useful. Either way, by alerting the value (or using console.log with Firebug or the like), you can check that the HTML code you're trying to append is actually what you want. -Mike On Mon, Dec 14, 2009 at 2:03 PM, T.J. Simmons theimmortal...@gmail.comwrote: Have you tried it without the data.content? IE: var html = data; that should get you all of the HTML you're pulling in via AJAX. I haven't ever seen the .content method before, and a quick Google search came up with nothing for it.. maybe that's the problem? I'm sure someone who knows more will come in and blast my answer, but that's my thought. Hope that helps. - T.J. On Dec 14, 10:05 am, joseph7 radioak...@gmail.com wrote: Hi, So, I'm attempting to add HTML to a document via Ajax, but when I get back the content, I'm finding that no matter what I try, I can't get it added to the DOM correctly. Basically I'm doing this: $.post('ajax.php', function (data) { var html = data.content; $('#somediv').append(html); } ); The HTML I'm loading looks like this: div class=somediv form id=someform p class=someclassName:/p input style=display: none; type=textbox name=somefield value=test / /p /form /div While the content does show up in the div, if I try to get the form by doing $('#someform'), jQuery returns nothing. I've tried using .append () and .html(), and neither way gives me what I want. Is there something I'm missing here? I know adding objects to the DOM in jQuery is ridiculously easy, so I feel like I'm either running up against something impossible, or I have a hugely flawed concept of how append () and html() work.
Re: [jQuery] Re: Can't get a block of HTML added to the DOM
Oh, wait a minute. You said the content *does* show up in the div. I think you need to post a link to a test page, so we can see what is actually happening. That would make it a lot easier to help troubleshoot. -Mike On Mon, Dec 14, 2009 at 2:15 PM, Michael Geary m...@mg.to wrote: T.J., I think you're right on the money. Joseph, no need to wonder whether you've run into an issue with the .append() method. Instead, verify whether you actually have the right data on hand or not. Where you had this code: $('#somediv').append(html); Change it to: alert( html ); and see what the alert shows. It may well say something like undefined. If you try T.J.'s suggestion, you may find something more useful. Either way, by alerting the value (or using console.log with Firebug or the like), you can check that the HTML code you're trying to append is actually what you want. -Mike On Mon, Dec 14, 2009 at 2:03 PM, T.J. Simmons theimmortal...@gmail.comwrote: Have you tried it without the data.content? IE: var html = data; that should get you all of the HTML you're pulling in via AJAX. I haven't ever seen the .content method before, and a quick Google search came up with nothing for it.. maybe that's the problem? I'm sure someone who knows more will come in and blast my answer, but that's my thought. Hope that helps. - T.J. On Dec 14, 10:05 am, joseph7 radioak...@gmail.com wrote: Hi, So, I'm attempting to add HTML to a document via Ajax, but when I get back the content, I'm finding that no matter what I try, I can't get it added to the DOM correctly. Basically I'm doing this: $.post('ajax.php', function (data) { var html = data.content; $('#somediv').append(html); } ); The HTML I'm loading looks like this: div class=somediv form id=someform p class=someclassName:/p input style=display: none; type=textbox name=somefield value=test / /p /form /div While the content does show up in the div, if I try to get the form by doing $('#someform'), jQuery returns nothing. I've tried using .append () and .html(), and neither way gives me what I want. Is there something I'm missing here? I know adding objects to the DOM in jQuery is ridiculously easy, so I feel like I'm either running up against something impossible, or I have a hugely flawed concept of how append () and html() work.
Re: [jQuery] Can't get a block of HTML added to the DOM
Wendi, just a tip to help you get the assistance you're looking for: Since your question doesn't seem to relate to the topic of this particular thread, people may not notice it. Could you re-post your question as a new post with its own title that summarizes the question? That will help people find it who may have an answer for you. It would also help if in that post you could describe the problem in more detail, and explain a bit more about what it is your need to accomplish. Thanks! -Mike On Mon, Dec 14, 2009 at 4:25 PM, Wendi Turner wenditur...@gmail.com wrote: *How can you remove/delete the active $(document).ready() script, re-write and re-register then re-trigger the ready script?? Without reloading the page?*
Re: [jQuery] Can't get a block of HTML added to the DOM
Good point, thanks for noticing that, Brian. This is a good example of why it's always helpful to post a link to a live test page instead of just a code snippet. Then we know what the actual code looks like and can see it run in the browser. -Mike On Mon, Dec 14, 2009 at 4:20 PM, brian zijn.digi...@gmail.com wrote: $('#somediv').append(html); You're appending to the div with ID 'someDiv'. But you say that this is the content: div class=somediv form id=someform p class=someclassName:/p input style=display: none; type=textbox name=somefield value=test / /p /form /div Note the class=somediv. I'm wondering if that's a typo and it's actually id=somediv, in which case you'll have 2 divs with identical IDs. Just a shot in the dark. On Mon, Dec 14, 2009 at 11:05 AM, joseph7 radioak...@gmail.com wrote: Hi, So, I'm attempting to add HTML to a document via Ajax, but when I get back the content, I'm finding that no matter what I try, I can't get it added to the DOM correctly. Basically I'm doing this: $.post('ajax.php', function (data) { var html = data.content; $('#somediv').append(html); } ); The HTML I'm loading looks like this: div class=somediv form id=someform p class=someclassName:/p input style=display: none; type=textbox name=somefield value=test / /p /form /div While the content does show up in the div, if I try to get the form by doing $('#someform'), jQuery returns nothing. I've tried using .append () and .html(), and neither way gives me what I want. Is there something I'm missing here? I know adding objects to the DOM in jQuery is ridiculously easy, so I feel like I'm either running up against something impossible, or I have a hugely flawed concept of how append () and html() work.
Re: [jQuery] delete / remove $.ajax() object ???
That sounds right on the money, Brian. Wendi, to give an example, suppose your code is something like this: $(document).ready( function() { $.ajax({ ... }); }); Let's say you want to make that $.ajax call both at load time and also later in response to a click event on some div. Then you could do: $(document).ready( function() { function loadSomething() { $.ajax({ ... }); } loadSomething(); // runs at document ready time $('#somediv').click( loadSomething ); // runs on the click }); It's that simple! Note that the reference to loadSomething in the .click() call does *not* have parentheses after it. By leaving out the parens, we avoid calling the function immediately. Instead we simply get a reference to the function that we pass into .click() so that jQuery can call it later on the click event. -Mike On Mon, Dec 14, 2009 at 5:21 PM, brian zijn.digi...@gmail.com wrote: Put your $.ajax() call inside a function and call that on load and whatever other event. On Mon, Dec 14, 2009 at 8:18 PM, Wendi Turner wenditur...@gmail.com wrote: Thank you Mike ! Repost Question: How can you remove/delete the active $(document).ready() script, re-write and re-register then re-trigger the ready script?? Without reloading the page? I have an anonymous $.ajax( function ( blah blah) ) created in the $document.ready() object. I want to reload the $.ajax () object on a client event. How can I do this best? Michael Geary m...@mg.to Wendi, just a tip to help you get the assistance you're looking for: Since your question doesn't seem to relate to the topic of this particular thread, people may not notice it.
Re: [jQuery] Re: proper way
Actually the scope rules I described always apply to all JavaScript code, whether it uses jQuery or otherwise. They also apply to your $.ajax example. Consider your second version. You have a result variable declared outside your validator code. The success function is able to access this variable even though it's nested two functions deep (you're inside both the anonymous function passed into addMethod and the innermost success callback). This would still work even if the entire example were nested inside yet another function, so 'result' would now be a local variable in that outer function. Given all that, why doesn't your first version work? Well, the $.ajax function is *asynchronous*. The success callback isn't called right away. It's called later, after the download has completed. If the success callback returns a value, where could that value go? It can't be passed through to become the return value from the $.ajax call, because that function has *already returned*. But the second version isn't right either. The success callback will set the 'result' variable as expected, but there's a little problem... How does the rest of your code know when that variable is ready to look at? I suppose you could write a polling loop somewhere: var watchdog = setInterval( function() { if( result !== undefined ) { clearInterval( watchdog ); // now result is ready, use it here } }, 100 ); That code checks the 'result' variable 10 times a second, and when it sees that the variable's value is no longer 'undefined' it stops the interval timer and uses the variable. But that would be kind of silly, not to mention inefficient. Fortunately, there is a much simpler solution. In your success callback, *call a function* and pass it your ajax result. In fact, that's the reason why there is a success callback in the first place. $.ajax calls your success callback when the ajax data has been downloaded and is ready for use. So any code that uses that data should also be called from your callback function. -Mike On Sun, Dec 13, 2009 at 8:23 AM, Jojje jojjsus_chr...@hotmail.com wrote: Hahaha! You dont have to apologise for that, my mother should apologise to me hahahaha Ok thank you for your very good and easy explanations on this. This was actually part of another qustion i posted here, these rules doesnt apply in this example right? $.validator.addMethod('userCheck', function (value) { $.ajax({ type: POST, url: _scripts/send_message.php, data: action=checkuser username= + value, success: function(msg) { if (msg) { return false; } else { return true; } } }); },); Even though it¨s nested functions i cant return anything outside this without using a global variable? Like this: var result; $.validator.addMethod('userCheck', function (value) { $.ajax({ type: POST, url: _scripts/send_message.php, data: action=checkuser username= + value, success: function(msg) { if (msg) { result = false; } else { result = true; } } }); return result; },); regards George
Re: [jQuery] Re: proper way
No, the two examples shouldn't work the same. They are both working exactly as expected. Let me slightly rewrite each version in a more step-by-step fashion and you will see why. The first version is equivalent to: $(function() { function handleClick() { clickFunction1(); } $('a.link1').click( handleClick ); }); In this code, you are defining a function and then passing a reference to that function into the click() method. When the click event is triggered, your handleClick function will be called, and that in turn calls clickFunction1. The second example is equivalent to: $(function() { var result = clickFunction1(); $('a.link1').click( result ); }); See the difference? This code calls clickFunction1() immediately. It then takes the *return value* from clickFunction1() and passes that into the click() method as the event handler. But your clickFunction1() probably doesn't return any value, does it? And it certainly doesn't return a *function* as its return value (although a function can return another function if you want it to). Why does it work this way? Because you put the () after the clickFunction1 name. Whenever you use () after a name, it calls that function *immediately*. Your second example would work as you expected if you simply remove the (): $(function() { $('a.link1').click( clickFunction1 ); }); Now, instead of calling clickFunction1 immediately, your code merely takes a reference to that function and passes it into the click() method. Make sense? Give a shout back with any questions... -Mike On Sat, Dec 12, 2009 at 3:01 AM, Jojje jojjsus_chr...@hotmail.com wrote: Ok, thank you for your anwer :) Appreciate it! One more question. If i use the code in example 2 the function gets triggered without me clicking the link, in example 2 it gets triggered only when i click the link. Dont know if i´m doin anything wrong here? Shouldnt both examples work the same? 1. $(function() { $('a.link1').click(function() { clickFunction1(); }); }); 2. $(function() { $('a.link1').click(clickFunction1()); }); function clickFunction1() { //code } George
Re: [jQuery] Re: proper way
I think you've got it! By George you've got it! (With apologies both to you and to Rex Harrison and Audrey Hepburn!) What you describe is not the only way to do it, but it's certainly a good way. You just have to understand what variables a function has access to. Of course a function can access its own local variables and its own parameters. A function can *also* access variables (and parameters, same thing) in any functions that it's nested inside. When JavaScript looks up a name, it starts in the innermost function where the reference to the name occurs. If it doesn't find the name there, and if the function is nested inside another function, then it looks in that outer function. If it still doesn't find the name, and there is another outer function, it looks there, and so on, until finally as a last resort it reaches the global scope (which is really the window object). It doesn't matter if the functions have names or are anonymous - all this works the same either way. A classic example is the use of a function with setTimeout: function test() { var foo = 'bar'; setTimeout( function() { alert( foo ); // alerts 'bar' }, 1000 ); } As with the jQuery event examples, note that the alert call is made long after the test() function has returned. But JavaScript keeps a reference to the foo variable just so that the inner function can use it. And like the jQuery examples, it works the same if you don't use an anonymous function: function test() { var foo = 'bar'; setTimeout( alerter, 1000 ); function alerter() { alert( foo ); // alerts 'bar' } } It's the fact that the alerter function is nested inside the test function that makes it work. This use of a nested function to access variables after an outer function has returned is called a closure. It's one of the most powerful features in JavaScript, and one to get very familiar with. -Mike On Sat, Dec 12, 2009 at 11:10 AM, Jojje jojjsus_chr...@hotmail.com wrote: Oh ok :) So in order for me to pass arguments without triggering clickFunction1 immediately,and instead triggering it when the link is clicked, i have to call it through another function thats not passed any arguments? So it´s still ok to use an anonymous function like in my example to achieve this? The reason i´m asking this is i´m still learning the fundamentals of javascript and i don´t know how the computer handles the code, If it takes up more memory and so on. :) Thank you so much for taking time to answer these questions, highly appreciate it :) Regards George
Re: [jQuery] Re: Ajax , Json, and error firing instead of success
It's probably 'parsererror', not 'parseerror', right? If you search the jQuery source for 'parsererror', you will find the two places where that error can be thrown. That may shed a little light on it. Actually what I would do would be to start stripping down the JSON response until the error goes away. When it starts working (or at least parses OK), then you know the error was in the part you just removed. Your JSON data certainly *looks* OK, and it passes the validator at www.jsonlint.com, but there must be something in it making IE6/7 unhappy. It works OK in IE8, right? -Mike On Tue, Dec 8, 2009 at 11:48 PM, elpatator romain.simi...@gmail.com wrote: Dear all, as suggested above, I just made a quick test using error: function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest: + XMLHttpRequest); alert(textStatus: + textStatus); alert(errorThrown: + errorThrown); }, Wich, in IE6/7, returns me textStatus:parseerror. What the hell ?
Re: [jQuery] Re: Very Strange !!! The same HTML code works well, but append() it not !!!
Eric, you really need to put up a test page so we can try actually loading it. Otherwise it's too hard to tell what might be wrong. I'm not even sure what the problem is we're supposed to be looking at! -Mike On Mon, Dec 7, 2009 at 11:44 PM, Eric Zhong ericiszhongwen...@gmail.comwrote: i have modified the code , but the result is the same, even if i write this in one line !!! Help !!! one line version: html head script src= http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js;/script SCRIPT LANGUAGE=JavaScript !-- $(function(){ // /* var html_video ='table id=tb_all width=724pxtrtd valign=toptable id=tb_video class=tb_widthtr class=tb_headtdnbsp/tdtdfilename/tdtdlen(s)/tdtdsize(KB)/td/tr/table/td/tr/table'; $(body).append( html_video ); var data = [ {name: 1, len: 432, size: 321}, {name: 2, len: 54543, size: 432}, {name: 3, len: 3243, size: 432}, {name: 4, len: 543, size: 432}, {name: 5, len: 543, size: 654}, {name: 6, len: 654, size: 654}, {name: 7, len: 765, size: 654}, {name: 8, len: 765, size: 765}, {name: 9, len: 53, size: 654} ]; var a = data; if ( a != null ){ for(var i=0; ia.length; i++){ var d = a[i]; $(#tb_video).append('trtdinput type=checkbox //tdtd' + d.name + '/tdtd' + d.len + '/tdtd' + d.size + '/tdtr'); } } $(#tb_video).closest(tr).append('td width=80px align=center style=vertical-align:topinput id=pl_bt_up type=button value=↑ /input id=pl_bt_down type=button value=↓ //td'); // */ $(#pl_bt_up).click(function() { var $all = $(#tb_video tr); var $trs = $(#tb_video tr:has(input:checked)); if( $all.index($trs.get(0)) != 1 ){ $trs.each(function(){ $(this).prev().before($(this)); }); } }); $(#pl_bt_down).click(function() { var $all = $(#tb_video tr); var $trs = $(#tb_video tr:has(input:checked)); if( $all.index( $trs.get($trs.length-1) ) != $all.length-1 ){ for( i = $trs.length-1; i=0; i-- ) { var $item = $( $trs.get(i) ); $item.insertAfter($item.next()); } } }); }); -- /SCRIPT /head body !-- table id=tb_all width=724px tr td valign=top table id=tb_video class=tb_width tr class=tb_head tdnbsp/td tdfilename/td tdlen(s)/td tdsize(KB)/td /tr trtdinput type=checkbox //tdtd1/tdtd222/tdtd432/td/tr trtdinput type=checkbox //tdtd2/tdtd333/tdtd543/td/tr trtdinput type=checkbox //tdtd3/tdtd444/tdtd654/td/tr trtdinput type=checkbox //tdtd4/tdtd555/tdtd765/td/tr trtdinput type=checkbox //tdtd5/tdtd666/tdtd876/td/tr trtdinput type=checkbox //tdtd6/tdtd777/tdtd432/td/tr trtdinput type=checkbox //tdtd7/tdtd888/tdtd543/td/tr trtdinput type=checkbox //tdtd8/tdtd999/tdtd265/td/tr /table /td td width=80px align=center style=vertical-align:top input id=pl_bt_up type=button value=↑ / input id=pl_bt_down type=button value=↓ / /td /tr /table -- /body /html 2009/12/8 seasoup seas...@gmail.com javascript cant read strings over line breaks. $(#tb_video).append(' \ tr \ tdinput type=checkbox //td \ td' + d.name + '/td \ td' + d.len + '/td \ td' + d.size + '/td \ tr '); must be $(#tb_video).append('tr'+ 'tdinput type=checkbox //td'+ 'td' + d.name + '/td'+ 'td' + d.len + '/td'+ 'td' + d.size + '/td'+ 'tr '); On Dec 7, 6:30 pm, Eric Zhong
Re: [jQuery] Re: Document undefined error
No, there are no IE settings that need to be enabled. jQuery works with every modern browser out of the box. Loading a .js file directly from the browser address bar is not how it would ever be used in the context of a website, so no conclusions should be drawn from that experience. jQuery will work as expected in all browsers when it is loaded in the normal way using a script tag within an HTML document (either a static HTML document or an HTML page generated dynamically by any server language). Just to amplify the point, remember when you loaded jquery.min.js in the Firefox address bar and it displayed the content of the .js file in the Firefox window? That certainly isn't what you'd want to happen on your website either. You wouldn't want the JavaScript code to be displayed in your web page when someone visits! :-) But you don't need to worry about what happens when you try to view the .js file directly in Firefox or IE. It's not the same as how it will work when the .js file is loaded in the normal manner from a script tag in your page. Hope that helps, -Mike On Tue, Dec 8, 2009 at 1:23 AM, Firefox barrie.wh...@gmail.com wrote: Many thanks for your replies. Yes I can confirm we have web developers that are re-writing our entire website, and they will be using jquery within it. I know the code itself does not do anything, but the developers seem convinced it should at least display the same info as it does when run with firefox. The team I work for is responsible for looking at GPO's, I guess I really just need to know if there are any particular IE settings that have to be enabled. If the answer is no, that is fine, because then I can go back to them with that :-D thanks for your time
Re: [jQuery] Re: Very Strange !!! The same HTML code works well, but append() it not !!!
Hi Eric, Please forgive me for not explaining clearly. Here is what I meant by a test page: post your HTML page on a website somewhere and give us the URL to that page. Then we can click the link and load your page, just like any other web page. That makes it much easier to help you troubleshoot. Here, since I didn't explain myself well, I went ahead and uploaded your files to my own site: http://mg.to/test/zhong/OK.html http://mg.to/test/zhong/Error.html Now when I load the page I can see the strange behavior you noticed. I also noticed that the two pages display slightly differently from each other. Do you see how the Error page has more spacing between the rows than the OK page? This made me think there is something different in the dynamically generated code. To find the difference, I used the View Source Chart extension for Firefox: https://addons.mozilla.org/en-US/firefox/addon/655 along with the Araxis Merge file comparison program: http://www.araxis.com/ I opened your OK.html file in Firefox and selected View Source Chart from the View menu. I also opened a new file comparison window in Araxis Merge. (Araxis Merge is an excellent but fairly expensive commercial product. You could use any file comparison or diff program, though.) Then I did a select all and copy, and pasted the result into the left panel in Araxis Merge. I did the same thing with your Error.html file and pasted the result into the right panel in Araxis Merge. This showed me the difference between the straight HTML version and the JavaScript-generated version. I saved the comparison report here for you to look at: http://mg.to/test/zhong/compare.html Scroll down in that page and take a look around line 116 on the left, line 256 on the right. Do you see the extra /tr and tr tags there, and the same thing in the lines below that? In the JavaScript-generated version, there is an *extra* empty table row in between each of your table rows. This is why your up and down buttons are acting strangely. They probably *are* moving the table row(s) up and down as expected, but those empty table rows are interfering with that. I'm sure if you get rid of the empty rows it will work as you want. This also explains why there is a small difference in layout between the two versions. Do you see where the JavaScript version has more spacing between the rows (at least in Firefox)? That is caused by the empty rows. I'll let you sort out what part of your JavaScript code is causing those extra rows to be added. Hope that helps, -Mike On Tue, Dec 8, 2009 at 1:59 AM, Eric Zhong ericiszhongwen...@gmail.comwrote: thanks for your reply, my english is poor , i can't understand what is test page, you meant src file or description for the result ??? description: 1. when you use HTML code, it runs well , you can select one or more select box and click up or down button, the selected line will up and down immediately. 2. but when you use jQuery to append() the code , you do the same action , the selected line, will move or not some times, and when you multiselect lines, you will see the strange result, it's hard to say with my poor english, sorry !!! i attach 2 files, one is OK, and another is Error. you can run it (double click) , and to opt and to see what difference. 2009/12/8 Michael Geary m...@mg.to Eric, you really need to put up a test page so we can try actually loading it. Otherwise it's too hard to tell what might be wrong. I'm not even sure what the problem is we're supposed to be looking at! -Mike On Mon, Dec 7, 2009 at 11:44 PM, Eric Zhong ericiszhongwen...@gmail.comwrote: i have modified the code , but the result is the same, even if i write this in one line !!! Help !!! one line version: html head script src= http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js;/script SCRIPT LANGUAGE=JavaScript !-- $(function(){ // /* var html_video ='table id=tb_all width=724pxtrtd valign=toptable id=tb_video class=tb_widthtr class=tb_headtdnbsp/tdtdfilename/tdtdlen(s)/tdtdsize(KB)/td/tr/table/td/tr/table'; $(body).append( html_video ); var data = [ {name: 1, len: 432, size: 321}, {name: 2, len: 54543, size: 432}, {name: 3, len: 3243, size: 432}, {name: 4, len: 543, size: 432}, {name: 5, len: 543, size: 654}, {name: 6, len: 654, size: 654}, {name: 7, len: 765, size: 654}, {name: 8, len: 765, size: 765}, {name: 9, len: 53, size: 654} ]; var a = data; if ( a != null ){ for(var i=0; ia.length; i++){ var d = a[i]; $(#tb_video).append('trtdinput type=checkbox //tdtd' + d.name + '/tdtd' + d.len
Re: [jQuery] jQuery validation error: 'settings' is null or not an object
It's pretty hard to tell what could possibly be wrong from just that code snippet. If you can post a link to a test page that demonstrates the problem, it will be much easier for someone to help. -Mike On Tue, Dec 8, 2009 at 10:17 AM, NovoGeek kris.techg...@gmail.com wrote: Hi all, I'm using jQuery validation plugin and everything works fine in Firefox. But in IE (78), when I try to validate my form, I get the error - ['settings' is null or not an object]. I'm using simple rules like this: $(#FormID).validate({ rules: { FirstNameText:required }, messages:{ FirstNameText: Please enter first name } }); I searched for similar posts and found this: http://groups.google.com/group/jquery-en/browse_thread/thread/831feb27923dc32c . However, a convincing answer is not given. Can some one tell me why this error is coming?
Re: [jQuery] Re: Ajax , Json, and error firing instead of success
Yeah, the eval() is undoubtedly wrong, but that wouldn't be the issue here if it's never getting to the success callback. Is there any clue about the error in the arguments passed to the error callback? You have the wrong parameter list in that function. It takes three arguments as shown here: http://docs.jquery.com/Ajax/jQuery.ajax#options error: function( XMLHttpRequest, textStatus, errorThrown ) { // typically only one of textStatus or errorThrown // will have info } -Mike On Tue, Dec 8, 2009 at 12:20 PM, MorningZ morni...@gmail.com wrote: Is there a reason why you have eval() ? jQuery will do that by itself if you are telling it to retrieve JSON On Dec 8, 1:44 pm, elpatator romain.simi...@gmail.com wrote: Hi people, I'm trying to make an ajax request, hoping for a clean json response to come up. Firefox, as usual, behaves like a charm, but when it comes to IE 6 and 7, it's the error function that's fired. $.ajax({ url: action, data: data, type: GET, dataType: json, error: function(msg) { alert(Error: + msg); alert(URL: + action); alert(DATA: + data); }, success: function(reponse) { var result = eval((+reponse+)); alert(result); console.info(reponse); [... ...] Using Charles Web DEbbuging Proxy, I started tracing what's happening when IE calls for ajax; here's what Charles says: { totalPanier: 0,00amp;euro;, articles: [ { id: 8a8b8d632481567f01248156fac90009, prixAffiche: 0,00, quantite: 0, libelle: Carte BEST CADEAUX à montant variable, montantRemise: , prixTotal: 00,00amp;euro; }, { id: 8a8b8d632481567f0124815706910010, prixAffiche: 80,00, quantite: 0, libelle: Carte BEST CADEAUX 80 Euros, montantRemise: , prixTotal: 00,00amp;euro; }, { id: 8a8b8d632481567f012481570578000f, prixAffiche: 50,00, quantite: 0, libelle: Carte BEST CADEAUX 50 Euros, montantRemise: , prixTotal: 00,00amp;euro; }, { id: 8a8b8d632481567f012481570549000e, prixAffiche: 30,00, quantite: 0, libelle: Carte BEST CADEAUX 30 Euros, montantRemise: , prixTotal: 00,00amp;euro; }, { id: 8a8b8d632481567f012481570364000d, prixAffiche: 15,00, quantite: 0, libelle: Carte BEST CADEAUX 15 Euros, montantRemise: , prixTotal: 00,00amp;euro; } ]} That's ... JSON, perfectlly formated. Here's for the headers now: HTTP/1.1 200 OK Server Apache-Coyote/1.1 X-Powered-ByServlet 2.4; JBoss-4.0.3SP1 (build: CVSTag=JBoss_4_0_3_SP1 date=200510231054)/Tomcat-5.5 Content-Typeapplication/json;charset=UTF-8 Content-Length 1221 DateTue, 08 Dec 2009 18:41:05 GMT Woot! What the hell am I missing ? Thanks for the great help you could (and I hope, will) provide !!!
Re: [jQuery] Tips and tricks for fixing memory leaks
Minifying your code and removing unused code are good ways to reduce your initial memory footprint, but they won't have any effect on memory leaks. A memory leak is when the browser's memory use continues to increase, either as as you interact with a page or when you reload the page or navigate to another page. (I don't make the distinction between leaks and pseudo-leaks that Olivier mentioned. I've seen that terminology in the famous IE memory leak paper, but I find it hopelessly confusing. It's easier for me to just say what is actually happening: the page leaks memory as you interact with it or the page leaks memory when you reload or exit from it.) -Mike On Mon, Dec 7, 2009 at 7:32 AM, Carlos De Oliveira cdeolive...@grupozoom.com wrote: try to use *.min *codes (minimized versions of .js), also may remove Jquery UI sections from *JQuery.ui.min.js*. -- Carlos De Oliveira Departamento De Sistemas Consultor Senior 0426 517 73 01 0212 204 69 60 cdeolive...@grupozoom.com card...@gmail.com
Re: [jQuery] Re: Document undefined error
I'd like to add one thing to Scott's very informative reply... You may wonder, But I wasn't trying to run the script from the Windows command prompt! I pasted it into the IE address bar and that's when I was prompted to open or save it. Like the doctor said, If that hurts, don't do it. The behavior you saw is what IE does with *any* .js file URL you enter into the address bar. It doesn't have anything to do specifically with jQuery, and it's not the way jQuery or similar scripts would normally be loaded. The normal use for a script like jQuery is to include its URL in a script tag in an HTML document. When you open that HTML document in a browser, it loads the JavaScript code from the .js file within the normal context of a web page. It *is* possible to run a .js file as if it were a Windows application - either from the command line or with the accidental method you stumbled across. But that doesn't run the JavaScript code in a browser environment. It runs it under the Windows Scripting Host, which doesn't have browser objects like 'document', but does have a variety of Windows-specific objects. So this requires JavaScript code that was written specifically to run under Windows Scripting Host, not a browser-oriented script like jQuery. -Mike On Mon, Dec 7, 2009 at 10:15 AM, Scott Sauyet scott.sau...@gmail.comwrote: On Dec 7, 11:49 am, Firefox barrie.wh...@gmail.com wrote: I have recently been tasked with making sure the following script works with our environment. http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js [ ... ] That script is the latest release of the jQuery library. It doesn't do any work you care about by itself. It needs to be included in a web page to do anything useful. [1] However when running under IE (any version) I first get asked if I want to open/save/cancel the file, when choosing open I get the following error [ ... ] Error: 'document' is undefined This is not a script that can simply run from the command line. Windows will by default try to open this up as an executable script, but will not supply a browser environment that includes the global variable document, hence the error. You need to look at some introductory documentation to see what jQuery is for and how to use it. I would suggest starting with this: http://docs.jquery.com/How_jQuery_Works Any place in that tutorial that has a script tag with this: src=jquery.js you can substitute: src=http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/ jquery.min.js That should get you going. But the notion of testing whether it will work in your environment is pretty fuzzy. jQuery is well established and works for many people working in the vast majority of commonly-seen browsers over a great many tasks, but without additional code to actually do something with it, it's not clear what it would meant that it works. Good luck, -- Scott [1] This is an oversimplification, but is enough for this discussion.
Re: [jQuery] Ajax calls with jQuery
We need to see something closer to a real-life example. There's a bit too much missing in the code you posted. In particular, what does the page look like when it actually has more than one row from your DB in it? I can't tell which part of your HTML would be repeated per row. What is the exact HTML structure of a single row in the page? I assume you are free to change the generated HTML any you want, is that right? Also, I assume the a tag that calls click_function is just test code that won't be in your real page? About how many rows would typically be listed in a single page? As it sits, all I can suggest is a few things: 1) You should probably use a jQuery event handler instead of the onclick handler. 2) Instead of hard coded element IDs in your $.post, you'll need to do a bit of DOM traversing or some such to get to the element values you need. 3) To make that DOM traversing easier, it's a good idea to wrap each row in its own container element such as a DIV. Or you may want to use a table to display the row data (it does sound like tabular data after all). In that case the table's TR elements would serve that purpose. -Mike On Sun, Dec 6, 2009 at 4:36 AM, factoringcompare.com firstfacto...@googlemail.com wrote: Hi Guys’ I have hit a complete brick wall on this one. I have an ASP page that lists out a DB into 3 columns. Each row has a unique ID number. When the user updates a checkbox I would like to fire off an AJAX update to my DB. I have made the page that’s ready to receive the unique ID Number and updated my DB but I can’t get the unique ID number to the update page using Jquery. I have the following script working to update a specific record. I just can take it to the next level so that it will pick up individual ID’s and post them across. html head title/title script language=javascript src=Sitefiles-N/js/ jquery-1.3.2.min.js/script script language=javascript function click_function() { $.post(Sitefiles-N/jquery.formwizard-0.9.8/QuoteProcessor3.asp, {QuoteNo: $(#QuoteNo).val(), accept: $(#accept).val() }, function(responseText){$(#show_stuff).html(responseText)}); } /script /head body labelEnter your name:/label input name=QuoteNo type=text id=QuoteNo value=83 / br /br / labelaccept:/label input name=accept type=text id=accept value=-1 / br /br / pa href=# onclick=click_function();click this/a /p input type=button value=click this to make Ajax call onclick=click_function(); div id=show_stuff/div /body /html
Re: [jQuery] Re: Document undefined error
One more comment... If you can tell us exactly what you mean by I have recently been tasked with making sure the following script works with our environment, then we can probably help you with more specifics. Do you have web developers who will be using jQuery in your web pages? Or what is it that you'd like to know specifically? -Mike On Mon, Dec 7, 2009 at 11:11 AM, Michael Geary m...@mg.to wrote: I'd like to add one thing to Scott's very informative reply... You may wonder, But I wasn't trying to run the script from the Windows command prompt! I pasted it into the IE address bar and that's when I was prompted to open or save it. Like the doctor said, If that hurts, don't do it. The behavior you saw is what IE does with *any* .js file URL you enter into the address bar. It doesn't have anything to do specifically with jQuery, and it's not the way jQuery or similar scripts would normally be loaded. The normal use for a script like jQuery is to include its URL in a script tag in an HTML document. When you open that HTML document in a browser, it loads the JavaScript code from the .js file within the normal context of a web page. It *is* possible to run a .js file as if it were a Windows application - either from the command line or with the accidental method you stumbled across. But that doesn't run the JavaScript code in a browser environment. It runs it under the Windows Scripting Host, which doesn't have browser objects like 'document', but does have a variety of Windows-specific objects. So this requires JavaScript code that was written specifically to run under Windows Scripting Host, not a browser-oriented script like jQuery. -Mike On Mon, Dec 7, 2009 at 10:15 AM, Scott Sauyet scott.sau...@gmail.comwrote: On Dec 7, 11:49 am, Firefox barrie.wh...@gmail.com wrote: I have recently been tasked with making sure the following script works with our environment. http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js [ ... ] That script is the latest release of the jQuery library. It doesn't do any work you care about by itself. It needs to be included in a web page to do anything useful. [1] However when running under IE (any version) I first get asked if I want to open/save/cancel the file, when choosing open I get the following error [ ... ] Error: 'document' is undefined This is not a script that can simply run from the command line. Windows will by default try to open this up as an executable script, but will not supply a browser environment that includes the global variable document, hence the error. You need to look at some introductory documentation to see what jQuery is for and how to use it. I would suggest starting with this: http://docs.jquery.com/How_jQuery_Works Any place in that tutorial that has a script tag with this: src=jquery.js you can substitute: src=http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/ jquery.min.js That should get you going. But the notion of testing whether it will work in your environment is pretty fuzzy. jQuery is well established and works for many people working in the vast majority of commonly-seen browsers over a great many tasks, but without additional code to actually do something with it, it's not clear what it would meant that it works. Good luck, -- Scott [1] This is an oversimplification, but is enough for this discussion.
Re: [jQuery] Re: Very Strange !!! The same HTML code works well, but append() it not !!!
Don't be so sure about that. I thought the same thing you did, but we were both wrong: you *can* write multline strings in JavaScript. Backslash-newline works inside a string just like it does outside one in normal JS code. You do have to be careful; there can't be any whitespace after the backslash. That would give you an unterminated string literal error. That said, I have no idea what the actual problem is. I would take a look at it if there were a test page I could load (hint to Eric!). -Mike On Mon, Dec 7, 2009 at 11:19 PM, seasoup seas...@gmail.com wrote: javascript cant read strings over line breaks. $(#tb_video).append(' \ tr \ tdinput type=checkbox //td \ td' + d.name + '/td \ td' + d.len + '/td \ td' + d.size + '/td \ tr '); must be $(#tb_video).append('tr'+ 'tdinput type=checkbox //td'+ 'td' + d.name + '/td'+ 'td' + d.len + '/td'+ 'td' + d.size + '/td'+ 'tr '); On Dec 7, 6:30 pm, Eric Zhong ericiszhongwen...@gmail.com wrote: html head script src=http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/ jquery.js/script SCRIPT LANGUAGE=JavaScript !-- $(function(){ // /* var html_video = ' \ table id=tb_all width=724px \ tr \ td valign=top \ table id=tb_video class=tb_width \ tr class=tb_head \ tdnbsp/td \ tdfilename/td \ tdlen(s)/td \ tdsize(KB)/td \ /tr \ /table \ /td \ /tr \ /table' $(body).append( html_video ); var data = [ {name: 1, len: 432, size: 321}, {name: 2, len: 54543, size: 432}, {name: 3, len: 3243, size: 432}, {name: 4, len: 543, size: 432}, {name: 5, len: 543, size: 654}, {name: 6, len: 654, size: 654}, {name: 7, len: 765, size: 654}, {name: 8, len: 765, size: 765}, {name: 9, len: 53, size: 654} ]; var a = data; if ( a != null ){ for(var i=0; ia.length; i++){ var d = a[i]; $(#tb_video).append(' \ tr \ tdinput type=checkbox //td \ td' + d.name + '/td \ td' + d.len + '/td \ td' + d.size + '/td \ tr '); } } $(#tb_video).closest(tr).append(' \ td width=80px align=center style=vertical-align:top \ input id=pl_bt_up type=button value=↑ / \ input id=pl_bt_down type=button value=↓ / \ /td '); // */ $(#pl_bt_up).click(function() { var $all = $(#tb_video tr); var $trs = $(#tb_video tr:has(input:checked)); if( $all.index($trs.get(0)) != 1 ){ $trs.each(function(){ $(this).prev().before($(this)); }); } }); $(#pl_bt_down).click(function() { var $all = $(#tb_video tr); var $trs = $(#tb_video tr:has(input:checked)); if( $all.index( $trs.get($trs.length-1) ) != $all.length-1 ){ for( i = $trs.length-1; i=0; i-- ) { var $item = $( $trs.get(i) );
Re: [jQuery] Re: Save javascript variable via jquery
Your first example doesn't work because getJSON doesn't return the JSON data as its return value; it *calls a function* and passes the data as an argument to that function. Remember that getJSON is asynchronous. The call to getJSON returns before the data is even downloaded. Any time you have asynchronous operations in JavaScript, you'll do them through a callback function like this. (There is a synchronous option for getJSON, but you really don't want to use it - it causes serious problems.) Your getJSON callback function *could* store the data in a variable in the parent page: $.getJSON( url, function( data ) { top.myData = data; }); But there's a flaw in this approach. How does the code in the parent page know when the data is ready? It doesn't. Instead, you should provide a function in the parent page and *call* it from the getJSON callback: $.getJSON( url, function( data ) { top.dataIsReady( data ); }); where the parent page has this global function: function dataIsReady( data ) { // ... } In fact, if calling that function is the only thing your callback does, you could just use the function directly as the callback: $.getJSON( url, top.dataIsReady ); -Mike On Fri, Dec 4, 2009 at 8:29 AM, m.ugues m.ug...@gmail.com wrote: I tried this way: http://pastie.org/727632 The div is appendend but the javascript declaration not: Any idea? Kind regards Massimo On 4 Dic, 16:13, m.ugues m.ug...@gmail.com wrote: Hallo all. I would like to save the response of an AJAX call in a variable declared in the document ready in parent page. Imagine this piece of code http://pastie.org/727450 The document ready lives in an iframe so I would like to save in the parent page the var myVariable, not to load it every time with a server-side call. Is there any way to inject in the parent the javascript variable? Kind regards Massimo
Re: [jQuery] Re: Can I use $(document).ready(function(){ in the same page more than a once time in the same page
It really makes little difference at all. jQuery makes an array of all your ready callbacks, and when the document is ready it loops through that array and calls each function. So other than that tiny bit of overhead, the net effect is exactly the same whether you put all the code in one ready function or have several different ones. If there is more than one, they will be called in the same order that the $(document).ready() calls were executed. -Mike On Fri, Dec 4, 2009 at 7:35 AM, coolf jm.neut...@gmail.com wrote: ok, thanks for the response. But what is the best, is it good to have more than a documen.ready ? it doesn't bring problems? On 4 dic, 11:33, Andreas Möller localhe...@l8m.de wrote: Hello i'm new here, Is it posible? Yes, it is. Best regards, Andreas
Re: [jQuery] IF. What am I doing wrong?
How do you know the 'if' isn't working correctly? It doesn't play? At this point we don't know if the problem is with the 'if' statement itself or with the code inside it. Have you put another alert *inside* the if statement to verify whether it actually gets there or not? The 'if' statement is pretty fundamental to JavaScript. It doesn't fail. So if something is going wrong, then likely either the value of 'cookie' is not quite what you expect, or the code inside the if isn't working. Could the cookie value have some whitespace in it? You wouldn't see that in an alert. You can check it with things like this: alert( cookie.length ); alert( '{' + cookie + '}' ); -Mike On Thu, Dec 3, 2009 at 4:46 AM, shapper mdmo...@gmail.com wrote: Hello, I have the following code: alert($.cookies.get(WCA.Player)); var cookie = $.cookies.get(WCA.Player); if (cookie == null || cookie == 'Play') { $(#JPlayer).play(); } The alert gives me the correct value which is null or 'Play' but the if is not working correctly. Am I doing something wrong? Thanks, Miguel
Re: [jQuery] jQuery gives error on page in IE after hover.
You're trying to use negative padding, but there is no such thing in CSS: http://www.google.com/search?q=negative+padding;http://www.google.com/search?q=%22negative+padding%22 Can you use negative margin instead, or some other technique? -Mike On Thu, Dec 3, 2009 at 4:51 AM, Duncan Krebbers duncankrebb...@hotmail.comwrote: I'm using a simple jQuery hover script on my page to animate menubuttons 15px to the right on a hover. They go back at a mouse-out. The jQuery version I'm using is 1.3.2 from the Google API's. The script, located in the head of my index.php, is down here. $(document).ready(function(){ $('.navitem').hover( function () { $(this).animate({paddingLeft:10px},250); }, function () { $(this).animate({paddingLeft:-10px},250); }); }); In FF and Chrome it works nice, but in IE after a hover the statusbar shows me error in page and the hovers don't work anymore. The error-details show me this (translated from Dutch): Message: Invalid Argument Line: 19 Character: 35190 Code: 0 URI: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js Does anyone know what I'm doing wrong? Because I think it's a problem with my side of the script.
Re: [jQuery] Re: Problem with plugins
Glad to help. It's nothing specific to jQuery, of course. Here's a simplified test case: var Test = function() {}; Test.prototype.foo = function() { alert('bar'); }; var test = new Test; test.foo(); // alerts 'bar' var Test = function() {}; var test = new Test; test.foo(); // TypeError: test.foo is not a function That's basically the same scenario you ran into with the two jQuerys - it's just easier to see the problem here. -Mike On Wed, Dec 2, 2009 at 3:27 AM, Paulodemoc paulode...@gmail.com wrote: Omg, I can't believe that was the problem You guys are the best :P I didn't know this particularity about jQuery... it's logical though Thanks you all for the help and your time. Att. Paulo Henrique ;) On Dec 2, 4:09 am, Michael Geary m...@mg.to wrote: Don't feel bad. You made it easy for me. Since you'd already done some investigating and ruled out a number of possibilities, all I had to do was look at the one or two things you might have missed! :-) On a more serious note, this thread is a great example of why we keep asking people to post a link to a test page. Without the test page, we were just taking wild guesses. Once the test page was posted, all it took was a couple of us taking a quick look at it, and bingo! -Mike On Tue, Dec 1, 2009 at 2:45 PM, Scott Sauyet scott.sau...@gmail.com wrote: On Dec 1, 5:31 pm, Michael Geary m...@mg.to wrote: Paulo, you're loading jQuery twice. First you load jQuery, then you load your plugins, then you load jQuery again. That second load of jQuery wipes out the original jQuery and all its plugins. Do a View Source on your page with the sort photos link, and search for: And I missed that? D'Oh! :-) -- Scott
Re: [jQuery] error essage: css is not a function
The jQuery object - the return value from $(whatever) - is an array-like object with .length and [0] etc. properties. You don't need to call .get() on it unless you need an actual JavaScript Array object, which is rare. The *elements* of the jQuery object - or the elements of the Array that .get() returns, are plain HTML elements - DOM nodes. They are not jQuery objects themselves. They have DOM methods and properties, not jQuery methods. You can always wrap a DOM node in a jQuery object with $(theDomNode). You can use a for loop just like the one you have, directly on a jQuery object without calling .get(). Or you can use jQuery's .each() method, which is often cleaner. One way to write your loop would be like this: $('.resizable').each( function( i, box ) { console.log( box.id + ': left=' + $(box).css('left') ); }); In this code, 'box' is the same as 'boxes[i]' in your for loop. Note the difference between box.id - referencing a property of the DOM node directly - and $(box).css() - wrapping the DOM node inside another jQuery object and then calling a jQuery method on that object. -Mike On Wed, Dec 2, 2009 at 11:34 AM, hsfrey hsf...@gmail.com wrote: I'm using the following code: var boxes = $('.resizable').get(); // get divs as array for (var i=0; iboxes.length; i++ ) { console.log(boxes[i].id+': left='+boxes[i].css('left')); } I get this error message from Firebug: boxes[i].css is not a function [Break on this error] { safelog($boxes[i].id+': left='+$boxes[i].css('left'));\r \n I have used similar code before, but for an individual item, not an array. For instance, This works fine: var sel1=$('#'+b1); var c1x = parseInt(sel1.css('left')); Does this simply not work on arrays, or have I made some other error?
Re: [jQuery] Best AJAX transfer method?
JSON is far better for use in JavaScript. It's much easier to access JSON data, since by the time you see it, it's just ordinary JavaScript objects. It's more convenient and faster too. Regarding security, this is data that you're generating on your own server for use in your own website? Then there is no security issue that doesn't already exist just by having JavaScript in your site at all. jQuery does eval your JSON data (or in future versions it uses a function constructor, which amounts to the same thing). But the browser already is parsing and executing all your other JavaScript code - you can think of the JSON data as just one more JavaScript file for security purposes. I'm curious that you find JSON harder to read than XML. Are you looking at JSON text that's all on one line? That *would* be hard to read, but there are tools to pretty-print it. You can paste a JSON string into www.jsonlint.com, or use the excellent JSON viewer that integrates with Fiddler or runs as a standalone app: http://www.fiddler2.com/ http://www.codeplex.com/JsonViewer These are for Windows only, and it looks like you're using Linux, but you probably have a Windows VM or box on hand for IE testing anyway, so you can run those there. Fiddler is very very very nice to inspecting your HTTP sessions, and when you select a JSON download in the Fiddler list you can see a nice tree-structured view of your JSON data. Or maybe there is a good JSON formatter/viewer for Linux. Hope that helps, give a shout back with any questions or concerns and I'll be happy to kick them around with you. -Mike On Wed, Dec 2, 2009 at 3:04 PM, ScottChiefBaker scott.ba...@gmail.comwrote: For server side scripts I'm wondering if there is an inherent advantage to returning XML vs JSON (or vice versa). I've always returned XML because I find it's more human readable, and thus I can verify the data better. I'm talking strict data structures (arrays,lists, etc), no HTML. I would imagine there is a performance penalty for parsing the XML into a data structure vs JSON. There could potentially be security problems parsing JSON? What do (you) the experts think?
Re: [jQuery] Re: Problem with plugins
Paulo, you're loading jQuery twice. First you load jQuery, then you load your plugins, then you load jQuery again. That second load of jQuery wipes out the original jQuery and all its plugins. Do a View Source on your page with the sort photos link, and search for: script You will see the extra copy of jQuery right away. Take that out and your plugins should work. -Mike On Tue, Dec 1, 2009 at 3:30 AM, Paulodemoc paulode...@gmail.com wrote: Hey Michael :) ALl jQuery commands are working just fine. When I try the commands you told me, it outputs 1.3 I have a test page here: http://jquery.creandi.eu You can login with user: admin and password: 123456 On the menu on the left, click on mannequins, and then click on Insert photos, on the listing that follows... It will take you to a page with the photos of the mannequin, there, there's a link on the top sort photos click on it. This is one of the pages where i use plugins and they don't work... Just navigate around and check firebug console. Some pages are with php errors because they are incomplete, i haven't uploaded the most recent controllers... On Nov 30, 2:59 pm, Michael Geary m...@mg.to wrote: Could it be that you are also loading prototype.js or some other library that redefines the $() function? Does it find plugin methods if you use jQuery(...)... instead of $(...)...? Do the built-in jQuery methods show up? What does it display if you enter each of these lines into the Firebug console: $().jquery jQuery().jquery Sooner or later you may have to post that test page. Sooner would be better, save us all a lot of work. :-) -Mike On Mon, Nov 30, 2009 at 7:48 AM, Paulodemoc paulode...@gmail.com wrote: The plugins are being loaded. When I open the source code and click on the js url, it opens alright But when I call the command: $(selector).pluginFunction({options}); An error message appears saying that pluginFunction is not a function... on ALL plugins... On Nov 27, 12:45 pm, Brett Ritter swift...@swiftone.org wrote: On Mon, Nov 23, 2009 at 5:55 AM,Paulodemocpaulode...@gmail.com wrote: Its the javasscript on the php page, and the only php there is to output the urls, and these urls are being printed correctly The url doesn't affect the understanding of the rest of the code... If your plugins aren't loading, those URLs are quite likely involved. We have no way of knowing if they are indeed working since we don't see the output. Try sending the HTML the browser is getting. -- Brett Ritter / SwiftOne swift...@swiftone.org
Re: [jQuery] Re: Problem with plugins
Don't feel bad. You made it easy for me. Since you'd already done some investigating and ruled out a number of possibilities, all I had to do was look at the one or two things you might have missed! :-) On a more serious note, this thread is a great example of why we keep asking people to post a link to a test page. Without the test page, we were just taking wild guesses. Once the test page was posted, all it took was a couple of us taking a quick look at it, and bingo! -Mike On Tue, Dec 1, 2009 at 2:45 PM, Scott Sauyet scott.sau...@gmail.com wrote: On Dec 1, 5:31 pm, Michael Geary m...@mg.to wrote: Paulo, you're loading jQuery twice. First you load jQuery, then you load your plugins, then you load jQuery again. That second load of jQuery wipes out the original jQuery and all its plugins. Do a View Source on your page with the sort photos link, and search for: And I missed that? D'Oh! :-) -- Scott
Re: [jQuery] Selector Help
That's a nice solution. Let's make it easier to follow with some indentation: $('a.filter').click(function() { $(this) .closest('ul') .children() .removeClass('active') .end() .end() .closest('li') .addClass('active'); }); The basic indentation rules we're following here are: * Put each method call on a line by itself, with the . at the beginning of the line. (You can put more than one call on the same line, but only when they don't change the selection.) * Where a method creates the jQuery object or changes its element selection, indent the next line. * Where .end() is called, un-indent that line. You could even go overboard on readability and add the missing .end() calls at the very end: $('a.filter').click(function() { $(this) .closest('ul') .children() .removeClass('active') .end() .end() .closest('li') .addClass('active') .end() .end(); }); Now this looks a lot like the way we indent blocks in JavaScript and other languages. Each .closest() or .children() call is matched up with its own .end() call - as is the initial $(this) - and the indentation indicates the code affected by each of those calls. It's more customary to omit those trailing.end() calls, but with or without them, the indentation is a great help in visualizing the structure of a complex chain. -Mike On Sun, Nov 29, 2009 at 11:39 PM, Michel Belleville michel.bellevi...@gmail.com wrote: Even better : $('a.filter').click(function() { $(this).closest('ul').children().removeClass('active').end().end().closest('li').addClass('active'); }); Michel Belleville 2009/11/29 Mauricio (Maujor) Samy Silva css.mau...@gmail.com Try this: $('a.filter').click(function(){ $(this).parent().siblings('li').removeClass('active'); $(this).parent('li').addClass('active'); }); Maurício -Mensagem Original- *De:* Charlie charlie...@gmail.com *Para:* jquery-en@googlegroups.com *Enviada em:* domingo, 29 de novembro de 2009 03:56 *Assunto:* Re: [jQuery] Selector Help ... Dave Maharaj :: WidePixels.com wrote: How would I go about adding class to the li in this set up? lia href=# class=filterspanall/span/a/li lia href=# class=filterspansome/span/a/li lia href=# class=filterspannone/span/a/li ...
Re: [jQuery] Re: Problem with plugins
Could it be that you are also loading prototype.js or some other library that redefines the $() function? Does it find plugin methods if you use jQuery(...)... instead of $(...)...? Do the built-in jQuery methods show up? What does it display if you enter each of these lines into the Firebug console: $().jquery jQuery().jquery Sooner or later you may have to post that test page. Sooner would be better, save us all a lot of work. :-) -Mike On Mon, Nov 30, 2009 at 7:48 AM, Paulodemoc paulode...@gmail.com wrote: The plugins are being loaded. When I open the source code and click on the js url, it opens alright But when I call the command: $(selector).pluginFunction({options}); An error message appears saying that pluginFunction is not a function... on ALL plugins... On Nov 27, 12:45 pm, Brett Ritter swift...@swiftone.org wrote: On Mon, Nov 23, 2009 at 5:55 AM,Paulodemocpaulode...@gmail.com wrote: Its the javasscript on the php page, and the only php there is to output the urls, and these urls are being printed correctly The url doesn't affect the understanding of the rest of the code... If your plugins aren't loading, those URLs are quite likely involved. We have no way of knowing if they are indeed working since we don't see the output. Try sending the HTML the browser is getting. -- Brett Ritter / SwiftOne swift...@swiftone.org
Re: [jQuery] Jquery specialist for hire
There was a pretty good example posted here a few days ago that may have all the code you need: http://groups.google.com/group/jquery-en/msg/546500f34de23d79 The problem that Darjana was asking about shouldn't apply in your case; just be sure to use the full absolute URL to your Server 2. You'll need to fill in the specifics, but you can see where the jQuery code sends some data up to the server, the PHP code on the server reads that data and sends back a JSON response (actually JSONP - that's how you work around the cross-domain issue), and the jQuery code reads that data that the server sent. -Mike On Mon, Nov 30, 2009 at 8:40 AM, Bjorn Symister bjorn@gmail.com wrote: I have posted on craigslist with no luck, so I will post here. I am seeking a specific jQuery solution. Please name your rate and I can pay through paypal. I needed this solution last week :) My Scenario, 2 Servers, 2 Scripts, 1 Form. Form collects Email addresses. This form is on Server 1: my client end server. I can only place html,javascript,css on this server. No server side scripts. On Server 2: I will have a php script that will receive the data or use jQuery getJSON to get it.. Problem: I need to handle the submission of the data without refreshing the entire page (need Ajax). Problem is however using Ajax, you cannot send data to another domain (So I’ve read). Options are using an iFrame or JSON. I would prefer JSON, however at this point, I just need a solution. If you know how to do this, please just name your fixed rate to provide the scripts and I’ll take it from there. Thanks, Bjorn
Re: [jQuery] Re: $.getScript results in two requests!
Glad you tracked that down - pretty nasty bug in Firebug! Just curious, 1.3 is still a pretty old version. Any reason not to use the latest Firebug 1.4.5? -Mike On Fri, Nov 27, 2009 at 2:43 AM, Eric ikeah...@gmail.com wrote: Hey there, Thanks for your answers. Sorry I didn't reply earlier, been pretty busy. It turned out the problem was caused by an old version of Firebug ( http://code.google.com/p/fbug/issues/detail?id=928 ). I am now using Firebug 1.3 on Firefox 3.5, where the bug is fixed. Eric On 25 Nov., 17:03, donb falconwatc...@comcast.net wrote: Be very certain you don't accidentally bind a click function twice somehow. Assuming, that is, a click initiates the action. Setting a Firebug breakpoint on entry to the repeated code, then inspecting the Stack panel to see how you got there each time, will probably reveal how this occurs. On Nov 24, 9:50 am, Eric ikeah...@gmail.com wrote: Hey there, A $.getScript() call I am making results in two seperate requests to the server. Any chance I can avoid that? Here are the headers: GET server.file?param1=param2 HTTP/1.1 Host: server User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; de; rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20 Accept: text/javascript, application/javascript, */* Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive X-Requested-With: XMLHttpRequest Referer:http://server/indexfile.html Cookie: (Cookie Contents) Followed by... GET server.file?param1=param2 HTTP/1.1 Host: server User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; de; rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20 Accept: text/xml,application/xml,application/xhtml+xml,text/ html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Cookie: (Cookie Contents) The web server runs IIS6. Thanks for your help Eric
Re: [jQuery] $.ajax and $.get
If you would post a link to a test page, I'm sure someone can tell you what's wrong. Without that, we have to start playing 20 Questions. :-) First questions: 1) What is the response from the server in both cases? 2) Install Fiddler2 [*] and have it log the session. What does it show? -Mike [*]: http://www.fiddler2.com/ On Fri, Nov 27, 2009 at 5:50 AM, Wayne Tong wei.tong.n...@gmail.com wrote: Hi Guys, Need some help on $.get or $.ajax, I have the following code that will send request to server then get either JSON or XML data back, but it seems only working in IE8, not working in Firefox 3.5, In IE8, it returns: data: [object Object] textStatus: success something: undefined in Firefox 3.5 it returns: XMLHttpRequest: [object XMLHttpRequest] textStatus: parsererror errorThrown: undefined Wonder why am I getting parsererror here? $.ajax({ type: GET, url: http://192.168.213.85:8080/solr/select?q=northwt=jsonindent=onqt=standard , dataType: json, success: function (data, textStatus, something) { alert(data: +data+\n+textStatus: +textStatus+\n+something: +something); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest: +XMLHttpRequest+\n+textStatus: +textStatus+\n+errorThrown: +errorThrown); } }); Regards, W
Re: [jQuery] IE balking at .siblings() - says 'Object does not support this property or method'
The first thing that caught my eye looking at your code is the missing var on this line: lg_pic = $(this).siblings('.lg_pic_name').html(); Surely you don't want to be creating a global variable here? It should be: var lg_pic = $(this).siblings('.lg_pic_name').html(); It's even possible that this will fix your problem. Do you have an element in your page with id=lg_pic? If so, this will fix it. For every element ID in your page, IE creates a *read-only* property on the window object with that name. So if you have an element with id=lg_pic, then there is a window.lg_pic property that is read-only. When you try to store a value into that property it will fail. If that doesn't turn out to be it, can you please post a link to a test page? It's awfully hard to troubleshoot a code snippet without seeing the actual error in a live running page. -Mike On Thu, Nov 26, 2009 at 12:47 PM, Getzel far...@gmail.com wrote: BH I created a slider of thumbnail images. I write the image filepaths directly into the HTML using PHP, so instead of using expandos I placed a hidden div after each image containing the file name of the large version to be shown onclick. Works fine in FF and Chrome. IE stops at the first line in the function, at .siblings(). It throws an error saying 'Object does not support this property or method.' $('.pic_listing img').click(function(){ // Set the a variable with large image associated with the thumb lg_pic = $(this).siblings('.lg_pic_name').html(); // If it is not currently displayed if($('#lg_pic_src').attr('src') != path+lg_pic){ //Hide Old Image $('#lg_pic_src').css('display','none'); //Replace it $('#lg_pic_src').attr('src',path+lg_pic); // Display Loader img $('#loader').css('z-index',1); // Once its loaded, Hide Loader and FadeIn the new image $('#lg_pic_src').load(function () { $('#loader').css('z-index',-1); $('#lg_pic_src').fadeIn(); }); } }); Anyone have any thoughts as to why IE would throw an error? Other functions defined in the same file work fine. Thanks, Getzel
Re: [jQuery] Comparing or checking for a specific sub class?
I think the method you're looking for is .not(): http://docs.jquery.com/Traversing/not Also, there is a shortcut for your mouseenter/mouseleave pattern called .hover(): http://docs.jquery.com/Events/hover If you look at the source code for .hover(), you can see that it is literally a wrapper for the two mouse events: hover: function(fnOver, fnOut) { return this.mouseenter(fnOver).mouseleave(fnOut); }, One other concern: It is invalid HTML to have a DIV element inside an A element. DIV is a block-level element and A is an inline element. You cannot have a block-level element inside an inline element. It will probably work in most browsers, but it's possible that some browser may decide to rearrange your elements to create a valid result. Setting that aside, your code might end up looking like: script type=text/javascript $(document).ready(function() { $('.page_item').not('.current_page_item').hover( function() { $(this).children('a').children('div').fadeIn(0); }, function() { $(this).children('a').children('div').fadeOut(200); } ); }); /script You could also (again ignoring the invalid HTML problem) simplify the .children bit like this: $(this).find('adiv').fadeIn (or fadeOut) There's no advantage to that other than brevity, so if you prefer the .children().children() approach that's fine too. -Mike On Thu, Nov 26, 2009 at 2:39 PM, Janmansilver jan.poul...@gmail.com wrote: I have a menu looking like this: li class=page_item current_page_item.../li li class=page_item.../li li class=page_item.../li and so on... I then have a mouseenter function that highlights/de-highlights the various menu items, but I would like to not having it affect the item with the extra class current_page_item. How do I solve this? my current code: script type=text/javascript $(document).ready(function() { $('.page_item').mouseenter(function(e) { $(this).children('a').children('div').fadeIn(0); }).mouseleave(function(e) { $(this).children('a').children('div').fadeOut(200); }); }); /script
Re: [jQuery] Using add/remove class vs. show hide for a swap out section?
It would really help if you could post a link to a test page instead of posting code excerpts. For example, I don't see any HTML code that has id=link-about and your other links. Is that missing from your page, or did you just omit it in the code you posted? Are the LI elements supposed to be those links? In any case, since I can't help you get the code working, at least I can help you simplify it. Let me assume that those LI elements are your links. Then I would change them to this: ul li class=clicklink id=link-about # About /li li class=clicklink id=link-work # Work /li li class=clicklink id=link-ramblings # Ramblings /li li class=clicklink id=link-contact # Contact /li /ul and I would change your JavaScript - it's not Java, please :-) to: $(document).ready( function() { $('li.clicklink').click( function() { $('div.content').addClass('hide'); $( '#' + this.id.split('-')[1] ).removeClass('hide'); }); }); If that .content class is also used on other elements in your page, then I would another classname to your four content targets and change the $('div.content') to use that classname instead. -Mike On Tue, Nov 24, 2009 at 7:20 PM, rorourke r...@pixelbleed.net wrote: I'm mostly a CSS/HTML guy, so delving into jQuery is a bit more then my normal task list would contain, but I'm happy to suck up any knowledge that you may be able to impart. Here is my scenario: I have four div's each has a different class in additon to the .content class (which controls font and link styles for each of them), .about, . work, .ramblings, .contact. Each of these classes is by default shown. But I've applied a class of .hide to all the ones after .about, which is the default shown. What I have seems to work for the first link clicked after page load, but after that nothing is happening. I would like, whenever a link is clicked to show that sections div and hide the other three. I never want more then one section showing. This adding classes business or even just using the .hide() .show() functions doesn't necessarily work because the java for the ID has to handle every situation on any given click. Markup looks like this: ul li # About /li li # Work /li li # Ramblings /li li # Contact /li /ul div class=content about pYada/p /div div class=content work hide pYada/p /div div class=content ramblings hide pYada/p /div div class=content contact hide pYada/p /div Java looks like this: $(document).ready(function() { $('#link-about').click(function(){ $('.about').removeClass(hide); $('.work').addClass(hide); $('.ramblings').addClass(hide); $('.contact').addClass(hide); }); $('#link-work').click(function(){ $('.work').removeClass(hide); $('.about').addClass(hide); $('.ramblings').addClass(hide); $('.contact').addClass(hide); }); $('#link-ramblings').click(function(){ $('.about').addClass(hide); $('.work').addClass(hide); $('.ramblings').addClass(hide); $('.contact').addClass(hide); }); $('#link-contact').click(function(){ $('.about').addClass(hide); $('.work').addClass(hide); $('.ramblings').addClass(hide); $('.contact').removeClass(hide); }); }); -- View this message in context: http://old.nabble.com/Using-add-remove-class-vs.-show-hide-for-a-swap-out-section--tp26506957s27240p26506957.html Sent from the jQuery General Discussion mailing list archive at Nabble.com.
Re: [jQuery] Closure/scope
The problem is in your setTimeout() call. When you pass a string argument to setTimeout(), that string is evaluated *in the global context*. Instead, pass a function to setTimeout() and that function will be executed in the scope you expect. Since you're just calling a single function anyway, you can simply give its name to setInterval(): setInterval( crossfade, 5000 ); Or you can pass a function expression to setInterval(): setInterval( function() { // body here }, 5000 ); Also, just to make sure you know, this pattern you're using doesn't wait for a document ready before executing the code: (function($) { // code here })(jQuery); It executes the code here immediately where you place this function. That's perfectly fine and may be what you want. If you want to wait for document ready you can change it to: jQuery(function($) { // code here }); Or if you have some code you want to run immediately and other code that should wait for document ready, you can combine the two approaches: (function($) { // code here runs immediately $(function() { // code here runs when document ready // and can access variables in outer function }); })(jQuery); -Mike On Tue, Nov 24, 2009 at 9:31 AM, Magnificent imightbewrongbutidontthin...@gmail.com wrote: Hello all, I'm trying to group some exisiting top-level functions inside a closure (to avoid polluting the global namespace) but I'm not quite getting it to work. First, all the JS works outside my anonymous function, but once I put it in the anonymous function I get an error of crossfade is not defined. Does anyone see anything completely obvious that I am missing? I'm not quite getting why the the setInterval/crossfade works outside the anonymous function but not inside. Anything inside start() should be able to see vars/functions outside start() and it should all be protected in the closure created by the top-level anonymous function? I'm not trying to access anything *within* crossfade(), I'm just trying to execute it. (function($) { //vars up here that internal functions can access //also using some jquery inside here, so using $ function crossfade() { //body here } //other functions function start() { //body here cInterval = setInterval('crossfade()', 5000); } })(jQuery);
Re: [jQuery] Closure/scope
message.replace( 'setTimeout', 'setInterval' ); :-) On Tue, Nov 24, 2009 at 10:30 AM, Michael Geary m...@mg.to wrote: The problem is in your setTimeout() call. When you pass a string argument to setTimeout(), that string is evaluated *in the global context*. Instead, pass a function to setTimeout() and that function will be executed in the scope you expect. Since you're just calling a single function anyway, you can simply give its name to setInterval(): setInterval( crossfade, 5000 ); Or you can pass a function expression to setInterval(): setInterval( function() { // body here }, 5000 ); Also, just to make sure you know, this pattern you're using doesn't wait for a document ready before executing the code: (function($) { // code here })(jQuery); It executes the code here immediately where you place this function. That's perfectly fine and may be what you want. If you want to wait for document ready you can change it to: jQuery(function($) { // code here }); Or if you have some code you want to run immediately and other code that should wait for document ready, you can combine the two approaches: (function($) { // code here runs immediately $(function() { // code here runs when document ready // and can access variables in outer function }); })(jQuery); -Mike On Tue, Nov 24, 2009 at 9:31 AM, Magnificent imightbewrongbutidontthin...@gmail.com wrote: Hello all, I'm trying to group some exisiting top-level functions inside a closure (to avoid polluting the global namespace) but I'm not quite getting it to work. First, all the JS works outside my anonymous function, but once I put it in the anonymous function I get an error of crossfade is not defined. Does anyone see anything completely obvious that I am missing? I'm not quite getting why the the setInterval/crossfade works outside the anonymous function but not inside. Anything inside start() should be able to see vars/functions outside start() and it should all be protected in the closure created by the top-level anonymous function? I'm not trying to access anything *within* crossfade(), I'm just trying to execute it. (function($) { //vars up here that internal functions can access //also using some jquery inside here, so using $ function crossfade() { //body here } //other functions function start() { //body here cInterval = setInterval('crossfade()', 5000); } })(jQuery);
Re: [jQuery] Re: Closure/scope
That code will certainly do the trick. Because your anonymous function expression simply calls crossfade(), you're essentially doing the same as this: cInterval = window.setInterval( crossfade, 5000 ); Well, there is a subtle difference. Your code below doesn't evaluate the name crossfade until your function expression is called. The code above evaluates the name (but doesn't call the function) at the time the setInterval call is made. But in your code the net effect is the same, since the crossfade function exists at the time this code is run. When you got the missing quotes error, did the error message actually read like this? Error: useless setTimeout call (missing quotes around argument?) That's because you tried to write this code: cInterval = window.setInterval( crossfade(), 5000 ); Here's what that code does, in this order: 1) Calls the crossfade() function immediately. 2) Passes the *return value* of the crossfade() function to setInterval. But crossfade() presumably does not return any value - which is to say that it returns the 'undefined' value, so it's the same as if you'd coded: cInterval = window.setInterval( undefined, 5000 ); And of course that is not what you intended. Note the difference between this code: cInterval = window.setInterval( crossfade(), 5000 ); and this working code: cInterval = window.setInterval( crossfade, 5000 ); When you use a function name without (), you get a reference to the function, which you can call later by using that reference (as setInterval does). When you use () after a function name, you call the function immediately and get its return value. Two other notes... You can leave out the 'window.': cInterval = setInterval( crossfade, 5000 ); And, I assume you have a 'var cInterval;' somewhere inside your outer function? I get nervous when I see a variable assignment without a 'var', unless I know there's a 'var' somewhere in the code for it. Otherwise you'd be unintentionally creating a global variable. -Mike On Tue, Nov 24, 2009 at 11:33 AM, Magnificent imightbewrongbutidontthin...@gmail.com wrote: Hi Mike, Thanks much for your reply. I dropped in an anonymous function and that fixed it: cInterval = window.setInterval(function() { crossfade(); }, 5000); I tried calling crossfade() without quotes, but FF gave me a missing quotes error.
Re: [jQuery] (this[0].ownerDocument || this[0]).createDocumentFragment is not a function
You have too much of this. :-) Remember that every function you call may have a different this. Just because you had a this in an outer function with the value you want, it doesn't mean that some other function you call will have the same this - even if it's nested inside that outer function. Inside $.get() callback, this is definitely not what you expect: http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype So, to fix it, don't use this. There are several ways you can do this (pun intended), but I would suggest using the explicit function arguments that .each() provides: $(.thismonth).each( function( i, monthElement ) { $(monthElement).bind(click, function( e ) { $.get( main.php?action=getEventList, function( data ) { $(#eventdetails).html( data ); $(.event).each( function( i, eventElement ) { $(eventElement).bind( click, function( e ) { $.get( main.php?action=getEvenDetails, function(data) { $(eventElement).html(data); }); }); }); }); }); }); Now everything is in ordinary JavaScript variables (or function parameters, which are the same thing). Unlike this, variables and parameters follow the scope rules that you expect. BTW, in the code you posted, there's an extra close paren in each of your $.get() calls. I assume that was just a typo in the posted code and they are not present in your actual code? -Mike On Tue, Nov 24, 2009 at 6:21 AM, coffeecup gocoffee...@gmail.com wrote: Hello, iam experimenting a little bit with jquery and have encountered the following problem. my project is a calendar which can be browsed and is drawed with ajax and events can be added, when clicking a day of the current month a div pops up which contains the overview of the selected day and lists all events. when clicking on a list item a more detailed info of this event should appear. viewing detailed info should only be possible if logged in. $(.thismonth).each(function(){ // for every day of the month $(this).bind(click, function(e){ // click handler $.get(main.php?action=getEventList),function(data){ // get eventdata of the selected day $(#eventdetails).html(data); // display events of the selected day $(.event).each(function(){ // for each event in the list $(this).bind(click, function(e){ add click handler for event in the list $.get(main.php?action=getEvenDetails),function(data){ // get detailed info if logged in $(this).html(data); // display detailed info }); . so.. if i skip the 2nd $.get request and use just $(this).html ('test'); it works fine, when using get i get the following error (this [0].ownerDocument || this[0]).createDocumentFragment is not a function.
Re: [jQuery] $.getScript results in two requests!
Can you post a link to a test page? Pretty hard to troubleshoot by just looking at the headers. Of course, someone will come along and troubleshoot it from the headers alone and prove me wrong! :-) -Mike On Tue, Nov 24, 2009 at 6:50 AM, Eric ikeah...@gmail.com wrote: Hey there, A $.getScript() call I am making results in two seperate requests to the server. Any chance I can avoid that? Here are the headers: GET server.file?param1=param2 HTTP/1.1 Host: server User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; de; rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20 Accept: text/javascript, application/javascript, */* Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive X-Requested-With: XMLHttpRequest Referer: http://server/indexfile.html Cookie: (Cookie Contents) Followed by... GET server.file?param1=param2 HTTP/1.1 Host: server User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; de; rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20 Accept: text/xml,application/xml,application/xhtml+xml,text/ html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Cookie: (Cookie Contents) The web server runs IIS6. Thanks for your help Eric
Re: [jQuery] Invalid argument jquery.min.1.3.2.js Code 0 IE7,IE8
You found that this line is triggering the error: $(menu_node).css({left:-+total_widths+px}); But you haven't told us what the value of the total_widths variable at this point in the code. The content of that variable will reveal the problem. Also, there are a few things you can do to optimize and simplify your code. But let's get your bug sorted out first. -Mike On Mon, Nov 23, 2009 at 9:06 AM, LuisFernando luiscastill...@gmail.comwrote: Check it out HTML ul lione/li litwo/li lithree/li lifour/li lifive/li /ul CSS ul{ display:block; overflow:hidden; padding:0px; margin:0px; } ul li{ list-style-type:none; float:left; background-color:#666; margin-right:10px; position:relative; top:0px; padding:5px 10px; } JAVASCRIPT var menu_node = null; var menu_lenght = $(ul).children().length; var menu_elements = $(ul).children(); var total_widths= 0; var speed = 1000; for(i=0;imenu_lenght;i++){ menu_node = menu_elements[i]; total_widths+= $(menu_node).outerWidth(); total_widths+= parseInt($(menu_node).css(margin-left),10); total_widths+= parseInt($(menu_node).css(margin-right),10); $(menu_node).css({left:-+total_widths+px}); } for(i=0;imenu_lenght;i++){ menu_node = menu_elements[i]; $(menu_node).animate({left:0px},speed); } ERROR IN IE7 and IE8 :'( Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0) Timestamp: Mon, 23 Nov 2009 17:00:24 UTC Message: Invalid argument. Line: 12 Char: 12949 Code: 0 URI: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js ERROR LINE: $(menu_node).css({left:-+total_widths+px}); Tracing with the developer tool of IE8 i found http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js or either other jquery 1.3.2 1661: elem[ name ] = value; Any suggestion? Thanks
Re: [jQuery] Create a function?
Your code could end up looking something like this: function setValidation( selector, validator ) { $(document).ready( function() { var $form = $(selector); $form.submit( function() { $form.validate( validator ); var valid = $(this).valid(); if( valid ) { var form_url = $form.attr('action'); var page_target = form_url.substr(1).replace(new RegExp(/, g), _); var queryString = $form.formSerialize(); $form.ajaxSubmit({ type: 'post', url: form_url + '/', data: queryString, resetForm: true, success: function( response ) { alert( response ); $( '#' + page_target ).slideToggle('slow', function() { $(response).hide().prependTo('#sortable').slideDown('slow'); }); } }); } return false; }); }); } And for the case you listed, you would call it like this: setValidation( '#newAward', validate_awards ); I threw a $(document).ready() block into that code. You don't need that if your call to the setValidation() function is already inside a document ready callback, but it doesn't do any harm either. -Mike On Tue, Nov 24, 2009 at 3:48 PM, Dave Maharaj :: WidePixels.com d...@widepixels.com wrote: I have the exact same code on every page where a form gets submitted. How can i turn that into a simple function? The only thing that changes is the $(this).validate(validate_awards) and the form ID; It would be so much easier if the function was in one place and called where needed but I cant figure this out. Something like: $('#newAward').submit(function({ myFormFunction(validate_awards, '#newAward'); }); where I could put in the formID and the validation rules to use CURRENTLY HAVE THIS ON EVERY PAGE: Only the validate_awards and #newAward changes $('#newAward').submit(function() { $(this).validate(validate_awards); var valid = $(this).valid(); if (valid) { var form_url = $(this).attr('action'); var page_target = form_url.substr(1).replace( new RegExp( / ,g), _ ); var queryString = $('#newAward').formSerialize(); $(this).ajaxSubmit({ type:'post', url: form_url+'/', data: queryString, resetForm: true, success:function(response){ alert(response); $('#'+page_target).slideToggle('slow', function (){ $(response).hide().prependTo('#sortable').slideDown('slow'); }); } }); } return false; }); Any help would be greatly appreciated. Thanks, Dave
Re: [jQuery] Create a function?
Do you have a script tag to load your external .js file? Post a link to a test page and I can tell you for sure what's wrong. -Mike On Tue, Nov 24, 2009 at 6:33 PM, Dave Maharaj :: WidePixels.com d...@widepixels.com wrote: Sorry. I cant seem to get it to go. Maybe I did not clearly explain the problem. I want to put the function like you have below in my external js, then on my html pages that have a form just set it up so all I have to do is include the setValidation( '#newAward', validate_awards ); on those pages so 1 function gets called for every form. I put your function setValidation( selector, validator ) { } In my external js On the page with a form I put script type=text/javascript $(document).ready( function() { setValidation( '#newAward', validate_awards ); }); /script But when I load the page I get: setValidation is not defined Ideas where I screwed up? Thanks again. Dave -Original Message- From: Michael Geary [mailto:m...@mg.to] Sent: November-24-09 10:02 PM To: jquery-en@googlegroups.com Subject: Re: [jQuery] Create a function? Your code could end up looking something like this: function setValidation( selector, validator ) { $(document).ready( function() { var $form = $(selector); $form.submit( function() { $form.validate( validator ); var valid = $(this).valid(); if( valid ) { var form_url = $form.attr('action'); var page_target = form_url.substr(1).replace(new RegExp(/, g), _); var queryString = $form.formSerialize(); $form.ajaxSubmit({ type: 'post', url: form_url + '/', data: queryString, resetForm: true, success: function( response ) { alert( response ); $( '#' + page_target ).slideToggle('slow', function() { $(response).hide().prependTo('#sortable').slideDown('slow'); }); } }); } return false; }); }); } And for the case you listed, you would call it like this: setValidation( '#newAward', validate_awards ); I threw a $(document).ready() block into that code. You don't need that if your call to the setValidation() function is already inside a document ready callback, but it doesn't do any harm either. -Mike On Tue, Nov 24, 2009 at 3:48 PM, Dave Maharaj :: WidePixels.com d...@widepixels.com wrote: I have the exact same code on every page where a form gets submitted. How can i turn that into a simple function? The only thing that changes is the $(this).validate(validate_awards) and the form ID; It would be so much easier if the function was in one place and called where needed but I cant figure this out. Something like: $('#newAward').submit(function({ myFormFunction(validate_awards, '#newAward'); }); where I could put in the formID and the validation rules to use CURRENTLY HAVE THIS ON EVERY PAGE: Only the validate_awards and #newAward changes $('#newAward').submit(function() { $(this).validate(validate_awards); var valid = $(this).valid(); if (valid) { var form_url = $(this).attr('action'); var page_target = form_url.substr(1).replace( new RegExp( / ,g), _ ); var queryString = $('#newAward').formSerialize(); $(this).ajaxSubmit({ type:'post', url: form_url+'/', data: queryString, resetForm: true, success:function(response){ alert(response); $('#'+page_target).slideToggle('slow', function (){ $(response).hide().prependTo('#sortable').slideDown('slow'); }); } }); } return false; }); Any help would be greatly appreciated. Thanks, Dave No virus found in this incoming message. Checked by AVG - www.avg.com Version: 9.0.709 / Virus Database: 270.14.76/2519 - Release Date: 11/24/09 04:16:00
Re: [jQuery] Problem with $(document).ready in =IE7 only
You don't need the language=javascript in the script tag; that isn't the problem. There is an extra comma at the end of the object literal in your infiniteCarousel({...}) call. See if removing that helps. Note that $(document).ready(function() { ... }); and $(function() { ... }); mean exactly the same thing. You may want to pick one form or the other for consistency. And no need to have two separate ones (although no harm done either). -Mike On Mon, Nov 23, 2009 at 6:03 AM, JD john.de...@gmail.com wrote: Hello everyone, I'm trying to figure out this weird error I'm seeing. I have a simple script that, after the document is ready, I want to change a CSS attribute from display:none to display:block and then load the jquery inifinite carousel plugin: script type=text/javascript language=javascript !-- $(document).ready(function() { $(#carousel).css({ 'display' : 'block' }); }); $(function(){ $('#carousel').infiniteCarousel({ transitionSpeed : 500, displayTime : 1, textholderHeight : .15, displayProgressBar : 0, displayThumbnails: 0, }); }); -- /script This works fine in Safari, Firefox and IE 8. But in IE 7 (and I assume lower but I'm not testing for it because it's not a requirement), I get an object expected error on the last }); in the first function. I've googled around and changed up the script include so it's set to language instead of type, I've moved stuff around, made sure that my JS include path is correct, but I'm stumped. For reference, here's how I include my JS. I know I can use the google inclusion code, but when I have that IE7 throws another hissy about variables not being defined: script type=text/javascript language=javascript src=http:// ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js/script script type=text/javascript language=javascript src=http:// ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js/ script link href=http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ smoothness/jquery-ui.csshttp://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/%0Asmoothness/jquery-ui.css type=text/css rel=stylesheet So I'm 99.9% positive it's not loading the js fast enough for the function, but I'm not sure how to fix it.
Re: [jQuery] How to Multiple wrap in Attribute level??
You can't split up a tag like that. Whatever you pass into functions like prepend(), append(), or html() will be treated (if possible) as a complete tag. It would help to know *exactly* what result you are looking for. I'm guessing you want to have it end up like this: table tr tdinput value=abc //td tdinput value=def //td tdinput value=ghe //td /tr /table Is that right? BTW, I assume that the extra characters in the second and third td tags is just a typo in your example, and your actual code is valid HTML? Here is how you could do it: $('tabletd').each( function( i, td ) { var $td = $(td); $td.html( 'input type=text value=' + $td.find('p').text() + ' /' ); }); Also instead of 'tabletd' as your selector, I'd suggest giving the table an id or class attribute and using that in the selector - otherwise your code will operate on *all* tables on your page. Finally, note that I switched your quotes around, using single quotes for JavaScript strings and double quotes for attributes. It will work either way, but valid HTML requires double quotes for attributes. It's worth getting in the habit of using single quotes for your JavaScript strings, so you can easily use double quotes for attributes inside those strings. -Mike On Sat, Nov 21, 2009 at 1:35 PM, navid zehi navid.z...@gmail.com wrote: hello all I have a problem with wraping a text or html with a tag, but the text should be placed in an attribute . for example : i have a table like this table trtdpabc/p/td tdpdef/p/td tdpghe/p/td/tr /table i want to change each of the TDs to Textbox with value of its TD . i used this : $('table td p').prepend(input type='text' value=' ).append( '); but the result acted as text and not HTML . plz someone help me , tnx
Re: [jQuery] Bolding a certain word - string manipulation?
I wouldn't know what to suggest about the IE7 problem without seeing the code in action. Do you have a test page I can look at? -Mike On Sun, Nov 22, 2009 at 4:45 PM, Rua ra2a...@gmail.com wrote: Awesome thanks that works, but not in ie7? Michael Geary-3 wrote: If the word anything is just part of the text inside the div, then it doesn't have a DOM element (tag) of its own. This means you can't select it with a jQuery selector or any kind of DOM manipulation, and you can't apply a CSS style to it. What you can do is rewrite the HTML content of your DIV element. If you know for sure that there is only a single DIV with class=tpSurveyQuestion, then it's simple: var $question = $('.tpSurveyQuestion'); $question.html( $question.html().replace( 'anything', 'anything' ) ); If there may be multiple DIVs that match that selector, you need to handle each one individually: $('.tpSurveyQuestion').each( function() { var $question = $(this); $question.html( $question.html().replace( 'anything', 'anything' ) ); }); -Mike On Thu, Nov 19, 2009 at 3:18 PM, Rua ra2a...@gmail.com wrote: Hi I'm trying to select a specific word inside a div and would like to bold it, I can't seem to find how to do this anywhere! $(.tpSurveyQuestion:contains('anything')).css(font-weight,bold); -- View this message in context: http://old.nabble.com/Bolding-a-certain-word---string-manipulation--tp26421612s27240p26421612.html Sent from the jQuery General Discussion mailing list archive at Nabble.com. -- View this message in context: http://old.nabble.com/Bolding-a-certain-word---string-manipulation--tp26421612s27240p26471202.html Sent from the jQuery General Discussion mailing list archive at Nabble.com.
Re: [jQuery] is this legal according to the jQuery license
You're welcome to make any changes to jQuery that you want. You can use jQuery under the MIT license, which puts very few (almost no) restrictions on what you can do with it. Basically the only two restrictions are that you have to keep the copyright notice in the jQuery source code, and you can't sue the jQuery authors if anything goes wrong - you use the software entirely at your own risk. But I wonder if you need to make this particular change. Have you looked at jQuery.noConflict()? It may be all you need to coexist with multiple versions of jQuery and other libraries that use the $() function. -Mike On Sat, Nov 21, 2009 at 5:38 AM, Dimitar dimitar.vel...@gmail.com wrote: Hello, I need to use jQuery lib in a script that will be included in my clients sites. My script will be included last in the body of a html page, and jQuery lib will be included dynamically from my script. Can anyone tell me is this going to have conflict with older jQuery libraries and with other libraries. If it's going to have conflict can someone tell me hot to solve it. I have made some modification on jquery, can someone tell me if this is legal according to the jQuery license. Here is the changes they are on the beginning of the script: (function(){ var // Will speed up references to window, and allows munging its name. window = this, // Will speed up references to undefined, and allows munging its name. undefined, // Map over jQuery in case of overwrite _jQuery = window.AR_jQuery, // Map over the $ in case of overwrite _$ = window.AR_jQuery, jQuery = window.AR_jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, I'll wait for response. Thanks
Re: [jQuery] Beginners problem with selectors
So you are saying you want the entire last row of the outer table, not the last row of the inner table, is that right? IOW, what you want to get back is this row: trtdtest/tdtdtabletbodytrtdNew test/td/tr/tbody/table/td/tr If that's right, you're just missing a '' in your selector. Change it from: var $row = $('table#list tbodytr:last'); to: var $row = $('table#listtbodytr:last'); Even better would be: var $row = $('#listtbodytr:last'); There's no benefit to specifying 'table' on the selector since the table has an ID - it may actually be faster if you just use the ID alone. Also I assume that the difference in ID ('list' in the selector, 'mytable' in the HTML) is just a typo. -Mike On Thu, Nov 19, 2009 at 6:20 AM, jkrassman joakim.krass...@sportdykare.sewrote: Hi, sorry if I am posting in the wrong group? I am having a simple nested table, looks like this table id=mytable tbody tr tdtest/td tdtabletrtdNew test/td/tr/table/td /tr /tbody /table So my problem is that I cant get the last TR within the first table? var Obj = $(table#list tbodytr:last); Of course it looks at the last tr in the table, but how should I manage to get the last TR in the first table? Best regards, Joakim
Re: [jQuery] Problem with plugins
Can you post a link to a test page? It's impossible to tell what is wrong from the .js file you attached. It's not even JavaScript code: it's PHP code. The browser doesn't ever see your PHP code. All it sees is the *output* of the PHP code. There could be any number of things wrong, but there's no way to tell what they may be without seeing that actual output in a test page. -Mike On Thu, Nov 19, 2009 at 8:03 AM, Paulo Henrique paulode...@gmail.comwrote: Can someone help me find any problem with the code attached? I am using it on a website, but its happening a problem with some of my plugins... I use all of them on other websites and they all work fine, but on this one, some aren't working. When I call the editable plugin, it throws an error message saying editable is not a function... the same happens with sortable, from jquery-ui... On another website I'm working, this happens with ALL jquery plugins. Does anyone know what might be causing this? Att. Paulo Henrique Vieira Neves Bsc. Sistemas de Informação +55 38 9141 5400 MSN: paulode...@live.com GTALK: paulode...@gmail.com SKYPE: paulodemoc
Re: [jQuery] Can't get image's dimension under a hidden object
I don't think even case 1 will work in all browsers. Some browsers won't bother loading the image if it has display:none. But they will all load it if it has visibility:hidden. Here's how I do it: jQuery.imageDimensions = function( src, callback ) { jQuery('img /') .css({ visibility:'hidden' }) .appendTo('body') .load( function() { var width = this.width; var height = this.height; jQuery(this).remove(); callback( width, height ); }) .attr({ src:src }); }; and then use: $.imageDimensions( 'xxx', function( width, height ) { // here you have the image width and height }); That's a little different from what you're doing - I'm not working with an IMG tag already in the document - but if you pull the src attribute from the img tag and pass it to this function it should work. -Mike On Thu, Nov 19, 2009 at 7:16 AM, David .Wu chan1...@gmail.com wrote: 1. img src=xxx id=img1 style=display: none; / $(window).load(function() { alert($('#img1').width()); }); 2. div style=display: none; img src=xxx id=img2 style=display: none; / /div $(window).load(function() { alert($('#img2').width()); }); case 1 can get the dimension, but case 2 can't, how to get it?
Re: [jQuery] Bolding a certain word - string manipulation?
If the word anything is just part of the text inside the div, then it doesn't have a DOM element (tag) of its own. This means you can't select it with a jQuery selector or any kind of DOM manipulation, and you can't apply a CSS style to it. What you can do is rewrite the HTML content of your DIV element. If you know for sure that there is only a single DIV with class=tpSurveyQuestion, then it's simple: var $question = $('.tpSurveyQuestion'); $question.html( $question.html().replace( 'anything', 'banything/b' ) ); If there may be multiple DIVs that match that selector, you need to handle each one individually: $('.tpSurveyQuestion').each( function() { var $question = $(this); $question.html( $question.html().replace( 'anything', 'banything/b' ) ); }); -Mike On Thu, Nov 19, 2009 at 3:18 PM, Rua ra2a...@gmail.com wrote: Hi I'm trying to select a specific word inside a div and would like to bold it, I can't seem to find how to do this anywhere! $(.tpSurveyQuestion:contains('anything')).css(font-weight,bold); -- View this message in context: http://old.nabble.com/Bolding-a-certain-word---string-manipulation--tp26421612s27240p26421612.html Sent from the jQuery General Discussion mailing list archive at Nabble.com.
Re: [jQuery] AJAX w/dataType='json', doesn't correctly handle boolean response?
You would normally expect that to work. What content-type is your server putting in the header for the JSON data? That could be throwing it off. Also note that a bare primitive value (true, false, null, or a string or number) is not valid JSON. The only valid JSON is either an object enclosed in {} or an array enclosed in []. However, this is not what's causing your problem. jQuery doesn't use a strict JSON parser - it simply evals the JSON text - so a bare primitive value should work fine if everything else is OK. -Mike On Thu, Nov 19, 2009 at 11:08 AM, livefree75 jpittm...@gmail.com wrote: Hi, I'm using the following code on the client side: $.ajax({ dataType : 'json', // other options success : function(json_response) { console.log(typeof response, response); // Using Firefox's firebug } }); And this PHP code on the server side: ?php // php processing code $response = some_boolean_value(); print json_encode($response); ? Now, using Firebug, I can verify that the actual JSON response coming back is indeed either true or false (without the quotes), which should evaluate to Javascript boolean true or false. However, when I obtain it in the success() method of my $.ajax() call, it comes in as a string. (e.g. true or false). i.e., the console.log() call renders: string true Shouldn't it render: boolean true ? Is this a bug? Jamie
Re: [jQuery] Re: non well-formed
false (and true) and numbers are valid JSON values. You *can* put them in quotes, but that changes their meaning: they become strings instead of boolean or numeric values. It's true that you would want to use the properties of the msg object such as msg.descrizione, but it's also fine to call alert(msg). It should alert this text: [object Object] I wouldn't use msg as the variable name, since that sounds like an abbreviation for message - and this is an object, not a message string. But that wouldn't affect how the code works. That said, it's pretty hard to tell what might be wrong. Luca, I assume that the line break between del and computer is not present in the actual JSON text, but is simply an artifact introduced in the email post, is that correct? Can you post a link to a test page that demonstrates the problem? That would make it much easier (i.e. it would make it *possible*) to help you. -Mike On Wed, Nov 18, 2009 at 1:55 PM, Carlos Alberto card...@gmail.com wrote: I think you must encapsulate false and numbers in quotes... and treat msg like an object (msg.descrizione, msg. disponibile... etc.) On 18 nov, 17:43, sportfantasy luca.santanie...@email.it wrote: Hi, I'm italian developer. I have a problem. I develope my simple web application using jquery for ajax call. My Servlet return json string generated with json-lib... for example: {descrizione:Questa è la descrizione del computer,disponibile:false,id:1,nome:Computer,prezzo: 123.456} My jsp page contains a simple nutton that call follow js function: $.ajax({ url: json?method=prodotti, global: false, type: POST, dataType: json, success: function(msg){ alert(msg); } }); Application run correcty... Only problem is mozilla/firefox browser... In js console appears this message: Errore: non well-formed File sorgente: ... Riga: 1, Colonna: 1 Codice sorgente: {descrizione:Questa ? la descrizione del computer,disponibile:false,id:1,nome:Computer,prezzo: 123.456} Why? How can I solve it? Sorry for my english. I hope solve my problem Thanks Luca
Re: [jQuery] Re: DOM changes takes effects only after function is done processing
Here is how this really works: 1. Changes you make to the DOM always take effect immediately. If you make any change to the DOM and then immediately follow that with code that looks for your change, that code will indeed see the change. For example: $('#mydiv').html( 'hello' ); alert( $('#mydiv').html() ); // alerts 'hello' 2. BUT... The browser does not refresh its display until your JavaScript code finishes running. So the user will not see any of your changes until then. 3. A synchronous Ajax call does not let your JavaScript code finish running. In that sense it's just like your hard loop. The user will not see anything you change in the DOM until after that call finishes and your code stops running. Why do you need a synchronous Ajax call? This is a VERY bad idea. In single-threaded browsers such as Firefox, it's not just a matter of the page display not refreshing. Your code will completely lock up the browser's user interface - menus and all - and not just for the current browser tab or window, but for *all* browser tabs and windows. Can you use the BlockUI plugin to simulate the effect you need? This would be MUCH better than using synchronous Ajax: http://www.malsup.com/jquery/block/ If you must use a synchronous Ajax call and you want the user to see a message you put into the DOM, then you will need to yield control after you add the message but before issuing the Ajax call. You can do this with setTimeout. Where you have code like this: $('#message').html( 'Sorry, dude, I will now lock up your browser' ); $.ajax({ async:false, ... }); You need to change it to: $('#message').html( 'Sorry, dude, I will now lock up your browser' ); setTimeout( function() { $.ajax({ async:false, ... }); }, 1 ); That will allow the user to see your message before you lock up the browser by issuing the Ajax call. But what would be the point? By using setTimeout() you've made the code asynchronous anyway. So you could just use asynchronous Ajax in the first place, with BlockUI to give the blocking effect you want in the UI. -Mike On Mon, Nov 16, 2009 at 3:21 AM, nowotny nowotn...@gmail.com wrote: On 16 Lis, 11:40, Michel Belleville michel.bellevi...@gmail.com wrote: Well for a start I wouldn't use a this kind of pause() trick if I were you, it's pretty brutal suff looping along until time has passed will likely freeze your interface and that's a bad thing. Like I said... it's only a stand in for the ajax call that'll replace it in the end... the thing is I have to test if on the IP and port the user specified there is a certain service running and if a user puts in an invalid IP (where the service is not running) the ajax call takes some time (until timeout) to process... during that time the interface is frozen and I want it to be... I just want it to show that it's testing the connection and I thought putting Testing into DOM before doing the ajax call would inform the user what's happening but it's not being changed until after the whole function finishes processing when it's already to late cause I already have the results of the ajax call... You'd probably be better off with a setTimeout() which would delegate exécution of a callback after the time, thus truely imitating an Asynchronous call. Again, I said I want to do a synchronous ajax call... and I don't need to delay anything so setTimeout() is not needed here... -- nowotny
Re: [jQuery] Re: IE 7 error with $.getJSON data elements
No, the scope of the data parameter is not the problem. The data parameter is already in scope inside your click handler. (Michel, check the code carefully - don't you agree? The click handler is nested inside the getJSON callback.) If it were broken in IE8 as well as IE7, then I would guess that you probably have a trailing comma at the end of your data.items array. If you have an array like [ 'a', 'b', ] then IE gives it a length of 3 with an undefined element at the end. But that should affect IE8 the same as IE7. But let's stop guessing. Get in there and have a look at the actual data. The error is occuring on this line in your click handler: var aIndexBG = data.items[aIndex].background; So add this code right before that line: alert( aIndex ); alert( typeof aIndex ); alert( data ); alert( data.items ); alert( data.items.length ); alert( data.items[aIndex] ); alert( data.items[aIndex].background ); What do the alerts say? -Mike On Tue, Nov 17, 2009 at 10:26 AM, roryreiff roryre...@gmail.com wrote: So I guess that is the problem then? How would I work towards a solution in making 'data' available to that .click() function? On Nov 17, 10:02 am, Michel Belleville michel.bellevi...@gmail.com wrote: Oh, yeah, now I see. Of course data is probably not what you expect where you're reading it. Why would it ? It's set in a callback as a function's parameter, it's not meant to get out of the callback's scope, and even when it would, you don't know when the callback is triggered, that can be right before, right after, a month after, never, depending on how the AJAX call ends. Michel Belleville 2009/11/17 roryreiff roryre...@gmail.com Could it have something to do with the 'data' variable not being available to the function that I have placed inside the $.getJSON call? Is there a way to force it to pass on/be available to my ppButton.click(...) function? This is all I can think of for now.
Re: [jQuery] Re: IE 7 error with $.getJSON data elements
That is odd. jQuery's attr() method goes to some amount of work to try to get the raw content href attribute ('0') instead of the fully qualified URL. But it all boils down to a .getAttribute('href',2) call on the DOM element. An interesting test would be to replace this line: var aIndex = $(this).attr('href'); with: var aIndex = this.getAttribute( 'href', 2 ); In theory, those should do exactly the same thing - in a simple test case I tried, they both returned '0'. What version of jQuery are you using? You could also just remove the extraneous part of the URL with a regular expression: var aIndex = $(this).attr('href').match( /\d+$/ )[0]; I would also convert the result to a number by using the + operator on it, whichever form you use: var aIndex = +$(this).attr('href'); var aIndex = +this.getAttribute( 'href', 2 ); var aIndex = +$(this).attr('href').match( /\d+$/ )[0]; Actually on that last one, since you're going to clean up the URL yourself anyway, you may as well simplify it to: var aIndex = +this.href.match( /\d+$/ )[0]; -Mike On Tue, Nov 17, 2009 at 10:44 AM, roryreiff roryre...@gmail.com wrote: Clicking on the first link (i.e. a href=0/a): http://pomona.edu/dev/home/0 string [object Object] [object Object], [object Object], [object Object], [object Object], [object Object] 5 I think the problem is in my var aIndex = $(this).attr('href'); In IE 7 it is appending the full URL...any ideas how to get around this? Thanks, On Nov 17, 10:37 am, Michael Geary m...@mg.to wrote: No, the scope of the data parameter is not the problem. The data parameter is already in scope inside your click handler. (Michel, check the code carefully - don't you agree? The click handler is nested inside the getJSON callback.) If it were broken in IE8 as well as IE7, then I would guess that you probably have a trailing comma at the end of your data.items array. If you have an array like [ 'a', 'b', ] then IE gives it a length of 3 with an undefined element at the end. But that should affect IE8 the same as IE7. But let's stop guessing. Get in there and have a look at the actual data. The error is occuring on this line in your click handler: var aIndexBG = data.items[aIndex].background; So add this code right before that line: alert( aIndex ); alert( typeof aIndex ); alert( data ); alert( data.items ); alert( data.items.length ); alert( data.items[aIndex] ); alert( data.items[aIndex].background ); What do the alerts say? -Mike On Tue, Nov 17, 2009 at 10:26 AM, roryreiff roryre...@gmail.com wrote: So I guess that is the problem then? How would I work towards a solution in making 'data' available to that .click() function? On Nov 17, 10:02 am, Michel Belleville michel.bellevi...@gmail.com wrote: Oh, yeah, now I see. Of course data is probably not what you expect where you're reading it. Why would it ? It's set in a callback as a function's parameter, it's not meant to get out of the callback's scope, and even when it would, you don't know when the callback is triggered, that can be right before, right after, a month after, never, depending on how the AJAX call ends. Michel Belleville 2009/11/17 roryreiff roryre...@gmail.com Could it have something to do with the 'data' variable not being available to the function that I have placed inside the $.getJSON call? Is there a way to force it to pass on/be available to my ppButton.click(...) function? This is all I can think of for now.
Re: [jQuery] Re: How can i make a timer that i can stop with jquery?
Now MorningZ, that is possibly the worst comparison of setInterval() and setTimeout() that I've ever seen! (Please take that as a little good-natured ribbing among friends, OK?) Both setInterval() and setTimeout() are cancelable, using clearInterval() and clearTimeout() respectively. The difference between setInterval() and setTimeout() is that setTimeout() calls the callback function only once (or not at all if you cancel it first). setInterval() calls the callback function repeatedly until you cancel it. https://developer.mozilla.org/en/DOM/window.setInterval https://developer.mozilla.org/en/DOM/window.setTimeout You're certainly right on the essential point: a bit of simple code using setInterval() or setTimeout() may well be all that Mark needs. Mark, you may want to look at the source code of that plugin and see where it calls one of these two functions. That will give you some idea of how you could use them in your own code. Also beware: this inside a setInterval() or setTimeout() callback is not what you expect! -Mike On Thu, Nov 12, 2009 at 5:28 PM, MorningZ morni...@gmail.com wrote: Not really requiring jQuery, just read up on JavaScript's setInterval, which is like setTimeout except you can cancel it On Nov 12, 7:39 pm, Mark mark...@gmail.com wrote: Hi, i tried this jquery countdown plugin: http://davidwalsh.name/jquery-countdown-pluginand it works neat.. but not for my interest. What i try to do is have this: Have a simple countdown that counts down from 5 to 0 then changes the text to Uploading... The plugin mentioned can do that but i also want to be able to cancel the countdown which it can't do. Can anyone point me to a plugin that does have that functionality? or how i make that in this plugin.. So what i want to be able to do: 5 4 3 2 1 0 Uploading... Or when cancel is pressed 5 4 3 2 CANCEL Just like that. I hope anyone can help me with this. Thanx, Mark.
Re: [jQuery] How can I store data from an AJAX function in a json-array?
You shouldn't be thinking in terms of storing the JSON data in a variable for other functions to use. Instead, you should *call* those other functions from your success callback, and pass the JSON data as an argument to those functions. Remember that Ajax calls are asynchronous (the A in Ajax). If you store the data in a variable, how will those other functions know when it is ready for use? By calling those functions from the success callback, you insure that the data is ready and available at the moment of the call. If you have a more complete example I can probably suggest something more specific. -Mike On Sat, Nov 7, 2009 at 3:19 PM, DigitalDude e.blumsten...@googlemail.comwrote: Hey, I need to gather somer data for a jQuery function. I need this data to be a json array, which I will achieve in a php action which returns an array that is encoded as JSON. So far, so good. I need sth like this: $.ajax({ url: '/controller/action', data: ajax=true, dataType: 'json', complete: function() { }, success: }); } }) but how can I store the data of the returned array into a variable which I can then use in other functions of my codeblock? I think this one is easy but I just started learning it and don't know how to do it :( Thanks, DD
Re: [jQuery] Re: getJSON - need some direction please.
Yeah, I though Michel's reply was a little snippy too. But that aside, he's right on the specific point that a synchronous Ajax call is to be avoided at all cost. It's even worse than he said: In a single-threaded browser like Firefox, *all* browser windows and tabs are locked up until your Ajax call completes. If your server doesn't respond - or if your visitor loses their Internet connection momentarily - it locks up not just your site but all sites they have open. There must be a way you can structure your code to use ordinary asynchronous Ajax. After you've done that homework, if the solution doesn't come to mind, post some more details and we can help sort it out. -Mike On Thu, Nov 5, 2009 at 6:11 PM, RayJames cdlcollege.rayja...@gmail.comwrote: Man, that felt like an ass chewing but I needed it. :) I am going to do some more homework and see how to put the advice you gave me to good use. Thanks for your time Michel. I really appreciate it. Ray James. On Nov 5, 2:42 pm, Michel Belleville michel.bellevi...@gmail.com wrote: 2009/11/5 RayJames cdlcollege.rayja...@gmail.com Hi Michel, I think I might have confused you a bit. The user is not necessarily my concern. Well... Then I guess it's not necessarily a good thing you design UI because it's all about the user. Ultimately, you're designing machines to work for humans, and when you're designing user interfaces you're at the ultimate step before the human uses the tools. If the user is not your concern here you've picked the wrong part of the job. Really. The code running in the background that sends calls to my api while the user is viewing the course is. Of course it is. These calls consist of functions that Initialize the learner session, terminate the learner session, set and get values from the LMS as well as a few error handling calls. Of course they do. Every time the course code calls the api the api is supposed to execute the call and return either data, true/ false, or both. Of course it is. The problem is that on the Initialize and Terminate calls, nothing should happen until the api returns a true or false. Well, if by nothing you mean nothing both server-side AND client-side I agree with you, you need synchronous calls. That will also prevent your user from doing anything between the beginning of the call and the end. Even scrolling the page, or opening an outside link in a new tab, anything AT ALL until the call finishes. I don't know you but I find that drastic. Once that happens, then the other calls WILL just be called in the background async style while the user is engaged with the course. I think this is the best way, because putting a waiting class could result in longer waiting times for the execution of the functions and could still possibly timeout before the code finishes. What do you think? I respectfully disagree, it is my informed opinion that adding a waiting class will not result in significant performances losses unless you botch the job (and I mean really botch the job, like adding the waiting class to any element of the page instead of the topmost element that needs it) or the calls are very close (and again I mean really very close, the kind of close that would make your interface unusable because synchronous calls would freeze it every odd second). The only constraint here is that you round up elements that must not be triggered between the beginning and the end of your pseudo-synchronous calls and give them this little trigger : $('.the_waiting_class .any_element_you_want_to_block').live('click', function() { return false; }); The event will only be triggered when the targets match (so when the_waiting_class is given to their common parent), it will work on elements added to the dom during ajax or whatever script, and no user will notice any performance problem as .live uses bubbling to catch the events. I apologize for not making myself clear enough. This is actually a fairly complex system and will be awesome when finished. I'm sure it will, but remember UI is one of the most important things that make the difference between awesome and I'm tired of this site that just freezes on me, let's google away. Keep an eye on Drupal and wait for it to come out as a module. I will be opening all my code up as open source once it is finished. Thanks. Hope you do well. Michel Belleville
Re: [jQuery] Re: How to call mouseover of the element in loop
Avoid 'this'. In the setTimeout() callback, 'this' is the window object! Instead you can do: $('ul.News li').each(function( i, element ) { curTimeInterval += timeInterval; //alert(element.id); works here setTimeout(function() { UpdateNews(element.id); }, curTimeInterval); }); -Mike On Thu, Nov 5, 2009 at 2:58 PM, vmrao maheshpav...@gmail.com wrote: OK. This is what I am trying to do. $('ul.News li').each(function() { curTimeInterval += timeInterval; //alert(this.id); works here setTimeout(function() { UpdateNews(this.id); //How to get this.id to work here ? }, curTimeInterval); }); On Nov 5, 5:42 pm, vmrao maheshpav...@gmail.com wrote: My code is as follows. How to call onMouseOver of 'li' element in the loop from jQuery ? script $(document).ready(function(){ var curTimeInterval = 0; var timeInterval = 2000 ; $('ul.News li').each(function() { curTimeInterval += timeInterval; setTimeout(function() { //I would like to invoke onMouseOver of the li element here //I tried $(this).mouseover(); and it did not work }, curTimeInterval); }); }); /script ul class=News li id=Story1 onMouseOver=UpdateNews('Story1')My Stroy1/li li id=Story2 onMouseOver=UpdateNews('Story2)My Stroy2/li li id=Story3 onMouseOver=UpdateNews('Story3')My Stroy3/li /ul
Re: [jQuery] Re: jQuery minified
Thanks for posting the Google URL; that's good information. But name-calling and foul language are not welcome here. -Mike On Sun, Nov 1, 2009 at 1:17 PM, Joonha joonha.sebr...@gmail.com wrote: You nut bags forgot to mention to the noob, Use the AJAX hosted Google URL directly in your source code like so: script src= http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js;/script A lot of sites are using this so its already cached on people's browsers so the download is ZERO in a lot of cases. Hello? Sorry, didn't mean to call you all nut bags. I really should have said scrotums as a proper term. On Oct 29, 4:05 pm, Mike tombaha...@gmail.com wrote: Hey guys, i've got two questions for you: 1. What/Where i cand find are the differences between the minified and complete jQuery version?? what kind of things i can't use with minified version?? 2. the first question was because i'm developping a big web site, we want it to be visited for many users, so i'm worried about performance and loading time, and i think 120K (complete jQuery version) could be a bit too much. I must confess i'm a noob with this loading time stuff :/, so any advice you can give me is welcome. Thanks
Re: [jQuery] licensing question
You're talking about this page, right? http://docs.jquery.com/License I rewrote it to be more clear and to reflect the actual intent of the license. See if your patent attorney finds it more palatable now... Thanks, -Mike On Thu, Oct 29, 2009 at 3:35 PM, David Robertson dwrobertso...@gmail.comwrote: I really like your software and software based on it, but I can't use it because of the language used in your licensing, according to our patent attorney. It reads under both MIT and GPL licenses. This means that you can choose the license that best suits your project, and use it accordingly. If it read under either the MIT or GPL licenses then you would have achieved the intent of your second sentence. Any chance you could change it? -David Robertson
Re: [jQuery] How to prevent default behavior in an event handler that returns a function
You mentioned not being able to pass the event object into your click function, but I don't see the code where you tried to do that, so I don't know what went wrong. In any case, the function-returning-a-function is much more complicated than you need. Risteli's code is on the right track, but it also doesn't show how to handle the event object. You can do it very simply like this: for (var i = 0; i arrPlayers.length; i++) addPlayer( i ); function addPlayer( i ) { // your existing $('body').append(...) goes here $(#playerLink + i).click( function( event ) { $(#imgPlayer).attr( src, img/ + arrPlayers[i].photo ); event.stopPropagation(); } } Although personally I would get rid of all the i indexing and do it more like this: for( var i = 0; i arrPlayers.length; i++ ) addPlayer( arrPlayers[i] ); function addPlayer( player ) { $( 'p' + 'a href=#' + player.name + '/a' + ' is a ' + player.position + ' for the ' + player.team + '/p' ).appendTo('body') .find('a').click( function( event ) { $('#imgPlayer').attr( 'src', 'img/' + player.photo ); event.stopPropagation(); }); } Or alternatively: $.each( arrPlayers, function( i, player ) { $( 'p' + 'a href=#' + player.name + '/a' + ' is a ' + player.position + ' for the ' + player.team + '/p' ).appendTo('body') .find('a').click( function( event ) { $('#imgPlayer').attr( 'src', 'img/' + player.photo ); event.stopPropagation(); }); }); This way I didn't even have to give the a tag an ID at all. BTW, instead of event.stopPropagation(), you can simply return false from the event handler. This automatically calls both .stopPropagation() and .preventDefault(), which in many cases is what you want anyway. Also a tip on creating your array. Any time you have code like this: var array = new Array(); array[0] = FirstThing; array[1] = SecondThing; array[2] = ThirdThing; You can write it more simply - and make it easier to read and maintain - with: var array = [ FirstThing, SecondThing, ThirdThing ]; Finally, you may notice I switched the double quotes to single quotes. This makes it easy to use the correct double quotes in HTML attributes as in the A tag: 'a href=#'. Of course the browser will accept it either way, but my mental validation flags code like href='#' as being invalid. :-) -Mike On Thu, Oct 29, 2009 at 9:29 AM, The alMIGHTY N natle...@yahoo.com wrote: Example page: http://jqueryfun.nathanielklee.com/eventFirefox.html Following one example provided in an official jQuery tutorial (located at http://docs.jquery.com/Tutorials:How_jQuery_Works), I can pass event into a function I define directly in the click assignment handler. e.g. $(#something).click(function(event) { event.preventDefault (); }); However, if this is put into a for loop and modified to include a statement that requires a value of i from the for loop iteration, it won't work because when the handler is fired, it only knows the last iterative value of i. I get around that by instead making a call to a function that returns a function that executes the statements I want. e.g. $(#something).click(doSomething(i)); function doSomething(i) { return function() { alert(i) }; } So far, so good. The problem I run into is that I need to prevent the default behavior with event.preventDefault(). Browsers won't recognize if I pass event into the function even though the aforementioned tutorial indicates that one can indeed pass event into a function. How can I get around this problem? I realize that there are other ways I could do the same thing, such as applying a class to the links in question and referencing the event target (example below), but I'm interested in figuring out why the method I described above doesn't work and whether there's a way to get it to work. e.g. $(#something).click(doSomething); function doSomething(event) { alert($(event.target).attr(anAttribute)); } Thanks!
[jQuery] Re: namespacing jQuery
If your script tag that loads jQuery is immediately followed by another script tag that calls noConflict, there should be no race conditions. You're not putting the noConflict call inside a $(document).ready() or the like, are you? It should be directly executed in a script tag: script type=text/javascript src=my.jquery.js/script script type=text/javascript var jq = jQuery.noConflict(); /script -Mike On Tue, Oct 27, 2009 at 9:42 AM, El Greg greglaval...@gmail.com wrote: Sorry - should have mentioned - I tried using jQuery.noConflict() as well as jQuery.noConflict(true) and reassigning to a variable, but ran into race conditions where another version of jQuery was executing a call before I could call noConflict()... I'm hoping to namespace my own separate version of jQuery sitting in another file such that I only have to do one script src call and end up with a myjQuery instead of jQuery. Thanks again for your help! On Oct 27, 11:08 am, Dan G. Switzer, II dswit...@pengoworks.com wrote: See the $.noConflict() docs: http://docs.jquery.com/Core/jQuery.noConflict var j = *jQuery.noConflict*(); // Do something with jQuery j(div p).hide http://docs.jquery.com/Effects/hide(); // Do something with another library's $() $(content).style.display = 'none'; -Dan On Tue, Oct 27, 2009 at 10:25 AM, El Greg greglaval...@gmail.com wrote: I'm interested in namespacing jQuery to something like $myjQ. or myjQ. $ and wondering what the best way is to do it. I will potentially be using my version of jQuery on other pages that are running other versions of jQuery - hence the idea to rename it completely so that I have control over version, plugins, etc. I thought about just doing a find and replace on the word jQuery in the source, but I'm hoping there's an easier way. Thanks!
[jQuery] Re: Unexpected $(document).ready() behavior when jQuery is loaded after the page
If that's true, shouldn't my test case fail in Firefox? http://mg.to/test/jquery/dynamic-nightly/jquery-dynamic-onload.html The page does use a nightly from several weeks ago and I haven't tested with a more recent version - but hopefully it hasn't gotten broken since then. -Mike On Mon, Oct 26, 2009 at 10:46 AM, Server Herder serverher...@gmail.comwrote: Under the latest nightly release bindReady() first checks for document.readyState === 'complete'. Browsers that support the readySTate property will then execute the jQuery.ready() function and this case will be handled properly. IE, Safari and Chrome all appear to have this; however, Firefox does not and as such attaching jQuery post-document-load will never fire the jQuery.ready() event.
[jQuery] Re: Variable within document ready... where is it in the DOM?
The concept you're looking for is called a closure. Search for: javascript closure and you will find all sorts of information about closures. It really has nothing to do with jQuery or the DOM. Closures are part of the core JavaScript language and work in any environment where JavaScript is implement. For example, Adobe Acrobat supports JavaScript, but it has no HTML-oriented DOM, and certainly no jQuery. But closures work exactly the same in JavaScript code in a PDF file as they do in a web page. Here's a simple way to understand closures: 1. When you nest one function inside another, the inner function can read and write variables declared in the outer function. 2. That *always* works, even if the outer function has already completed running and returns to its caller. That's what is happening in your example: You have an outer function - the ready callback - and an inner function - the click handler. The inner function can access the variable declared in the outer function, even though the inner function runs long after the outer function has returned. -Mike On Sat, Oct 24, 2009 at 5:23 PM, Nikola nik.cod...@gmail.com wrote: It has to be stored somewhere though... Say, for example, we bind a handler to the click event on the BODY of the document and we log the pen object to the console. $(function(){ var pen = { type: Ballpoint, color: blue, hasInk: true } $(BODY).click(function(){ console.log(pen) }) }); As you can see when you run that code, the pen object is logged to the console so it has to be stored somewhere... Where, is the question. On Oct 24, 8:01 pm, donb falconwatc...@comcast.net wrote: You can't. It exists for the duration of the ready function, then it's gone. On Oct 24, 7:51 pm, Nikola nik.cod...@gmail.com wrote: Hi, I've been trying to understand a little tidbit of jQuery here... Lets say we define an object in the Document ready method: $(function(){ var pen = { type: Ballpoint, color: blue, hasInk: true } }); Where in the DOM can we find the pen object?