[jQuery] Re: question about plugin programming
Hi Rene, I've never quite understood the benefits to the plugin approach, when you can simply create an object that uses jquery. (I've wondered about this before on the list, but so far no one has enlightened me.) function Animator(container) { this.jC = container; // this is a jquery instance }; Animator.prototype.draw = function() { this.jC.html('divdraw some elements/div'); this.jC.find('div').click(function() { alert('add some events'); }); }; Then you can create as many objects as you need. var a1 = new Animator($('#img1')); var a2 = new Animator($('#img2')); etc. Works great and seems (to me) much simpler than creating a plug-in. -j On Apr 19, 5:40 am, Rene Veerman [EMAIL PROTECTED] wrote: Hi. I've created a button jquery plugin that does a png animation onhover, and takes text on the button from html/dom. Although i've modelled the code after the datePicker plugin, and it works, i think i have a problem with scope. When I instantiate buttons in two different windows, a click in the first window uses settings from the second window. :( I'd like some advice on the code i've written. If there are any tutorials about jquery plugin writing that you can recommend, i'd like to read those aswell. The code can be downloaded throughthttp://mediabeez.ws/mediaBeez/permalink.php?tag=buttonAnimated
[jQuery] Re: Passing variables between two functions
looks good. pointX is a global variable and can be accessed by both functions. What's the problem? On Apr 11, 6:13 am, Decagrog [EMAIL PROTECTED] wrote: Hi all, I've a newbie question about variable scope...essentially i've two anonimous function and i need to retrieve a variable generated into first function and use it in the second one. Here the basic code to get an idea of what i'm trying... var pointX ; $(.nav_slider).mousemove(function(e){ pointX = e.pageX ; // do some other stuff with pointX ... }); $(document).scroll(function () { var docH = $(window).height(); var docW = $(window).width(); docWcenter = docW / 2; //here i need again pointX ... $(#point).css( 'position', 'relative' ).animate({ left :docWcenter + pointX + px}, 200 ); });
[jQuery] Re: How do I use ColdFusion and jQuery variables for pagination?
Calling a $.get() on each page change click kind of defeats the point of doing client-side paging. It will be basically be as slow as reloading an entire new page (and you have to add some UI to show that the page is 'loading...). If your db has 10,000 rows, then agreed, you won't want to dump them all at once. But why not send 100? Then you can page through them super quick using client side js (and jquery). When you reach the end of the what's in memory, query the next 100. (or even fancier, query the next 100 when the user is looking at the 2nd last page.) The key concept is that you load your paging data and keep in a javascript object or array. var rows; $.getJSON(json.php, {action:get100rows}, function(json) { rows = json.result; }); // then your callback for the pagination class looks something like this... function showpage(page) { // page is 1..n var pagesize = 10; var offset = ((page-1)*pagesize); for (var i=0; ipagesize; i++) { $('#results').append('div'+rows[i]+'/div); // display each row } // here's where you would check to see if you need to load more data... if (offset+pagesize = rows.length) { ... } } -j On Apr 10, 4:48 pm, Josh Nathanson [EMAIL PROTECTED] wrote: Rick, if you have 10,000 records, I would say to not dump them all into the client. My suggestion would be to set everything up as if you were doing the pagination on the server using CF, and then change your pagination links so that they are intercepted, and used to do an ajax call to your CF template which retrieves the records. Your CF template could output the records as an html table and then send that html back to the client -- this html would be the argument in your ajax callback function, which would take the returned html and place it in the right place on the page. This is all independent of any plugins, just using straight jQuery and CF. Just as a rough outline... suppose your pagination link looks like a href=myCfTemplate.cfm class=paginate5/a (this would be to go to page 5 of the pagination). Your ajax call would look like something like: $(a.paginate).click(function() { $.get( this.href, $(this).text(), outputhtml ); return false; }); Where outputhtml is the function that takes the returned html and outputs it to the page. This would send the data 5 to your CF template as an url variable, which you could use to determine which records to get from the database. -- Josh - Original Message - From: Rick [EMAIL PROTECTED] To: jQuery (English) jquery-en@googlegroups.com Sent: Thursday, April 10, 2008 1:17 PM Subject: [jQuery] Re: How do I use ColdFusion and jQuery variables for pagination? Thanks for the reply, Josh... I think the part that I'm not understanding is the dump the whole query to the client and then the plugin takes care of the pagination. It also sounds like a memory and/or processor intensive way to get 20 records per page. If I have 10,000 records, I guess I would be getting and dumping all 10,000 records at once? I've considered taking the straight CF route with this, or perhaps using SQL to retrieve just the records I need. Would using CF or SQL be preferable for datasets composed of thousands of records? Rick On Apr 10, 3:31 pm, Josh Nathanson [EMAIL PROTECTED] wrote: Rick - I don't know how the pagination plugin that you're using works, but there may be some sort of before event that you can use to ajax some variables to your CF page. Your CF template would take these variables and use them to set the startrow and maxrow values and then send back the result. That said, not sure why you'd need to do that if you're doing pagination on the client side? The idea is that you dump the whole query to the client and then the plugin takes care of the pagination. -- Josh - Original Message - From: Rick Faircloth [EMAIL PROTECTED] To: jquery-en@googlegroups.com Sent: Thursday, April 10, 2008 12:19 PM Subject: [jQuery] How do I use ColdFusion and jQuery variables for pagination? Hi, all... I'm a bit confused about how to get variables from jQuery that I can use in my ColdFusion code. In typical CF pagination, I use startrow and maxrows variables to limit the query output. How would I get these variables from the jQuery? I just can't piece together what's happening. Below is the jQuery I'm currently using. The total number of records is set in the jQuery using the recordCount CF variable. Thanks for any help! Rick script type=text/javascript function pageselectCallback(page_id, jq){ $('#Searchresult').text(Showing search results +((page_id*20)+1)+-+((page_id*20)+20)); } $(document).ready(function(){ // Create pagination element $(#Pagination).pagination(cfoutput#get_properties.recordCount#/cfoutput, { items_per_page:20, num_edge_entries: 2,
[jQuery] Re: Slow tabs
Try creating a test page with only the js code needed for the tabs. As for keeping content hidden during loading, I like to use a css class called hidden. /* css */ .hidden { display: none; } /* html */ div class=foo hiddenI am hidden/div On Apr 8, 1:54 pm, Glen Lipka [EMAIL PROTECTED] wrote: We are using tabs on this page:http://success.marketo.com/index.php There is a long delay (FF2) between click and the transition. Are we doing something wrong? Also, what is the best practice to make the tabs detail hidden until it finishes tabbifying the block? Thanks much, Glen
[jQuery] Re: what wrong in code?
infinite loop? getready() calls sendsite() which calls getready() which calls sendsite()... On Apr 8, 4:06 pm, R.O.M. [EMAIL PROTECTED] wrote: This code doesn't work in all browsers exept firefox. Why and what i must to do? Trouble: when button with id=newsitesubmit was pressed there is no reaction, but in firefox all is ok. code: function getready() { $('#newsitesubmit').click(sendsite); }; function sendsite() { /* отправляем данные из формы */ getready(); var sitename = $(#siteinfo #sitename).val(); var siteurl = $(#siteinfo #siteurl).val(); var uname = $(#siteinfo #username).val(); var uemail = $(#siteinfo #uemail).val(); $.get('savesite.cgi', {sname: sitename, surl: siteurl, uname: uname, uemail: $.get('static/msg_site_added.txt',function(data){ var oldcontent = $('#siteinfo').html(); $('#siteinfo').html(data+'Добавить еще сайт'); getready(); } ); html: div id=add h4Добавление сайта/h4br form id=newsite dl dtlabel for=form-sitenameНазвание:/label/dt ddinput type=text name=sitename id=sitename/dd dtlabel for=form-siteurlАдрес:/label/dt ddinput type=text name=siteurl id=siteurl/dd dtlabel for=form-usernameВаше имя:/label/dt ddinput type=text name=username id=username/dd dtlabel for=form-useremailВаш e-mail:/label/dt ddinput type=text name=uemail id=uemail/dd ddinput type=button value=Отправить id=newsitesubmit/dd /form /div
[jQuery] Re: Logic issue - can jQuery help?
I've used an object to 'cache' jquery instances. Works great. I've also used id strings to pack data. like div id=x45-64 where the 'x' is because id's shouldn't be numeric. And the other numbers might be your employee id or task id. I find this id method ugly, and would rather use a javascript object (or hash as you call it) to keep track of instances instead of walking through the DOM trying to figure out which object was clicked on. You've explained your problem in detail, but it sounds like your real problem is at some higher level. You're storing all the information in the DOM, and now you don't want to parse the DOM because it's slow? well... time for a new approach. (and seriously, spend a day experimenting with closures. it's a damn near religious experience once you understand them.) -j On Apr 3, 2:59 am, Shawn [EMAIL PROTECTED] wrote: I apologize if this is semi OT... I have an odd performance problem that I can't see any clear logic around. I was wondering if jQuery might be able to help me with this. Situation. 1. I have a table of employees. Employees in the left column (one per row), and days in the remaining columns. Some employees are team leaders, some are team members. Teams can change at any time, and employees may change their role from leader to member, or vice versa. But an employee can only be on one team at a time. 2. I have a large list of tasks to be match up to the employee and day. The only match to the employee is the employee ID. Problem. - Because teams can change I can potentially be viewing a period of time where one employee has been on two (or more) different teams, and so would rightfully have multiple rows of data. Therefore, I can't simply use the employee ID as an element ID to find the row. (potential duplicates). - The only unique identifier I would have for each employee is a combination of the employee ID, team leader ID, and start date. - The task only knows the employee ID. So, I'm looking for a way to match the task to the correct employee row, while still satisfying the DTD requirements of not using duplicate ID values. Once I know the row, I can determine the rest fairly easily. But thus far the only method I have come up with includes some nested loops which is resulting in significant delays. And even then, I still have potential for duplicate IDs. One thought that has occured to me (and I'll be trying out soon) is to create a hash object where the employee is the key which points to an array of employee objects. The employee object would contain a hased ID value (combine employee id, leader id, start date for instance) that will be unique. (or at least given a good statistical probability of being unique). Then the further processing has the unique ID to find the corresponding row, AND the data to determine which row (if more than one) is pertinent. But, I've never done this kind of indexing before and am concerned I may be introducing overhead and delays. Any thoughts/comments here? Thanks for letting me get this down in writing. Sometimes the answer pops out at me when I do this. But not this time. Also thanks for any tips or suggestions. Shawn
[jQuery] Re: callbacks calling callbacks calling callbacks ....
Hi Shawn, Interesting problem you've outlined. Running the queries sequentially is slow, and splitting them apart appears faster (presumably since you display some progress to the user). My approach using objects will not speed up your 30 second database queries, but it can break down the problem into more manageable chunks and display progress to the user. Consider this example. We want a list of Employees, their current projects, and the next due action item for each project. Something like... Name / Project / Action Item -- Bob / Website / Install forum software Sue / Wiki / Fix IE memory leak Now, you could get all employees, and for each employee get all projects, and for each project get the most current action item. That would be the linear method, and it would be one big glob of code with lots of nested anon subroutines. Another way of approaching this problem would be to break it down using objects. Instead of drawing the table at once, let's draw the table row, and draw the employee name, projects and action items as they come in. WorkerList - gets worker ids, creates table structure and creates instances of Worker and Project Worker - get worker name Project - gets project info and gets next action item for a worker At the top level, you would call: var list = new Workerlist($('#workers')); // assume a table element exists e.g. table id=workers list.get(); The classes would look like this... /* class: Workerlist */ Workerlist(jC) { this.jC = jC; // jquery container } // get workers and create Worker and Project instances Workerlist.prototype.get = function() { var me = this; $.getJSON('getworkers.php', {}, function(json) { foreach (w in json.workers) { var row = $('trtd class=worker/tdtd class=projects/ td/tr'); row.find('td.worker').each( function() { new Worker({id:w, container:$(this)}); }); row.find('td.projects').each( function() { new Projects({worker_id:w, container:$(this)}); }); jC.append(row); // add row to HTML table } }); } /* class: Worker */ Worker(opts) { this.id = opts.id; // id this.jC = opts.container; // jquery container this.name = ''; // no name yet var me = this; $.getJSON('getworker.php', {id:id}, function(json) { me.name = json.name; me.draw(); }); } // display the worker Worker.prototype.draw() { this.jC.html('b' + this.name + '/b'); } This example is getting long, so i'm going to stop here. But the key point is that the problem is broken down into objects, where each object knows how to retrieve information - as well as display itself since it was passed a jquery container. The page is populated as various asyncronous requests come in. You don't need to manually manage these requests, since they use closures. You might also notice that this example would create lots of tiny JSON calls to retrieve the worker name (and project info). True. To reduce those calls, you would need a wrapper class to aggregate the requests to 'getworker.php', so it passes in 10 names at once instead of one at a time. (But that's an optimization that could be done at a later date.) -j On Mar 8, 10:27 pm, Shawn [EMAIL PROTECTED] wrote: Can you show a quick sample of the objects/callback methods you allude to? (instead of the nested approach). In my case I have three ajax requests, each of which takes a fair bit of processing on the server side. They were created as separate processes because of the non-linear use of the data in the app. However when the page first loads I need to call all three and wait on em. The problem is that putting these three items into a single routine results in 30+ second data retrieval. (complex joins, and business rules...) I do know there are ways to optimize my code some, but even this would only cut off a second or two. In short, I'm kinda stuck with the nested approach right now, but could speed up the initial page load significantly if each request was concurrent and final processing/rendering took place after all the data was collected. But one of the steps needs to do some intermediate processing to modify the data returned. I guess I could move this intermediate processing to the server, but I didn't see any performance improvements when I tried it early in the app. Thanks for your response. (btw, I'm not the OP you were referring tooo, but I think he was alluding to similar situations...) Shawn J Moore wrote: Regarding your example of waiting for N records to come back, it is definitely worth it to pack all those requests into a single AJAX/JSON request. Not only are you saving the overhead of the HTTP requests (browsers can only make a 2-4 requests concurrently) but your code will be cleaner. (e.g. no counter in on the callback) To the OP: can you post more details about what you're
[jQuery] Re: basic Show Hide icon
return false; is your friend. I find i have to add it to almost every click() and submit() event. e.g. $('#toggletandc').click(function(){ $('div.showhide,div#tandc').toggle(); return false; }); On Mar 7, 6:40 pm, SparrowDog [EMAIL PROTECTED] wrote: I am using the Basic Show Hide (code below) succesfully and have figured out how to link it to text rather than a 'submit button'. What I would like to do though is to have a hand (or some other meaningful icon) show up on mouse over instead of the cursor. Is there a way to do this? When I wrapped the text in an a tag with a #, on click, it returned the user to the top of the page, which I don't want to do. $(document).ready(function(){ $('div#tandc').hide(); $('#toggletandc').click(function(){ $('div.showhide,div#tandc').toggle(); }); }); Thanks Joanne (first time jQuery user)
[jQuery] Re: callbacks calling callbacks calling callbacks ....
need to handle this itself. But this entire process could in theory be wrapped up into a single function. I guess the real question is if that function can be abstracted enough to make it generic. Right now, I don't see how. I don't think this idea is revolutionary or anything. Probably kinda obvious and/or flawed. But perhaps it'll get you (us?) moving in a positive direction. Now I'm curious though and want to try out some things... I'll report back if I have any success... Shawn h0tzen wrote: On 5 Mrz., 15:40, J Moore [EMAIL PROTECTED] wrote: wouldn't nesting the methods work? e.g. unfortunately not as some methods have to be invoked in parallel. generally exactly this nesting looks fine with no real code behind but it is just cruel if you imagine having error-handling, rollbacks and business logic etc within. what im looking for is some pattern abstracting the async-callbacks or just a real-world example/solution of someone having the same issues with logic involving multiple, dependent ajax-calls. thanks, kai- Hide quoted text - - Show quoted text -
[jQuery] Re: help with a strategy?
Much like how jquery keeps the javascript out of the HTML, it's so much cleaner to keep PHP out of the HTML as well. Have a look at the Smarty templating system for PHP. It's awesome. -j On Mar 4, 11:20 am, charlie [EMAIL PROTECTED] wrote: Hi all, the application I'm attempting to write couldn't be simpler: I want to display rows of data, retrieved from a database and allow people to edit or delete those rows and add new rows. Backend is PHP, but I'd prefer to keep that out of the picture. So far I'm passing my rows successfully to jquery and have the loop ready to go, but I'm not sure how to proceed. Here's my dilemma: what's the best strategy for keeping the HTML out of my Javascript as much as possible? The whole point of this excercise has been to try to extricate as much PHP as possible from the display logic, but just subbing in javascript is obviously pretty pointless. One strategy I'm toying with is having an HTML empty row in the normal layout that's hidden and get's cloned for both existing and new records. Is this a common technique? Are there better ones? I'm trying not to re-invent the wheel here! TIA, Charles
[jQuery] Re: Plugin Authoring Help pt 2
You might find it easier to simply create objects that use jquery, instead of writing a jquery plugin. The biggest advantage is that you actually have a normal instance of an object. You can pass this instance to other objects, call other methods on it... all the usual good stuff. (jquery plugins seem to be a one-shot deal. you call the method, pass in a bunch of parameters, and it works. If you need to access that instance again, you can't. i had this problem with the pagination plugin. i added more elements to my list, but there was no way to tell the pagination object that the list was longer. i would have to delete it and recreate it.) here's the pattern i use. let's say i wanted a 'fancy' textarea box. function TextBox(opts) { this.jC = opts.container; // all jquery objects start with a 'j' this.visible = 0; }; TextBox.prototype.draw = function() { this.jC.html('textarea/textara'); // could add lots of functionality to the textbox. key press handlers, etc. this.visible = 1; }; // how you use the object... $(document).ready(function() { var txt = new TextBox({container:$('#text')}); // obviously need an element to be the container. txt.draw(); }); Works well for me. Maybe one of the plug-in experts can comment on when it makes sense to write a jquery plugin versus write a normal object that uses jquery? -j On Mar 4, 2:09 pm, Leanan [EMAIL PROTECTED] wrote: Ok, I'm really trying to wrap my head around this, and it's irritating me. I've checked out the following pages: http://docs.jquery.com/Plugins/Authoringhttp://www.learningjquery.com/2007/10/a-plugin-development-pattern And they help some but there's one problem I'm running into. I have: $.fn.myPlugin = function(options) { $.myPlugin.defaults = $.extend($.myPlugin.defaults, options); return(this); }; $.myPlugin = { defaults: { def1: 'default1', def2: 'default2', ... defx: 'defaultx' }, myFunc: function() { var options = $.myPlugin.defaults; //do something here, anything really }, myFunc2: function() { var options = $.myPlugin.defaults; //do something here, again, anything } }; Now, I want to do something like this: jQuery().myPlugin({def1: 'other_def1', def2: 'other_def2'}).myFunc(); Can I? Because it's not working. It tells me that jQuery().myPlugin({def1: 'other_def1', def2: 'other_def2'}) is not a function. However, if I change it so that myFunc is $.fn.myFunc = function() { }, then I can, but I have to do it as: jQuery().myPlugin({def1: 'other_def1', def2: 'other_def2'}).myPlugin.myFunc(); Which I don't like. None of the tutorials or documentation I can find is clear on this point, though they do refer to the functions in $.myPlugin as being user-accessable... and they are, but only if I do $.myPlugin.myFunc. I can't chain. And I want to be able to do that.
[jQuery] Re: JQuery Hello world not working
actually, your code doesn't display a link. it sets up an action when the link is clicked. You're missing: a href=#do something/a There might be other problems too if you aren't even seeing the alert message. Download firefox and firebug. IE isn't much help for developing javascript. -j On Mar 5, 5:16 am, pradeep_tp [EMAIL PROTECTED] wrote: Hi All, I am new to JQuery. I did the following to get started with JQuery. 1) Downloaded JQuery Uncompressed version. Renamed JQuery.1.2.3.js to JQuery.js (I do not know whether this is correct! ) 2) I followed the tutorial for Hello world and typed the following code into an HTML file html head script type=text/javascript src=jquery.js /script script type=text/ javascript alert('here'); $(document).ready(function() { $(a).click(function() { alert(Hello world!); }); }); / script / head body / body /html After opening this HTML file in IE 7.9, I find nothing on the page, not even any javascript error. The code is supposed to display a link, but I do not find any link on the page. Can anyone help me here. - pradeep
[jQuery] Re: callbacks calling callbacks calling callbacks ....
wouldn't nesting the methods work? e.g. script type=text/javascript $('#comp1').trigger('load.comp1', function() { $('#comp2').trigger('load.comp2', function() { $('#comp3').trigger('load.comp3', function() { if (action2()) { // do business logic... } }); }); /script On Mar 5, 5:44 am, h0tzen [EMAIL PROTECTED] wrote: Hello, as everything Ajax-related is (mostly) asynchronous every response is handled using callbacks. I often have the problem that to do action A I have to initialize multiple components on the page (if not initialized yet), then fire 1- n ajax calls, waiting for the callback and so on. this leads to a set of functions chained together by callback-calls. function action() { if (!$('#comp1').is('.loaded')) { $('#comp1').trigger('load.comp1', [ cb1 ]) } if (!$('#comp2').is('.loaded')) { $('#comp2').trigger('load.comp2', [ cb2 ]) } if (!$('#comp3').is('.loaded')) { $('#comp3').trigger('load.comp3', [ cb3 ]) } if (cb1 cb2 cb3 have been called and returned success) { action2(action2-callback) if (action2-callback has been called and returned success) { // do real business logic } } } do you know of any patterns to implement these callback-chains more elegantly? how do you solve nested, nasty callback-chains?
[jQuery] Re: .html() callback?
I think the OP is adding elements to the dom, and then wondering why the events for the new elements aren't working. after adding elements with .html(), you need to add the events. For example, adding an anchor: $(#header).html('a href=#yo/a').find('a').click(function() { alert('click'); return false; }); -j On Mar 4, 10:53 am, Scott González [EMAIL PROTECTED] wrote: .html() doesn't have a callback because it is synchronous, so any code executed after the .html() call will definitely occur after the html is set. I'm not sure why you're having any problems, but the problem is probably in your code. You'll get better responses by posting a test page. On Mar 4, 8:10 am, alexanmtz [EMAIL PROTECTED] wrote: Hi everyone, Like a lot of methods of jQuery, why the .html() doesnt have a callback? I need that some javascript load when the dom change with .html() (append and others too), and some events are attached with the new elements created by this method. What happens is that sometimes they are attached and other times not. I thing its due the fact that I execute this code: $('#div').html(stuffVar); $.getScript('newEvents.js'); This work sometimes. I would need one way to accomplish this task like this: $(#div').html(stuffVar,function(){ $.getScript('newEvents.js'); }); This way, we would have sure that the html is updated and so we can load the script to attach events. Anyone has idea??? thanks, Alexandre Magno Web Developerhttp://blog.alexandremagno.net
[jQuery] Re: JQuery Hello world not working
wow, the lag on this list is brutal. is there any way of reducing it, so people don't spend time responding to already-answered questions? On Mar 5, 9:34 am, J Moore [EMAIL PROTECTED] wrote: actually, your code doesn't display a link. it sets up an action when the link is clicked. You're missing: a href=#do something/a There might be other problems too if you aren't even seeing the alert message. Download firefox and firebug. IE isn't much help for developing javascript. -j On Mar 5, 5:16 am, pradeep_tp [EMAIL PROTECTED] wrote: Hi All, I am new to JQuery. I did the following to get started with JQuery. 1) Downloaded JQuery Uncompressed version. Renamed JQuery.1.2.3.js to JQuery.js (I do not know whether this is correct! ) 2) I followed the tutorial for Hello world and typed the following code into an HTML file html head script type=text/javascript src=jquery.js /script script type=text/ javascript alert('here'); $(document).ready(function() { $(a).click(function() { alert(Hello world!); }); }); / script / head body / body /html After opening this HTML file in IE 7.9, I find nothing on the page, not even any javascript error. The code is supposed to display a link, but I do not find any link on the page. Can anyone help me here. - pradeep
[jQuery] Re: Div Changer Using Hide And Show
good tips so far. I just wanted to add that using classes and ids works well. a href=# id=blackbook class=showshow blackbook/a a href=# id=redbook class=showshow redbook/a div class=book hidden id=blackbook-contentblackbook stuff.../ div div class=book hidden id=redbook-contentredbook stuff.../div This makes your click function simpler. $('a.show').click(function(){ hide_divs(); var x = $(this).attr('id'); $('#'+ x + '-content').show('fast'); return false; }); The hide_divs method is also a bit simpler. var hide_divs = function(){ $('div.book').hide('fast'); }; You might notice that the div has a hidden class. This just makes initialization simpler, since the items are hidden on page load. The css would be something like: div.hidden { display: none; } -j On Feb 22, 4:02 am, andrea varnier [EMAIL PROTECTED] wrote: On 21 Feb, 23:03, Sientz [EMAIL PROTECTED] wrote: $('a#blackbook').click(function() { //HIDE DIVS hide_divs(); //SHOW LISTED DIV $('.blackbook').show('fast'); return false; }); you see you got all these functions that basically do the same thing. if an anchor has an id, they show the corresponding div I think you could do it like this $('a[id]').click(function(){ hide_divs(); var x = $(this).attr('id'); $('div[class= + x + ]').show('fast'); return false; }); and should do the same thing. but you could go further, and use classes in a different way. let's say that instead of calling them divs with 'human' names, we can use more 'efficient' names, like: hs_a hs_b hs_c hs_d ... where hs stands for hide/show (just an example). in this way the function hide_divs becomes something like var hide_divs = function(){ $('div[class^=hs]').hide('fast'); /* this selector looks for the div(s) that have a classname that starts with the string 'hs' */ }; then you give corresponding id's to the anchors, so the other on I wrote before: $('a[id^=hs]').click(function(){ hide_divs(); var x = $(this).attr('id'); $('div[class= + x + ]').show('fast'); return false;});
[jQuery] Re: a small accessibility rant
Well, a pixel could be a tiny dot or it could be 5mm. So, really, isn't saying font-size: 11px proportional too? It sounds like your friend needs a better screen magnifier. Increasing just the font size in the browser is a hack. The one build into OS X (see 'universal access' in system prefs) is excellent. It just zooms the whole screen and everything on it (fonts, divs, gifs, etc.). -j On Feb 14, 11:44 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Before (trying to) adopt jQuery, I've never used Javascript to control content. In reading hundreds of blogs by Javascript developers over the past weeks, I've been alarmed by their attitude to accessibility. It's not just a matter of 'political correctness', and it's not just about minority users. One tiny example: a friend of mine has rubbish eyesight - she's not blind, she's fit to drive - she has her screen resolution set to LARGE so she can read it. The other day, she wanted to open a new 'internet-only' savings account. This is business; she has quite a lot of money to invest. The idiot who made that bank's website hadn't accounted for variable fonts; on her screen, the text overwrote the fields! So, she could not open this account, which is only available via the Web, because the form was unusable. The bank may as well have advertised the account as only available to savers with normal eyesight! Things like this, you can fix very simply by making all your sizes proportional - if my friend then has to scroll off the screen to fill the form, she don't care, as long as she can read complete it. All of my problems with jQuery, so far, have been to do with trying to solve basic accessibility issues. I understand why making a site do something feels more important! It's more exciting. But I wish you would, at the same time, ensure a readily-available alternative that can be used as well. Just a gentle reminder :) Cherry.http://jquery.cherryaustin.com
[jQuery] Re: Selecting Descendents of This
does this work? $(this).find('ul').toggle(); On Feb 12, 5:14 pm, studiobl [EMAIL PROTECTED] wrote: I'm having trouble selecting descendents of this So, this works to initially hide uls: $(.treeHeader ul).toggle(); But this doesn't work to toggle them: $(.treeHeader).click(function(){ $(this + ul).toggle();});
[jQuery] Re: returning an object array to a JS function - doesnt work
you can't return a value from an anonymous function! think about it: you call $.get() and pass in an anon function as a parameter. $.get() returns basically immediately, and then sometime later (much later) your anon function will be called. Where does the return value of anon go? Nowhere. That's why you have to either process the result of your ajax call in the anon method you pass in. (You can also stick the results in a variable to be processed later, but that's a bit messier.) -j On Feb 12, 10:04 pm, jquertil [EMAIL PROTECTED] wrote: Hi, I'm mixing regular javascript with Jquery and for some reason I cannot pass a return value back - any idea why? output = loadXMLarray('echo.php','datatable1') ); alert (output); // does not work function loadXMLarray(scripturl,variable){ $.get(scripturl,{xml:variable}, function(data){ // loading my XML objectArray = new Array(); // setting up my array to hold objects with $(data).find('row').each(function(i){ // iterating through my XML source rowObj = new Object(); // adding attributes to my object rowObj.col1 = $(this).children('col_1').text(); rowObj.col2 = $(this).children('col_2').text(); rowObj.col3 = $(this).children('col_3').text(); objectArray.push(rowObj); // populating my array }); alert(objectArray); // this works return objectArray; // does not work }); return objectArray; // tried it here as well but that returns nothing }
[jQuery] Pagination plugin (and jquery plugin instances in general)
I'm using the pagination plugin at the top and bottom of a list. Works great, except that the two instances are independent. Clicking on page 3 in the one pagination instance will not change the other. I've thought of various solutions/workarounds, but they all involve getting access to the pagination instance. Is this possible? Here's some sample code... $(document).ready(function() { // there are two divs of class pagination. $('div.paging').pagination(list.length, {callback(pg): drawpage(pg);}); // so how can i access or call a method on these instances? // assuming that the divs have the ids #pager1 and #pager2 // is there a way to access the pagination instance from jquery internals? }); -j
[jQuery] Re: Animate function. Once I animate how do I er.... de... animate
um, use a variable? var x = true; $(#container).click(function() { if (x) { $(#container).animate({marginTop: -=237px}, slow); } else { $(#container).animate({marginTop: 400px}, slow); } x = !x; }); On Feb 13, 3:05 pm, somedude [EMAIL PROTECTED] wrote: Ok sorry about the title, don't know what to say. I have a site for a client, and when you click a certain div it animates with a marginTop -=300px like effect so the div is just visible sliding in behind another div. Now, if the user clicks the div again it will do the same and go up by 300px. What I want is a toggle like function where if you click it the second time it now adds the 300px back and the div is back in place. so right now here is the setup code, very simple: $(#container).click(function() { $ (#container).animate({marginTop: -=237px}, slow); }); There has to be an easier way then to set a cookie stating Clicked=yes then reset to No Anyone? Thanks
[jQuery] Re: Correct way to read JSON string
This isn't specific to jQuery. One way... var x = '{a:123,b:456}'; // json eval('var z='+x); z is now an object. z.a = 123, etc. -j On Feb 13, 3:47 pm, wolf [EMAIL PROTECTED] wrote: hi, what is the correct way in jQuery to decode = deserialize a JSON string? jQuery itself can obviously do it as it can formulate and read JSON via Ajax. But i seemingly can't find a callable in jQuery that allows me to decode JSON without issuing an HTTP request. That is strange to me. Can you help? _wolf
[jQuery] Re: jQuery caching DOM refferences? Performance issues
How would do you call flyout()? -j On Feb 11, 12:03 pm, Jeffrey Kretz [EMAIL PROTECTED] wrote: Personally, I do something like this, say for an event that is called frequently: function flyout(e) { if (!this.$self) this.$self = $(this); this.$self.show(); } JK -Original Message- From: jquery-en@googlegroups.com [mailto:[EMAIL PROTECTED] On Behalf Of Michal Popielnicki Sent: Monday, February 11, 2008 5:41 AM To: jQuery (English) Subject: [jQuery] Re: jQuery caching DOM refferences? Performance issues Hi there, and thanks for the reply. Actually there is no visible bottleneck yet and I can't really point it out since the javascript behind the app is massive and it results in poor performance under Opera (which is very strange, since its the fastest browser supporting JS) . However I was wondering about ways that the performance can be improved ad that was generally where I suggested the solution and basing on Your opinion it should work. If there are any other opinions/suggestions I'd be glad to hear them. Thanks in advance Best regards! On 11 Lut, 01:55, J Moore [EMAIL PROTECTED] wrote: You can profile javascript with firebug and see total calls for different approaches and how long they take. That said, $('#id') is fast, since it is basically getElementById() a native javascript method. However, if you call $('#id') 100x, you'll see that it's faster to cache it in a variable. e.g var id = $('#id'); for (i=0;i100;i++) { id.append(pnumber +i+/p); } what is the bottleneck in your code? -j On Feb 10, 6:12 pm, Michal Popielnicki [EMAIL PROTECTED] wrote: Hi there! I've been dealing with some performance clean-up of a code of a web- app that I wrote and I was wondering if jQuery does caching of the DOM references. Lets say I have a function: function myFunction(){ $('#foo').attr(bar); } I frequently refer to the function, so is it the case that each time I launch it, the DOM is scanned for element with foo id? Or maybe this reference is somehow cached? If its not, then maybe doing something like this would speed up the code execution: function DomLinker(){ this.foo = $('#foo').attr(bar); function myFunction(){ domMember.foo.attr(bar);} $(document).ready( domMember = new DomLinker(); } Please keep in mind that we talk about case of many executions of myFunction Please share your thoughts on this one. Best regards
[jQuery] Re: IE/FF Memory Leak
How are you measuring memory leaks? -j On Feb 11, 10:16 am, optimalcapacity [EMAIL PROTECTED] wrote: I am a newbie to jQuery so this may be a simple answer... My goal in this exercise is to return a specific html table block (table.DetailTable) from a dynamically generated html page which is the result of a servlet call into a div (xyz). The issue I am having is that whether I set the timer interval to 1 second (1000) or 30 seconds (3), this code is leaking horriblly. I verified the leak in both IE6 and FF 2.0.0.12. Here's the abbreviate code snippet that I'm working with: function loadMyData(){ var t; $(#xyz).load(http://URLtable.DetailTable,{Param1:Param1Value}); t = setTimeout(loadMyData(), 5000); } $(document).ready( function(){ loadMyData(); } ); Any help with this issue is very much appreciated!
[jQuery] Re: Using jQuery inside an ordinary function notes!
(also the 'el' variable in your code is undefined.) On Feb 11, 1:28 pm, saidbakr [EMAIL PROTECTED] wrote: Hi, I think that my problem is complicated. I already done what you have told me due to the following requirement: I have another function used for doing form validation which I named it as formVal(). Inside formVal() I called avaChk() in a conditional if statement i.e. if (avaChk()){ I modified avaChk() by adding after alert('222) and alert('333') return false and return true respectively. Calling avaChk() leads only alert('111') and alert('444'). In other word avaChk() did not return true or false it just return the code outside $.ajax. You may notice that the code $.ajax is placed inside success handler. This is making me mad!!! Best regards, Said Bakr On Feb 11, 5:44 am, Karl Rudd [EMAIL PROTECTED] wrote: It's a easy misunderstanding to have when you first begin to use AJAX. Remember that the first 'A' in AJAX stands for Asynchronous. You ask the browser (via jQuery's ajax function) to retrieve a URL and you give it a function that it will call with the result when it has retrieved it. The browser may take 50 milliseconds or 50 seconds to retrieve the URL, you can't be sure how long. In the mean time the browser (and your JavaScript function) continues on its way. So you must put all the code for handling the results in the success (or error) handler function. Does that help? Karl Rudd On Feb 11, 2008 1:59 PM,saidbakr[EMAIL PROTECTED] wrote: Hi, I have very little knowledge about javascript. I used it with ordinary functions and the code of jquery may make me confused. I used it in a javascript function some thing like that: script function avaChk(lnk,id){ alert('111') ob = document.getElementById('id'); $.ajax({url: 'chk_user.php',type:'GET', data: id+'='+ el, cache: false, dataType: script, success: function(data, textStatus){ if (data == 0){ alert('222'); } else{ alert('333'); } }, error: function(x,txt,err){ $(#waitImg+lnk).remove(); alert('Could not check...'+\n+'The server may down or busy. Retry again after a while.'); } }); alert('444'); } What I noticed is, when I call the function avaChk(), for me, very strange thing is happened. ;) I think the jQuery proffesional will know it: The alert sequence as I respect is 111, 222 or 333 then 444 what happened is not like above, it was 111,444, 222 or 333 !!! I respected that the jQuery code should be executed before the alert(444). In real world this prevent me from using the value of data or return it through another function. What's wrong in my understanding and how can I overcome this problem?- Hide quoted text - - Show quoted text -
[jQuery] Re: Using jQuery inside an ordinary function notes!
saidbakr, you're still not understanding how the method calls are 'asynchronous'. Read Karl's reply again. It's full of good info. adding a return true or return false to your success or error methods won't do anything. You need to add code to fully handle the response. (Basically where you are calling alert('222') and alert('333')) you need to hide your status indicator, display a message to the user or whatever.) -j On Feb 11, 1:28 pm, saidbakr [EMAIL PROTECTED] wrote: Hi, I think that my problem is complicated. I already done what you have told me due to the following requirement: I have another function used for doing form validation which I named it as formVal(). Inside formVal() I called avaChk() in a conditional if statement i.e. if (avaChk()){ I modified avaChk() by adding after alert('222) and alert('333') return false and return true respectively. Calling avaChk() leads only alert('111') and alert('444'). In other word avaChk() did not return true or false it just return the code outside $.ajax. You may notice that the code $.ajax is placed inside success handler. This is making me mad!!! Best regards, Said Bakr On Feb 11, 5:44 am, Karl Rudd [EMAIL PROTECTED] wrote: It's a easy misunderstanding to have when you first begin to use AJAX. Remember that the first 'A' in AJAX stands for Asynchronous. You ask the browser (via jQuery's ajax function) to retrieve a URL and you give it a function that it will call with the result when it has retrieved it. The browser may take 50 milliseconds or 50 seconds to retrieve the URL, you can't be sure how long. In the mean time the browser (and your JavaScript function) continues on its way. So you must put all the code for handling the results in the success (or error) handler function. Does that help? Karl Rudd On Feb 11, 2008 1:59 PM,saidbakr[EMAIL PROTECTED] wrote: Hi, I have very little knowledge about javascript. I used it with ordinary functions and the code of jquery may make me confused. I used it in a javascript function some thing like that: script function avaChk(lnk,id){ alert('111') ob = document.getElementById('id'); $.ajax({url: 'chk_user.php',type:'GET', data: id+'='+ el, cache: false, dataType: script, success: function(data, textStatus){ if (data == 0){ alert('222'); } else{ alert('333'); } }, error: function(x,txt,err){ $(#waitImg+lnk).remove(); alert('Could not check...'+\n+'The server may down or busy. Retry again after a while.'); } }); alert('444'); } What I noticed is, when I call the function avaChk(), for me, very strange thing is happened. ;) I think the jQuery proffesional will know it: The alert sequence as I respect is 111, 222 or 333 then 444 what happened is not like above, it was 111,444, 222 or 333 !!! I respected that the jQuery code should be executed before the alert(444). In real world this prevent me from using the value of data or return it through another function. What's wrong in my understanding and how can I overcome this problem?- Hide quoted text - - Show quoted text -
[jQuery] Re: Slowness on IE6
i don't see any jquery at the link you've given. -j On Feb 8, 3:41 pm, eltbb [EMAIL PROTECTED] wrote: Hi, I am using the jquery.treeview, and when first building a tree, on IE 6, the cpu usage goes up for a few seconds. Also whenever expanding or collapsing nodes, the cpu usage seems very high. As a result it appears sluggish. Has anyone else experienced this with IE6? For an example, please seehttp://unao.com/waterville Regards, Philippe
[jQuery] Re: Design question.
hey shawn, this is an old thread, but i have another option for you: closures. jquery is all about closures, but i only recently fully got how they worked and how cool they can be. In the case of a table of results, where each row has a button, closures avoids the ugliness of parsing the dom looking for an id. Using your original example of a list of employees, we could add an action to each employee with a closure. The jQuery each() method makes this easy. script type=text/javascript var employees = [ {id:13, name:'bob'}, {id:14, name:'sue'}, {id:15, name:'joe'} ]; $(document).ready(function(){ var container = $('#results'); jQuery.each(employees, function() { var emp = this; var row = $('trtd' + emp.name + '/td/tr'); $('a href=#delete/a') .click(function() { fire(emp); } ) .appendTo(row); row.appendTo(container); }); function fire(employee) { console.log('todo: fire ' + employee.name + ' id:'+employee.id); } }); /script table id=results/table Now, each link delete, knows which employee to delete. This seems like the cleanest approach. Anyone know how to make this even more succinct? -j On Jan 19, 7:04 pm, Shawn [EMAIL PROTECTED] wrote: hmmm... jQuery.data looks promising. I'll check it out. Thanks for the tip. Shawn polyrhythmic wrote: Hello Shawn, Not having unique IDs will always cause trouble. Not recommended. I've tried various techniques, including building a JS object structure... Something like $(#trigger)[0].extraData = { id: 4 }; ? If you need data stored relative to elements, you could store information with jQuery.data. http://docs.jquery.com/Internals/jQuery.data I have found it to be a very fast way to have data relative to DOM elements. But breaks down when you start needing to access multiple items for a given action... You can store as much data attached to an element as you need with key/ value pairs with jQuery.data. If you need to 'trigger' reading data from a link in a different location, you could store the ID in the link's REL (or store the ID with jQuery.data) and then grab the data from there. With jQuery.data, if you can find the element somehow, you can retrieve all its data. HTH and hope it all makes sense... Charles doublerebel.com On Jan 18, 8:00 pm, Shawn [EMAIL PROTECTED] wrote: A good start, but I see a few issues here. Both from the same line of code: var id = $(this).parent().parent().attr('id).substr(1); 1) the structure has to be known for this to work. (i.e. the ancestor element two levels up contains the ID). This may be a non-fixable thing though. You're going to have to know where the information is stored somehow. And doing something like $(this)[0].extraData = $(#IDelement) leads to circular references... 2) the ID now needs to be processed. For a small number of items this isn't bad, but as the complexity of your page increases, you end up with a whole set of modifcations that have to be parsed out. For instance, in your sample you have id=u4. But if that same ID has to be used in other places, you end up with x4, y4, etc. Maybe it's a moot point though in that you are just stripping off the text that makes the ID unique, and then just working with the value anyways - in which case it'll always be .substr(1), which will always be relatively fast. 3) This deals well enough with items where you have a single piece of information needed (the ID in this case). But breaks down when you start needing to access multiple items for a given action. I have a specific example where I need to know the employee name (stored at the TR level), and the date represented by the cell clicked on. These two items are passed to an Ajax call for further processing. Using the date as an ID is a non-starter (same date used on multiple rows). But using it as a class is also problematic - what if you had class=1-Jan-2006 odd taskHeader ? 4) Scalability. with smaller data sets, the amount of processing is negligible and can be safely ignored. But increase the volume of data and the amount of processing becomes a problem. If it takes 10 milliseconds to process one item, what happens when you have 1000+ items? Then again, I think I mixing up different aspects of the problem - creating the output, and then dealing with events afterwards. Either way, I'm still looking for methods that would minimize performance issues. I do have a specific sample in mind, but this issue is rather generic I think. Thanks for the response. I think it's a good starting point. :) Shawn J Moore wrote: A simple work around is to append a character to the id to keep them unique. But also, store the ID in the parent TR. e.g. tr id=u4 td class=empBob Smith/td tddiv class=1-Jan-2008link 1/div/td /tr Then you can get the id with $('div.1-Jan-2008').click(function
[jQuery] Re: jQuery caching DOM refferences? Performance issues
You can profile javascript with firebug and see total calls for different approaches and how long they take. That said, $('#id') is fast, since it is basically getElementById() a native javascript method. However, if you call $('#id') 100x, you'll see that it's faster to cache it in a variable. e.g var id = $('#id'); for (i=0;i100;i++) { id.append(pnumber +i+/p); } what is the bottleneck in your code? -j On Feb 10, 6:12 pm, Michal Popielnicki [EMAIL PROTECTED] wrote: Hi there! I've been dealing with some performance clean-up of a code of a web- app that I wrote and I was wondering if jQuery does caching of the DOM references. Lets say I have a function: function myFunction(){ $('#foo').attr(bar); } I frequently refer to the function, so is it the case that each time I launch it, the DOM is scanned for element with foo id? Or maybe this reference is somehow cached? If its not, then maybe doing something like this would speed up the code execution: function DomLinker(){ this.foo = $('#foo').attr(bar); function myFunction(){ domMember.foo.attr(bar);} $(document).ready( domMember = new DomLinker(); } Please keep in mind that we talk about case of many executions of myFunction Please share your thoughts on this one. Best regards
[jQuery] Re: Using Literal Objects in Javascript with JQuery
Yes, great screencast. (I think i learned a little portuguese too.) A question about literal objects - is it fundamentally different than using prototype? // // example 1: literal obj // var Counter = { container = $('#counter'); start: 1, init: function() { container.val(start); } } $(document).ready(function() { Counter.init(); }); // // example 2: prototype obj // function Counter() { var start = 1; var container = $('#counter'); }; Counter.prototype.init = function(obj) { this.container.val(this.start); }; var c = new Counter(); c.init(); certainly the object literal method looks a bit cleaner. It is possible to create multiple instances? Any other advantages? -j On Feb 6, 9:59 am, rics [EMAIL PROTECTED] wrote: Hello, Here is a great screencast tutorial on how to better organize your js code with Literal Objects and JQuery. The author is brazilian and he talks portuguese, but you can follow and understand the tutorial without any sound, just seeing what he do on screen. http://www.tuliofaria.net/arquivos/videotutoriais/jsobjetoliteral/ Good luck! rics
[jQuery] Re: reusing jqmodal container
Looks to me like you're missing a closing bracket, so your 2nd click method ($('a#enviar_jqm_trigger') is encapsulated in the first ($ ('a#corregir_jqm_trigger'). No? -j On Feb 5, 9:12 am, Sebastián Würtz [EMAIL PROTECTED] wrote: my script $('a#corregir_jqm_trigger').click(function(){ $('#jqm').jqm({ajax: this.href, trigger: '#corregir_jqm_trigger', modal: 'true', target:'div.jqmAlertContent', overlay: 50, overlayClass: 'whiteOverlay', cache: false, onLoad: preparar_corregir_form}).jqmShow().jqDrag('.jqDrag'); $('.jqmdTC').html('Enviar correccioacute;n de la paacute;gina:'); jqm_windows(); return false; }); $('a#enviar_jqm_trigger').click(function(){ $('#jqm').jqm({ajax: this.href, trigger: '#enviar_jqm_trigger', modal: 'true', target:'div.jqmAlertContent', overlay: 50, overlayClass: 'whiteOverlay', cache: false, onLoad: preparar_envio_form}).jqmShow().jqDrag('.jqDrag'); $('.jqmdTC').html('Enviar esta noticia por email'); jqm_windows(); return false; }); use the same jqm container, i pass the windows title via $('.jqmdTC').html, but if i click in the first link and then in the second the second allways showme the first ajax response. And im calling other thing! how i can fix this?
[jQuery] Re: JQuery takes 80% of my core2Duo proc on DOM element inserts
I've heard a few people mention the building an array and then using .join(''). I found that good-old-fashioned string concatenation was faster - and the syntax a bit cleaner. There's a neat test on this page. The joining arrays seems is a bit slower for me. (Firefox on OS X) http://www.quirksmode.org/dom/innerhtml.html Is joining arrays (i.e. the innerHTML 2 test) faster for you? -j On Feb 6, 1:37 pm, polyrhythmic [EMAIL PROTECTED] wrote: You will have an easier time creating a single append by ,join() -ing an array of elements and adding them as a block. Forcing jQuery to evaluate each one individually creates a lot of repetition. The .domManip() code in the source is pretty legible, if you're curious. Charles On Feb 5, 3:00 am, George GSGD [EMAIL PROTECTED] wrote: I think it's generally proven that inserting dom objects is much slower than innerHTML, for the kind of inserting you're trying, that might be worth investigating... On Feb 4, 1:57 pm, Ashish [EMAIL PROTECTED] wrote: Hi , I am very new to jquery. I am using jquery 1.2.2 . I use jquery tablesorter to insert around 400 rows to a table. The data is collected using an Ajax call. When new rows are inserted to the table the CPU utilization shoots up to 80%. All browsers freeze until the table is populated :( I tried to insert 400 divs to a single div and faced the same problem. This rules out a problem with tablesorter. Does jquery attach a lot of handlers to dom events that make appends very slow ? Any suggestions would be much appreciated. Thanks and regards, - Ashish
[jQuery] Re: OT: how to benchmark user hardware?
First, I would try to optimize your code. Make sure that you are calling as few $() methods as possible. (e.g. build strings and set with html() instead of repeatedly calling append() or after(). Firebug can also help you profile.) But if your code is as tight as it can be, then why not a setting on the page so the users can select their level of fanciness? Even if someone has a monster computer, it might be busy encoding video or something, and they would want the low-fi version. -jason On Jan 22, 6:05 am, Alexandre Plennevaux [EMAIL PROTECTED] wrote: Hi friends, i have a question slightly off topic: my jquery-based experimental application is very visual, and renders quite well on recent pcs, but not so good on old ones: i'm moving too many elements for these old bastards. I would like to explore the possibility to adapt the content to the user's setup so that it degrades gracefully, and still feel responsive. so i'm thinking about a scheme like: 1/ detect user setup or perform some tests, to determine the available CPU, graphic Card, RAM, browser,OS. It may not even be necessary to know these datas, if we run a test that just tells us if the end user specs are speedy or not. 2/ send a different javscript file according to the results of the benchmark. Has anyone done somethiing similaror have any thought about this? Thank you, Alexandre
[jQuery] Re: creating a table from an array
Firebug shows you the HTML as it understands it. So if it doesn't look right, it usually means you are creating invalid HTML. The biggest problem with your example, is that you are calling append() repeatedly, and I don't think the elements are being inserted where you expect. What type of element is #mytable? If it is an anchor tag, then you are appending your entire table inside an a element! Probably not what you wanted. I would suggest you use strings to build your HTML, and then just add it all at once. Cleaner, simpler and faster. Something like... var r = ''; for (...) { r += trtd + data + /td./tr; } $('#a-div-to-hold-your-table').html('table'+r+'/table'); -jason On Jan 19, 1:59 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: My use case is pretty common and surely it is in some tutorial but I cannot find the right place where to look, so let me post here. I would like to generate an HTML table from JSON data coming from a server. I am a very green when it comes to Javascript, so naively I wrote the following code: var a = [[a,b,c],[1,2,3],[4,5,6]]; // the array will be read from the server in the real app $(#mytable).click(function() { $ (this).append(table); $ (this).append(thead); $ (this).append(tr); for(j=0; j3; j++) { $(this).append(th + a[0][j] + / th);}; $(this).append(/ tr); $(this).append(/ thead); $ (this).append(tbody); for(i=1; i3; i++) { $ (this).append(tr); for(j=0; j3; j++) { $(this).append(td + a[i][j] + / td); }; $(this).append(/ tr); }; $(this).append(/ tbody); $(this).append(/ table); }); When I click on #mytable and I look at the generated HTML with Firebug I get table/ thead/ tr/ tha/th thb/th thc/th tbody/ tr/ td1/td td2/td td3/td tr/ td4/td td5/td td6/td What's happening here? It seems .append is inserting closed tags instead of what I told it to append. I am pretty convinced that I should have generated the tags with document.createElement instead, but I did expect .append to work for a quick and dirty experiment. Anybody here can shed some light? TIA, Michele Simionato
[jQuery] Re: Callback-return into global variable
Couple of thoughts: 1) $.each() is not for moving through an array. (is for doing something to each matched DOM element) try: for(item in _json) { alert('item:'+item);} 2) try defining your global as an object. e.g. var _json = {}; -jason On Jan 16, 2:17 am, Niels [EMAIL PROTECTED] wrote: Is there any way to put a return from within a callback into a global variable? I'm trying to retrieve JSON-values in one statement, and output them in another statement; and code looks like this: var _json; function load_comments(id, params) { if (typeof id != 'number' typeof id == 'object' params == null) { // Only the params were specified. _params = process_params(id); $.getJSON(paths.get_comment, _params, function(data) { _json = data; return _json; }); console.info('1 : $.getJSON(' + paths.get_comment + ', ' + _params + ')'); } } function display_comments() { load_comments(); $.each(_json.comments, function(comment) { $(#recent-comments-list).append(li + comment.content + / li); }); } Unfortunately, _json seems to remain undefined... What am I doing wrong? Or is there really no way to accomplish this? Thanks a lot! Niels
[jQuery] Re: Using getJSON...not successful
to isolate the problem, make your script dump out something like: {a: hello} are you sure it's not a 404? is jquery being found? It could be lots of things... if you haven't already, install firebug (and use firefox). It will save you a lot of frustration. On Jan 18, 6:13 pm, gms [EMAIL PROTECTED] wrote: Hello, I am new to JQuery. I'm trying to get a JSON response back from my django view. However, I guess my data never gets loaded successfully. Does anybody know what I'm doing wrong? script $(document).ready(function(){ $(#first).click(function(){ $.getJSON(/mysite/myajax, function(data) { alert(Here); }); });}); /script def myajax(request): a = Testimonial.objects.all()[:3] response_dict = {} response_dict.update({'a': a}) return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript') /// Whenever I access this page and click on my div that contains the id 'first'...nothing happens. I should see an alert that says 'Here'. Any Suggestions on what I'm doing wrong? Thanks
[jQuery] Re: Design question.
A simple work around is to append a character to the id to keep them unique. But also, store the ID in the parent TR. e.g. tr id=u4 td class=empBob Smith/td tddiv class=1-Jan-2008link 1/div/td /tr Then you can get the id with $('div.1-Jan-2008').click(function() { var id = $(this).parent().parent().attr('id).substr(1); alert(do something with employee id:+id); }); would that work? On Jan 18, 7:43 pm, Shawn [EMAIL PROTECTED] wrote: I have a case that is going to prove to be processor intensive, so am looking for suggestions on how to make the code as responsive as possible. In addition, I'm a little stumped on how to resolve a problem with my IDs. I have a page that will list hundreds of people (I'm ignoring paging for now, it's just not quite suitable). For each person there will be a number of actionable items/links. Each of these links imply to do something different, but all rely on the employee ID, These links will also be embedded in sub-structures (divs/tables, etc.) So a sample of one row might look something like this: tr tdBob Smith/td tddivlink 1/div/td tdtabletrtdlink2/td/tr/table/td /tr (this is very contrived to help illustrate the design issues... :) Now the problem. If the first link (though it could be anywhere on the row) were to trigger a Cluetip with details for that employee and item, I'll need the employee ID, and supporting information (a date say, based on what column it's in). In my current code I've done this: tr td id=4Bob Smith/td tddiv id=4 class=1-Jan-2008link 1/div/td /tr Now this isn't valid HTML because the IDs are not unique. But, I need the ID to do the needed processing. I can't just ask for the first sibling's ID, because my trigger elements are embeded in other structures. The content is dynamic, so it may or may not have the same structure (it would be one of a small handful of possible structures) each time - so I can't embed the structure (i.e. .parents(tr).children(td:first) ). My reasoning here is that if I put the target ID as close as possible to the trigger element, there is less processing needed to get that ID - which is a large factor when dealing with hundreds of rows on the page. So, my question is what others are doing in this sort of situation. I've tried various techniques, including building a JS object structure with the pertinent data, but keep hitting a performance issue. Maybe I need to embed an object on each of my trigger elements that contains the needed data? Something like $(#trigger)[0].extraData = { id: 4 }; ? But won't this run into run-away memory usage when I'm dealing with potentially thousands of these triggers (multiple triggers for each employee). If it helps conceptually, think of a table with one employee per row, and each of the remaining columns being a day. Each day needing a trigger to show a Cluetip for what the employee is doing that day. I do realize my definitions are kinda simplistic, but hopefully there is enough there to get the issue across. For me to define the full picture would need a book or three... :) Thanks for any input.