Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Ned
May 23, 2002

by Hand Knit
jQuery is a Javascript framework that gets a lot of love in CoC but doesn't have it's own thread so I decided to make one.

While there are lots of other Javascript libraries out there, jQuery is quickly becoming the standard library for web development. Both Microsoft and Nokia have announced they are integrating it with their development environments.

The two areas where I find jQuery to be most useful are presentation and AJAX. The presentation layer of a website can be quite complex - especially if you have customers who want advanced effects. More and more websites are replacing Flash functionality with jQuery for SEO purposes. AJAX doesn't really require a strong library to be good and the syntax for AJAX in jQuery is very simple.

I have worked at quite a few places over the last year and I have taught a lot of coworkers how to use jQuery. I think that many folks in CoC would benefit greatly from learning jQuery.

I'll update this post over time to make it more informative and add good examples of jQuery code.

This documentation is very easy to use. Sometimes the docs on jQuery.com go down or get slow.
http://www.visualjquery.com/1.1.2.html

Ned fucked around with this message at 22:30 on Sep 30, 2008

Adbot
ADBOT LOVES YOU

Dromio
Oct 16, 2002
Sleeper
I'm in the midst of a javascript-crazy project and jquery is definately helping. The simplicity of DOM navigation and modification has greatly simplified my life.

But I get a bit concerned when I have to delve into using a "plugin". Like using jquery.canvas. Sometimes things just don't work and using a hack on top of a hack on top of a hack makes me nervous.

KuruMonkey
Jul 23, 2004
I took 2 years out of web programming (trained to be a teacher) and in that period Javascript seems to have gone from something that I (honestly) advised people to avoid where possible to a (reasonably) mature system that forms a third leg of "delivered to client side" code.

The reason is that jQuery (with some caveats) makes the DOM something that is actually useful and workable. Being able to access page elements in .js via css selectors is SO sensible!

Oh yeah; and jQuery is actually documented in reasonably clear english!

There are some caveats though; you have to be careful with the syntax as it can quickly devolve into a LISP-like parenthesis orgy, and javascript itself still suffers from a failure mechanism that strongly resembles a deaf-mute flipping you the bird.

And as said above, the quality of plugins is seriously variable (jquery.timers is a goddamn joke, for instance - its actually less intuitive than the standard timeout system)

I've found that the best thing to do is to build my own components with jQuery - I work with PHP (LAMP+CodeIgniter+jQuery basically) so I code up PHP to generate xhtml for a given component, using standardised markup, css classes and ids with a seperate .css for the component, then a seperate .js file for the component's jQuery stuff. (then at depoyment time I can aggregate the .css and .js files together)

Makes 'add an image rotator' or some such a much more straight forward process.

Some specifics I found / issues I'd be interested in work arounds for:

you can't attach hover events to areas in image maps (don't do anything in IE) you need to set onMouseOver and onMouseOut manually (in the xhtml)

jquery.timers doesn't work properly if you want multiple items with independant timers (or at least; I 'attached' timers to two elements, with different 'labels' and got 2 timers firing on one of them...)

Reviews of plugins that we've used and found to be good / bad would be a nice feature for this thread.

Oh; and OP; link to https://www.visualjquery.com drat fine documentation.

the onion wizard
Apr 14, 2004

What's the deal with the MIT license, is complying with it really as simple as just including the license?

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

triplekungfu posted:

What's the deal with the MIT license, is complying with it really as simple as just including the license?

Yes.

SixPabst
Oct 24, 2006

If you didn't see it, jQuery is going to be integrated with ASP.NET in the near future, including IntelliSense in Visual Studio.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

mintskoal posted:

If you didn't see it, jQuery is going to be integrated with ASP.NET in the near future, including IntelliSense in Visual Studio.

It was posted in the OP?

Ned posted:

Both Microsoft and Nokia have announced they are integrating it with their development environments.

duck monster
Dec 15, 2004

triplekungfu posted:

What's the deal with the MIT license, is complying with it really as simple as just including the license?

MIT is pretty much a "do whatever the gently caress you want" type license.

jquery is amazing, and the heavy use of lispy closures really helps clarify readability and helps encourage functional programming styles. The fact that you can *mostly* push all the javascript, including hooking triggers, outside the HTML gives me a hardon. This is great stuff.

And yes, the plugin quality is very hit and miss. But its javascript, whatya expect.

Dromio
Oct 16, 2002
Sleeper
And within a few days of using jquery, I have filed my first bug :(.

If an element is positioned using the css "bottom" property, then jquery.ui.draggable() is applied to it, the bottom will remain fixed while you drag it around. It's not the most common use case, but it's hurting me right now.

Still way better off for using jquery than I would be without it though :)

Pardot
Jul 25, 2001




http://lsrc2008.confreaks.com/10-yehuda-katz-using-jquery-with-ruby-web-frameworks.html

That's a good (once he gets past the first bit of live coding failure) presentation on doing BDD with screw unit and jquery.

Digital Spaghetti
Jul 8, 2007
I never gave a reach-around to a spider monkey while reciting the Pledge of Alligence.

Dromio posted:

And within a few days of using jquery, I have filed my first bug :(.

If an element is positioned using the css "bottom" property, then jquery.ui.draggable() is applied to it, the bottom will remain fixed while you drag it around. It's not the most common use case, but it's hurting me right now.

Still way better off for using jquery than I would be without it though :)

The great thing is there is a team of people who will actually look at the code. I have write access to the jQuery repo, I really need to get back to fixing some bugs in it!

Dromio
Oct 16, 2002
Sleeper
Is there some way to insert conditionals into one of these jquery chains? I'm using the jquery html canvas plugin to draw a curved box around an element like this:
code:
$("#myCanvasElement").polygon(
         [0, 0],
         [
         ['moveTo', [ntr, nt]],
         ['quadraticCurveTo', [nr, nt], [nr, ntt]],
         ['lineTo', [nr, ntb]],
         ['quadraticCurveTo', [nr,nb], [ntr, nb]],
         ['lineTo', [ntl, nb]],
         ['quadraticCurveTo', [nl, nb], [nl, ntb]],
         ['lineTo', [nl, ntt]],
         ['quadraticCurveTo', [nl, nt], [ntl, nt]],
         ['lineTo', [ntr, nt]]
         ],
         { 'fill': true, 'stroke': true, 'close': true },
         {
             'fillStyle': 'rgba( 150, 195, 150, .9)',
             'strokeStyle': 'rgba( 0, 0, 0, 1)',
             'lineWidth': 1
         }
         );
I want it to be a "speech bubble" with one corner pointing to a point on screen, but the corner chosen depends on the relation of this element's position to that point. Is there some way for me to toss a conditional into the middle of this chain?

Edit: Oh crap, forgot that I'd switched to this "polygon" function that isn't even a chain. Ugh.

Dromio fucked around with this message at 20:20 on Oct 3, 2008

duck monster
Dec 15, 2004

Dromio posted:

Is there some way to insert conditionals into one of these jquery chains? I'm using the jquery html canvas plugin to draw a curved box around an element like this:
code:
$("#myCanvasElement").polygon(
         [0, 0],
         [
         ['moveTo', [ntr, nt]],
         ['quadraticCurveTo', [nr, nt], [nr, ntt]],
         ['lineTo', [nr, ntb]],
         ['quadraticCurveTo', [nr,nb], [ntr, nb]],
         ['lineTo', [ntl, nb]],
         ['quadraticCurveTo', [nl, nb], [nl, ntb]],
         ['lineTo', [nl, ntt]],
         ['quadraticCurveTo', [nl, nt], [ntl, nt]],
         ['lineTo', [ntr, nt]]
         ],
         { 'fill': true, 'stroke': true, 'close': true },
         {
             'fillStyle': 'rgba( 150, 195, 150, .9)',
             'strokeStyle': 'rgba( 0, 0, 0, 1)',
             'lineWidth': 1
         }
         );
I want it to be a "speech bubble" with one corner pointing to a point on screen, but the corner chosen depends on the relation of this element's position to that point. Is there some way for me to toss a conditional into the middle of this chain?

Edit: Oh crap, forgot that I'd switched to this "polygon" function that isn't even a chain. Ugh.

Why dont you prepare some variables with the location of the tail thingo, and *then* use your canvas to do it.

Or just not nest it.

Dromio
Oct 16, 2002
Sleeper

duck monster posted:

Why dont you prepare some variables with the location of the tail thingo, and *then* use your canvas to do it.

Or just not nest it.

Making the tail requires that I replace one of the quadratic curves with two lines:
code:
['quadraticCurveTo', [nr, nt], [nr, ntt]],
turns into
code:
['lineTo', [pointerx,pointery]],
['lineTo', [nr,ntt]],
And the relative position of the point to the bubble determines WHICH curve it replaces.

Maybe I can make a variable for each corner, and then replace the one I need to with a single switch statement or something.

Dromio
Oct 16, 2002
Sleeper
I re-wrote it as a jquery chain like so:
code:
//Set up boundaries	
tl = this.position().left;
tt = this.position().top;
tr = this.position().left + this.width()-10;
tb = this.position().top + this.height()-10;
l = tl - settings.cornerRadius;
t = tt - settings.cornerRadius;
r = tr + settings.cornerRadius;
b = tb + settings.cornerRadius;

canvasArea.style(settings.style)
	.beginPath()
	.moveTo([tr, t])
	.quadraticCurveTo([r, t], [r,tt])
	.lineTo([r,tb])
	.quadraticCurveTo([r,b], [tr,b])
	.lineTo([tl,b])
	.quadraticCurveTo([l,b],[l,tb])
	.lineTo([l,tt])
	.quadraticCurveTo([l,t],[tl,t])
	.lineTo([tr,t])
	.closePath()
	.stroke()
	.fill();
But I still don't know how I'm going to conditionally replace on of the quadraticCurveTo() calls with two lineTo() calls to draw a callout.

Edit:
Maybe I can define my own function, .drawCorner() to use in place of the .quadraticCurveTo() calls? Something like:
code:
$.fn.drawCorner = function(controlPoint, pointTo) {
    //figure out relation.  if normal corner do this
    this.quadraticCurveTo([controlPoint[0], controlPoint[1]], [pointTo[0],pointTo[1]])
    //else draw two lines
}; 
But if I replace my quadraticCurveTo() calls with this, I get the following:

quote:

canvasArea.style(style).beginPath().moveTo([tr, t]).drawCorner([r, t], [r, tt]) is undefined
I really need a jQuery ninja.

Edit 2:
Aha, jquery functions have to return a jquery object! I'm closing in on this!

Dromio fucked around with this message at 16:03 on Oct 6, 2008

Dromio
Oct 16, 2002
Sleeper
And finally to finish my spamming of this thread, here's how I got it working:
code:
 jQuery.fn.speechBubble = function(canvasArea, style, settings)
 {
 	//setting defaults
	style = jQuery.extend({
		fillStyle: 'rgba( 255, 255, 200, .9)',
		strokeStyle: 'rgba( 150, 150, 100, 1)',
		lineWidth: 1
	}, style);
	settings = jQuery.extend({
		cornerRadius:10,
		target:null
	}, settings);
	
 	//Special function to draw a rounded corner OR callout,
	//  depending on relation to target
	// 4  1
	// 3  2
	cornersDrawn = 0;
 	jQuery.fn.drawCorner = function(controlPoint, pointTo) {
		cornersDrawn++;
		if (useTarget) {
			switch(cornersDrawn){
				case 1:
					if(targetAbove & !targetLeft){
						return this.drawCallout(pointTo);
					}
					break;
				case 2:
					if(!targetAbove & !targetLeft){
						return this.drawCallout(pointTo);
					}
					break;
				case 3:
					if(!targetAbove & targetLeft){
						return this.drawCallout(pointTo);
					}
					break;
				case 4:
					if(targetAbove & targetLeft){
						return this.drawCallout(pointTo);
					}
					break;
			}
		}
		return this.quadraticCurveTo([controlPoint[0], controlPoint[1]], [pointTo[0], pointTo[1]]);
	}; 
	
	//draws a callout to the target, then back to the return point
	jQuery.fn.drawCallout = function(retPoint){
		this.lineTo([settings.target.midX, settings.target.midY]);
		return this.lineTo(retPoint);
	}

	//if the target isn't null, determine it's relationship to the bubble
	var useTarget;
	var targetAbove;
	var targetLeft;
	if (settings.target != null) {
		useTarget = true;
		settings.target.midX = settings.target.position().left + (settings.target.width() / 2);
		settings.target.midY = settings.target.position().top + (settings.target.height() / 2);
		targetAbove= (settings.target.midY<this.position().top);
		targetLeft = (settings.target.midX<this.position().left);
	}
		
	//Set up bubble boundaries	
	tl = this.position().left;
	tt = this.position().top;
	tr = this.position().left + this.width()-10;
	tb = this.position().top + this.height()-10;
	l = tl - settings.cornerRadius;
	t = tt - settings.cornerRadius;
	r = tr + settings.cornerRadius;
	b = tb + settings.cornerRadius;
	
	//draw rounded rectangle, from top-right curve going clockwise
	canvasArea.style(style)
		.beginPath()
   		.moveTo([tr, t])
		.drawCorner([r, t], [r,tt])
		.lineTo([r,tb])
		.drawCorner([r,b], [tr,b])
		.lineTo([tl,b])
		.drawCorner([l,b],[l,tb])
		.lineTo([l,tt])
		.drawCorner([l,t],[tl,t])
		.lineTo([tr,t])
		.closePath()
		.stroke()
		.fill();
 }
I don't really like using the switch() to determine the relation of the target to the bubble, but it's the best I could come up with.

Dromio fucked around with this message at 16:48 on Oct 6, 2008

Ned
May 23, 2002

by Hand Knit

Dromio posted:

I don't really like using the switch() to determine the relation of the target to the bubble, but it's the best I could come up with.

You are the ninja now, dog!

duck monster
Dec 15, 2004

:siren: Woah look what I found....

http://plugins.jquery.com/project/jqcouch

CouchDB bindings for jQuery.

I genuinely think schemaless databases like couch are the future, but looking at that, holy poo poo would couch make a loving amazing local end store for offline JS apps.

Dromio
Oct 16, 2002
Sleeper
Time for another problem: Any ideas on how I can animate typing text into a textbox one letter at a time, pausing 1 second between each letter?

My current (ugly) code isn't working for IE for some reason:
code:
for (i = 0; i < theTrueValue; i++) {
  letter = theTrueValue.charAt(i);
  $("input#animatedTextBox").val($("input#animatedTextBox").val() + letter);
  pausecomp(1000);
}

// SNIP //

function pausecomp(millis) {
  var date = new Date();
  var curDate = null;

  do { curDate = new Date(); }
  while (curDate - date < millis);
} 
That pausecomp function came from some random blog post and I'm certain it sucks. I just don't know how to do it better. Some sort of setTimeOut() call maybe?

the talent deficit
Dec 20, 2003

self-deprecation is a very british trait, and problems can arise when the british attempt to do so with a foreign culture





duck monster posted:

:siren: Woah look what I found....

http://plugins.jquery.com/project/jqcouch

CouchDB bindings for jQuery.

I genuinely think schemaless databases like couch are the future, but looking at that, holy poo poo would couch make a loving amazing local end store for offline JS apps.

Holy crap, my two favorite things, combined! There's some talk of packaging couchDB with gears as a browser plugin to take advantage of couch's replication in offline apps. That, plus jQuery, could be a seriously killer app.

duck monster
Dec 15, 2004

Theres another jquery plugin called 'notemplate' that basically takes a data dictionary (nested if need be) and uses it as a templating system.

You combine that with couch, and you have a cms in a few lines of javascript. An *absurd* and *insecure* cms, granted. But a CMS none the less.

Wild stuff.

KuruMonkey
Jul 23, 2004

Dromio posted:

Some sort of setTimeOut() call maybe?

It scares me that you even have to ask whether you should use the builtin "wait until" function or simply hammer around in a tight loop until the time is up.

Of course you should be using setTimeout.

Summat like;

code:
function slowinput(input, text)
{
  var i = $(input).val().length;
  if(i < text.length)
  {
    $(input).val(text.substring(0, i));
    setTimeout(function(){slowinput(input, text);}, 1000);
  }
}
(I've not had time to run this as a test, so the code will be guaranteed buggy, but the principle should work, also I'm 1 character out in 99.9% of all string manipulation I do, so check/disregard that)

So you specify the input and the text to add, and it'll loop through it. The closure in the timeout is non optional AFAIK, as you need the parameters.

Dromio
Oct 16, 2002
Sleeper

KuruMonkey posted:

Of course you should be using setTimeout.

I'm still a little shaky in javascript, so I plead ignorance. When I asked, I was (mistakenly) led to believe that setTimeout only took strings. I learned the truth and implemented it properly.

On the other hand, having to chain setTimeout inside setTimeout inside setTimeout in order to simulate a mouse-click then typing text is UGLY :(

KuruMonkey
Jul 23, 2004

Dromio posted:

I'm still a little shaky in javascript, so I plead ignorance. When I asked, I was (mistakenly) led to believe that setTimeout only took strings. I learned the truth and implemented it properly.

On the other hand, having to chain setTimeout inside setTimeout inside setTimeout in order to simulate a mouse-click then typing text is UGLY :(

1; sounds like you need to take a long hard look at whoever you asked, and reassess whether they are worth asking questions of. Try asking http://www.w3schools.com/jsref/default.asp instead.

2; chaining whaaaaa? Example and context/reason/rationale for doing this please?!?

Dromio
Oct 16, 2002
Sleeper

KuruMonkey posted:

2; chaining whaaaaa? Example and context/reason/rationale for doing this please?!?

Less "chaining" than nesting, so I could have it pause appropriately between each step. I needed to move the "cursor.png" to the textbox, blink it black then back to indicate a click, then start typing the text out char by char. I can't copy+paste the code right now, but here's pseudocode what it ended up like:
code:
cursor.animate({top:toY, left:toX},animMovementTime, function() {
  cursor.attr("src", "blackcursor.png");
  //playsound click
  setTimeout(function() {
    cursor.attr("src", "whitecursor.pnh");
    setTimeout(function() {
      //play typing sound
      //while there is a character left to type
        setTimeout(function() {
            //get letter
            //type letter, etc.
    
Then close all the setTimeout calls with the appropriate delays.

Dromio fucked around with this message at 13:22 on Oct 10, 2008

fansipans
Nov 20, 2005

Internets. Serious Business.

Dromio posted:

Less "chaining" than nesting, so I could have it pause appropriately between each step.
code:
  setTimeout(function() {
    ...
    setTimeout(function() {
        ...
        setTimeout(function() {
            ...    

http://blog.napkindrawing.com/fansipans/playin/js/nestFuncs.html

:clint:

That was good practice. Heh, kinda forgot this was the jQuery thread though, I intentionally took out my little $ and map helpers. It's neat what you can do when functions are objects. :c00l:

LOLLERZ
Dec 9, 2003
ASK ME ABOUT SPAMMING THE REPORT FORUM TO PROTECT ~MY WIFE'S~ OKCUPID PERSONALS ANALYSIS SA-MART THREAD. DO IT. ALL THE TIME. CONSTANTLY. IF SHE DOESN'T HAVE THE THREAD, SHE'LL WANT TO TALK TO ME!

Dromio posted:

Less "chaining" than nesting, so I could have it pause appropriately between each step. I needed to move the "cursor.png" to the textbox, blink it black then back to indicate a click, then start typing the text out char by char. I can't copy+paste the code right now, but here's pseudocode what it ended up like:
code:
cursor.animate({top:toY, left:toX},animMovementTime, function() {
  cursor.attr("src", "blackcursor.png");
  //playsound click
  setTimeout(function() {
    cursor.attr("src", "whitecursor.pnh");
    setTimeout(function() {
      //play typing sound
      //while there is a character left to type
        setTimeout(function() {
            //get letter
            //type letter, etc.
    
Then close all the setTimeout calls with the appropriate delays.
Haha, funny you should post this, I just had to invent this same pattern myself for a task that had several long running (>500ms) tasks and needed to unblock the UI between each.

KuruMonkey
Jul 23, 2004

fansipans posted:

:clint:

I'm gonna go ahead and steal that, got a name/url or email you want in the source for, like, credit due and such?

ashgromnies
Jun 19, 2004

fansipans posted:

http://blog.napkindrawing.com/fansipans/playin/js/nestFuncs.html

:clint:

That was good practice. Heh, kinda forgot this was the jQuery thread though, I intentionally took out my little $ and map helpers. It's neat what you can do when functions are objects. :c00l:

Couldn't you accomplish something similar with the decorator pattern?

fansipans
Nov 20, 2005

Internets. Serious Business.
I braindumped my thoughts here: https://napkindrawing.com/blog_view/nehssaieyseitdea

KuruMonkey posted:

I'm gonna go ahead and steal that, got a name/url or email you want in the source for, like, credit due and such?

Sure, I just added license text to it, go ahead :)

ashgromnies posted:

Couldn't you accomplish something similar with the decorator pattern?

I guess, but the original intent was to chain one function to the next, and so on. I'm not sure how you'd decorate a function to do that, asides from what would seem to me to be monkey-patching.

I'd say Decorator would be warranted if I was doing this in a properly object oriented environment (JOOSE PLUG!) and I was dealing with actual objects, and not more low-level things like functions (yes I'm aware functions in JavaScript are objects - what did I say about monkey-patching?)

Actually this is a great example of why things like Joose will help so much. We'll finally have fully-capable modern object-oriented programming facilities available to us in the browser. Then again, if all we're talking about is pretending a typewriter is typing out keys on the keyboard, hacks like this are nice too :)

duck monster
Dec 15, 2004

fansipans posted:

http://blog.napkindrawing.com/fansipans/playin/js/nestFuncs.html

:clint:

That was good practice. Heh, kinda forgot this was the jQuery thread though, I intentionally took out my little $ and map helpers. It's neat what you can do when functions are objects. :c00l:

javascript can be disturbingly functional sometimes.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Is this pretty much the JavaScript questions thread now, or should I start a separate JavaScript/ECMAScript thread?

Edit: OK, it can probably wait till my lunch break if we've gone this long without one.

Munkeymon fucked around with this message at 17:12 on Oct 13, 2008

LOLLERZ
Dec 9, 2003
ASK ME ABOUT SPAMMING THE REPORT FORUM TO PROTECT ~MY WIFE'S~ OKCUPID PERSONALS ANALYSIS SA-MART THREAD. DO IT. ALL THE TIME. CONSTANTLY. IF SHE DOESN'T HAVE THE THREAD, SHE'LL WANT TO TALK TO ME!

Munkeymon posted:

Is this pretty much the JavaScript questions thread now, or should I start a separate JavaScript/ECMAScript thread?
A separate one will probably fare better.

Ned
May 23, 2002

by Hand Knit

LOLLERZ posted:

A separate one will probably fare better.

I think it would be fine to put regular javascript questions in here. The topic isn't that different and the people who read this thread should be able to give you good answers.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Ned posted:

I think it would be fine to put regular javascript questions in here. The topic isn't that different and the people who read this thread should be able to give you good answers.

Too late: http://forums.somethingawful.com/showthread.php?threadid=2983298

I link here from there in the OP, though :3:

indigoe
Jul 29, 2003

gonna steal the show, you know it ain't no crime
I have a report that generates a big table of stuff. I have added columns to show hourly data, so that's 24 extra columns. Now the table is quite wide, so I wanted to have those hour columns hidden by default, and have a toggle to show/hide them. The problem is my implementation executes very very slowly and even makes the browser appear to be frozen for some seconds.

Every table cell I want to toggle has the class 'hour'.
code:
$("#hourToggle").click(function(){
	
	if ($(this).text() == '>>')
	{
		$(".hour_block").toggle();
		$(this).text('<<').blur();
	}
	else
	{
		$(".hour_block").toggle();
		$(this).text('>>').blur();
	}
	return;
}); 	

Is there a better faster way to do this?

mwarkentin
Oct 26, 2004
Could you just toggle a class on the table itself, rather than on each cell?

Something like this? (This is mootools, should be able to do something similar in jQuery)

code:
$('hourToggle').addEvent('click', function() {
    $('tableID').toggleClass('showHour');
}
And css..

code:
td.hour {display:none}
table.showHour td.hour {display:block}

fansipans
Nov 20, 2005

Internets. Serious Business.

indigoe posted:

I have a report that generates a big table of stuff. I have added columns to show hourly data, so that's 24 extra columns. Now the table is quite wide, so I wanted to have those hour columns hidden by default, and have a toggle to show/hide them. The problem is my implementation executes very very slowly and even makes the browser appear to be frozen for some seconds.

Every table cell I want to toggle has the class 'hour'.
code:
$("#hourToggle").click(function(){
	
	if ($(this).text() == '>>')
	{
		$(".hour_block").toggle();
		$(this).text('<<').blur();
	}
	else
	{
		$(".hour_block").toggle();
		$(this).text('>>').blur();
	}
	return;
}); 	

Is there a better faster way to do this?

See code at: http://paste.ifies.org/110

You can play with it by pasting the code into the demo page at w3schools.com

I'm assuming all the hidden cells in your table each individually have the class hour_block.

$(".hour_block") probably matches hundreds, if not thousands, of elements, each one having to be toggled individually, by jQuery, with JavaScript, back through the browser... (eons)

You'd be much better off putting all of those cells into one table, with the same # of rows as the original table, and placing it into the original table in a single cell with a rowspan that matches the # of rows you have.

But yeah, selectors can be deceiving, because with an unoptimized design it's easy to call a selector that forces the browser to do hundreds or thousands of individual renders, as opposed to just one.

I'm also assuming here that jQuery isn't smart enough when given 1000 DOM changes to do all its work in private, then give the new DOM as a single object to the browser, it may be. But I doubt it ;)

indigoe
Jul 29, 2003

gonna steal the show, you know it ain't no crime
Thanks, that really helped. It's much faster now. There were thousands of cells to display.

Adbot
ADBOT LOVES YOU

Dromio
Oct 16, 2002
Sleeper
I'm trying to integrate my jQuery-heavy page into a site that was already using scriptaculous/prototype. I've put "jQuery.noConflict();" so it runs immediately and I've replaced all instances of "$" with "jQuery" in my code.

But I'm still getting an error in jquery.js claiming "this.cloneNode is not a function". It's coming from somewhere inside one of one of my jquery plugins.

Any suggestions on how to hunt it down?

  • Locked thread