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.
 
  • Post
  • Reply
Mackerel, the Thief
Sep 24, 2003

Lumpy posted:

You have a couple variable names to cut down one letter mister. He might be able to understand those parts.

I really want to punch someone whenever I see something like this:

code:
$('td').each(function() {
    for (i = 0, t = this, a = "<div", b = t.attributes, l = b.length; i < l; ++i)
        a += ' ' + b[i].name + '="' + b[i].value + '"';
    $(t).replaceWith( $(a+">"+$(t).html()+"</div>") );
});

Adbot
ADBOT LOVES YOU

OddObserver
Apr 3, 2009
That brevity version is missing quite a few uses of 'var'.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Mackerel, the Thief posted:

I really want to punch someone whenever I see something like this:

code:
$('td').each(function() {
    for (i = 0, t = this, a = "<div", b = t.attributes, l = b.length; i < l; ++i)
        a += ' ' + b[i].name + '="' + b[i].value + '"';
    $(t).replaceWith( $(a+">"+$(t).html()+"</div>") );
});

Can you come to where I work and start punching people? You've just written every piece of javascript, C, Java, and [ insert language here ] my "boss" writes. :(

EDIT: well, not quite, your code might work....

Lumpy fucked around with this message at 20:04 on Aug 24, 2010

Mackerel, the Thief
Sep 24, 2003

OddObserver posted:

That brevity version is missing quite a few uses of 'var'.

For when I need to access i globally after the lambda's finished?

dancavallaro
Sep 10, 2006
My title sucks

Mackerel, the Thief posted:

For when I need to access i globally after the lambda's finished?

You do realize that the way you wrote it, i, attrs, and attrLength are all global, right?

Mackerel, the Thief
Sep 24, 2003

dancavallaro posted:

You do realize that the way you wrote it, i, attrs, and attrLength are all global, right?

Oh snap. I had that backwards.

dark_panda
Oct 25, 2004

OddObserver posted:

That brevity version is missing quite a few uses of 'var'.

I'd say he's missing one. After using JSLint for so long I'm very much used to the one-var-statement-per-block rule. I think it's a pretty good rule, too. It avoids the unexpected "var hoisting" that JavaScript does, which can sometimes lead to unexpected results. Sort of C-ish, too, of course.

I'd also put some braces in there on that for loop, even through it's only a single statement. Old habits, I guess, and the whole resiliency-to-editing thing.

Otik
Apr 6, 2005

Psycho log baby
I'm completely useless with JS, and was struggling like hell to get a script I've been working on to function.

It turns out that at some point I had accidentally removed the curly brackets at the end of half of my functions :doh:

Seriously, how did I miss that for so long? I'm poo poo with JS, but I'm not retarded.

dark_panda
Oct 25, 2004

Otik posted:

I'm completely useless with JS, and was struggling like hell to get a script I've been working on to function.

It turns out that at some point I had accidentally removed the curly brackets at the end of half of my functions :doh:

Seriously, how did I miss that for so long? I'm poo poo with JS, but I'm not retarded.

JSLint is your friend, even if it hates you. It's picky and opinionated and will probably hate most of the JavaScript it sees, but it's also an invaluable tool for JavaScript development.

http://www.jslint.com/

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Yeah jslint is nice, but another thing I would recommend is using a text editor that will automatically highlight the matching brace when your cursor goes over one. I use this feature all the time for sanity checks. Geany does it, for example.

dark_panda
Oct 25, 2004

peepsalot posted:

Yeah jslint is nice, but another thing I would recommend is using a text editor that will automatically highlight the matching brace when your cursor goes over one. I use this feature all the time for sanity checks. Geany does it, for example.

Yay vim!

For others who maybe don't like vim, I've also been using Komodo Edit as of late, which has built-in syntax checking and some basic linting-while-editing. (It also does other edit-time checks for many of the languages it supports syntax highlighting for.) It's not the prettiest editor, but it gets the job done.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

dark_panda posted:

JSLint is your friend, even if it hates you. It's picky and opinionated and will probably hate most of the JavaScript it sees, but it's also an invaluable tool for JavaScript development.

http://www.jslint.com/

Thanks for this link, I have added it to my favourites, even though some of the things it complains about are a bit bizarre (it doesn't like window.close() even though I checked "assume a browser"?)

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Hammerite posted:

Thanks for this link, I have added it to my favourites, even though some of the things it complains about are a bit bizarre (it doesn't like window.close() even though I checked "assume a browser"?)

JSLint can be a real dick sometimes. It has some great advice, and its checking for accidental globals, syntax, etc. is pretty good. It gets really pedantic about things like one var per statement (I understand the sentiment, due to hoisting, but meh), and 'using a function before it's declared' - I suspect he wants all functions to be declared with 'var ThisisaFunction = function() { ... }', because, after all, functions are just variables are just objects in Javascript, but that doesn't mean I have to go along with its crazy syntax.

The fact that it doesn't support jQuery is a huge annoyance as well; I'm sure I'd get some use out of the "Disallow undefined variables" option, but since it considers $ an undefined variable, I have to disable it.

I usually click The Good Parts, then unset 'strict white space', 'require use strict', 'disallow undefined vars' (because of the $ issue), and 'require InitialCaps for constructors', since JSLint is unhappy that all my functions have initial caps. And I still ignore most of the rest, but I keep it on in case it finds something useful. For example, banning ==/!= in favor of ===/!== doesn't make sense in most situations... but it does in some. I disagree with his stance against ++, but I keep that on anyway.

So, I'll run my code through it a few times until the only errors left are "function used before it was declared" (that can't be disabled, I don't think) and a smattering of == and ++ issues.

dancavallaro
Sep 10, 2006
My title sucks

Golbez posted:

For example, banning ==/!= in favor of ===/!== doesn't make sense in most situations... but it does in some.

What is an example of a use case where it makes sense to use == over ===?

Tivac
Feb 18, 2003

No matter how things may seem to change, never forget who you are

dancavallaro posted:

What is an example of a use case where it makes sense to use == over ===?

Maybe he just really likes type coercion?

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

dancavallaro posted:

What is an example of a use case where it makes sense to use == over ===?

I don't like having to do "=== '3'" when dealing with form input, which are (I believe?) always strings. I could cast it as an int, or I could just leave it be. If I had to cast everything as a type, I might as well use a strongly typed language, right?

It's just that every time I start to look at it, my mind starts to wonder about the edge cases where I might be breaking something. But on the other hand it might be smarter to force myself to make it work to prevent those edge cases from happening.

Kekekela
Oct 28, 2004

dancavallaro posted:

What is an example of a use case where it makes sense to use == over ===?

parseInt(x) == parseInt(y)

e: alternatively...
aFunctionReturningAnIntThatDoesntGiveAFuckAboutBases(x) == aFunctionReturningAnIntThatDoesntGiveAFuckAboutBases(y)

Kekekela fucked around with this message at 15:49 on Sep 2, 2010

Otik
Apr 6, 2005

Psycho log baby

dark_panda posted:

JSLint is your friend, even if it hates you. It's picky and opinionated and will probably hate most of the JavaScript it sees, but it's also an invaluable tool for JavaScript development.

http://www.jslint.com/

Aha - I used that a couple of months ago with my first experience of JS. I had a useless lecturer who was of the "copy this down by hand from paper and you'll understand the language" school of teaching, and when my script didn't work I managed to find that site.

The problem, if I remember correctly, ended up being in his original code as some of the functions were in the wrong order. He hadn't even tested his own code...

No wonder I'm struggling now.

Munkeymon
Aug 14, 2003

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



dancavallaro posted:

What is an example of a use case where it makes sense to use == over ===?

Do you find that it matters in most situations? Serious question.

The code I deal with at work is terrible in many ways and depends on the ambiguity that type coercion provides to not fall over constantly, but I still find that, even when I think about it, I almost never see the point in putting the extra restriction on the conditional. I mean, do I really care that the answer was a string '2' instead of a Number 2 when either one can and will work? I know that's a trivial example, but I'm having a hard time thinking of an instance where it mattered.

Kekekela
Oct 28, 2004

Munkeymon posted:

Do you find that it matters in most situations? Serious question.

The code I deal with at work is terrible in many ways and depends on the ambiguity that type coercion provides to not fall over constantly, but I still find that, even when I think about it, I almost never see the point in putting the extra restriction on the conditional. I mean, do I really care that the answer was a string '2' instead of a Number 2 when either one can and will work? I know that's a trivial example, but I'm having a hard time thinking of an instance where it mattered.

The most common place where it matters is (as with most everything) when dealing with 0's, empty strings etc since you'll get some things you might not be expecting, like 0 == '' being true.

Vanadium
Jan 8, 2005

Golbez posted:

If I had to cast everything as a type, I might as well use a strongly typed language, right?

Most people use javascript because of the platform, not the language~

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Vanadium posted:

Most people use javascript because of the platform, not the language~

Well, yes, very true, but if it was a major issue they'd've changed it by now, right? :v:

epswing
Nov 4, 2003

Soiled Meat
Is it really too much to ask of a programmer to know the types of the variables he/she is throwing around?

If I get some x, and I expect it's a number, and it's actually NaN, I'd want to know it's NaN ASAP. Use parseInt, use parseDouble, make sure the thing you've got is a thing you want, rather than "oh == is happy so I'm happy" which will eventually bite you (and potentially be hard to track down, because everything will "look" correct).

There's really no reason to use == other than laziness/sloppiness.

epswing fucked around with this message at 22:16 on Sep 1, 2010

Tivac
Feb 18, 2003

No matter how things may seem to change, never forget who you are

Kekekela posted:

parseInt(x) == parseInt(y)

You probably want bases on those calls to parseInt or else if the input is something like "08" you aren't going to get the answer you want.

Always specify a base for calls to parseInt, seriously.

dark_panda
Oct 25, 2004
While on the subject of JSLint, it might be informative to watch a couple of videos on JavaScript by the author JSLint and one of the chief evangelists of JavaScript as a language, Douglas Crockford.

http://developer.yahoo.com/yui/theater/

See the videos in the second column, starting with "Volume 1: The Early Years" up through the recent "Scene 6: Loopage". Even if you outright hate JavaScript or are otherwise indifferent, I highly recommend watching all six of his videos in this particular series 'cause they're really informative, not only on the subject of JavaScript itself but as lessons in the evolution of the art of computer programming. And they're downloadable in m4v format so you can watch 'em on an iPod or whatever, so collect 'em all.

Really, these videos are awesome, and highly recommended for anyone who works with JavaScript. Hell, the first video barely even mentions JavaScript and talks more to the history of computer programming languages, so everyone can enjoy that one.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Tivac posted:

You probably want bases on those calls to parseInt or else if the input is something like "08" you aren't going to get the answer you want.

Always specify a base for calls to parseInt, seriously.

Yup. I had to fix a MAJOR BUG :supaburn: in a JS app last week... they had been trying to figure out what was causing the problem for three days. A user was passing '09' as a value to a function that used parseInt, and didn't do any bounds checking and passed of a value that never should have been more than 10 to something else that imploded (that also didn't do any input checking). I love working with people who literally say "well, javascript isn't a real language, so I'm not going to bother learning it; I just need to hack this out and I'll never have to use JS again." Despite having said that for the first time two years ago and having to work with JS more than any other language.

OddObserver
Apr 3, 2009
parseInt-and-leading-zero-octal is pretty icky spec-wise, too. Here is what the 3rd edition says:

quote:

When radix is 0 or undefined and the string's number begins with a 0 digit not followed by an x or X, then the implementation may, at its discretion, interpret the number either as being octal or as being decimal. Implementations are encouraged to interpret numbers in this case as being decimal.

The 5th edition removed this paragraph, and now requires the leading zero case to be handled as decimal; which I think we'll all agree is the more sensible behavior... except despite the encouragement-of-base-10 note, seems like just about any modern browser I have on Linux (everything except Opera) interprets it as octal anyway (though perhaps because I was too lazy to provide a type on script tag) --- making it potentially an incompatibility hazard.

Save the whales
Aug 31, 2004

by T. Finn

Lumpy posted:

I love working with people who literally say "well, javascript isn't a real language, so I'm not going to bother learning it; I just need to hack this out and I'll never have to use JS again." Despite having said that for the first time two years ago and having to work with JS more than any other language.

+1. For some reason so many of my colleagues think JavaScript is "dirty" and everything you do in it is a hack. When a client asks for a complex UI they panic. And they think nothing of writing something like:

code:
<script>
var i = 0;
...
</script>
I mean, great... now window.i = whatever you left it at. Is that really what you meant to do? Do you declare a global i variable in every programming language you use?

Functions as first class objects is enough for me to take JS seriously. If you're used to working with a stricter language like Java, that concept is so refreshing and awesome. It really changes the way you think about programming in general.

Kekekela
Oct 28, 2004

Tivac posted:

You probably want bases on those calls to parseInt or else if the input is something like "08" you aren't going to get the answer you want.

Always specify a base for calls to parseInt, seriously.

Thanks for this. Just substitute in "function call returning a specific type == same function called with different params" if you're really not understanding what that post was trying to convey. (I realize you probably couldn't and won't be bothered to read what I was replying to, but just in case)

Kekekela fucked around with this message at 15:48 on Sep 2, 2010

Tivac
Feb 18, 2003

No matter how things may seem to change, never forget who you are

Kekekela posted:

Thanks for this. Just substitute in "function call returning a specific type == same function called with different params" if you're really not understanding what that post was trying to convey. (I realize you probably couldn't and won't be bothered to read what I was replying to, but just in case)

I'm just making sure anybody reading those posts realizes what a nasty bug they can unleash by not using bases with parseInt. Not picking on you or anybody in particular.

HFX
Nov 29, 2004

Save the whales posted:

+1. For some reason so many of my colleagues think JavaScript is "dirty" and everything you do in it is a hack. When a client asks for a complex UI they panic. And they think nothing of writing something like:

code:
<script>
var i = 0;
...
</script>
I mean, great... now window.i = whatever you left it at. Is that really what you meant to do? Do you declare a global i variable in every programming language you use?

Functions as first class objects is enough for me to take JS seriously. If you're used to working with a stricter language like Java, that concept is so refreshing and awesome. It really changes the way you think about programming in general.

I could point to quite a few languages who do all the nice stuff Javascript does and better.

HFX fucked around with this message at 10:17 on Sep 4, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

HFX posted:

I could point to quite a few languages who do all the nice stuff Javascript does and better.

Great. Did anyone claim there weren't any?

For some topic related content, if you sometimes get stuck doing IE only apps like me, I just found out about this pretty awesome performance monitoring tool: http://ajax.dynatrace.com/pages/

epswing
Nov 4, 2003

Soiled Meat

I've been meaning to link this for days. It's awesome.

me your dad
Jul 25, 2006

I maintain a simple intranet-based resource tool for members of my department at work and I am a novice at best when it comes to Javascript. I use code when needed and I can usually find what I need through Google. I'm working on something now though and I'm having trouble bending the code to my needs.

I am creating a "tech support guide" for our customer service team. They're new to handling tech suppport issues so I need an automated way of walking them through procedures.

My goal is to create a series of simple dropdown menus that can walk an employee through the troubleshooting process. Each dropdown selection will be associated with a hidden div that will appear upon selection.

I found the following Javascript which has helped me get started. I'm having a problem with it though. The guide starts with a Yes/No dropdown. Upon clicking No, some text and a second dropdown should appear. Making a choice with this second dropdown should expand even more text, and another dropdown if needed, and so on.

The first dropdown works fine but if a choice is made on the second dropdown, it clears everything out and leaves only the first dropdown on screen.

code:
<script type="text/javascript">
		<!--
var lastDiv = "";
function showDiv(divName) {
	// hide last div
	if (lastDiv) {
		document.getElementById(lastDiv).className = "hiddenDiv";
	}
	//if value of the box is not nothing and an object with that name exists, then change the class
	if (divName && document.getElementById(divName)) {
		document.getElementById(divName).className = "visibleDiv";
		lastDiv = divName;
	}
}
//-->
</script>
The corresponding HTML:

code:
<div class="techguide">
	<form id="FormName"name="FormName">
		<p>Can you duplicate the error?
			<select name="selectName" onchange="showDiv(this.value);">
				<option value="">Choose One</option>
				<option value="yes">Yes</option>
				<option value="no">No</option>
			</select>
		</p>
	</form>
	<div class="hiddenDiv" id="yes">
		<p>Some steps here if they choose yes</p>
	</div>

	<div class="hiddenDiv" id="no">
		<p>Some info here if they choose no followed by another dropdown</p>
		<p span class="b">Solution:</p>
			<form id="FormName2"name="FormName2">
		<p>What operating system is being used?
			<select name="selectName" onchange="showDiv(this.value);">
				<option value="">Choose One</option>
				<option value="os1">OS 1</option>
				<option value="os2">OS 2</option>
			</select>
		</p>
			</form>

		<div class="hiddenDiv" id="os1">
			<p>Info here about OS 1</p>
		</div>
		<div class="hiddenDiv" id="os2">
			<p>Other OS info here</p>
		</div>
	</div>
</div>
I know this is probably an inelegant way to accomplish this and I'm open to ideas, but keep in mind I'm kind of an idiot.

Can someone please help me accomplish what I'm trying to do?

Supervillin
Feb 6, 2005

Pillbug

Chinaski posted:

The first dropdown works fine but if a choice is made on the second dropdown, it clears everything out and leaves only the first dropdown on screen.

You're setting an element (id "os1" or "os2") to be visible, but at the same time you're setting its parent element (id "no") to be hidden. That means os1 or os2 will still not be visible.

As you said, there are cleaner ways to go about this, and it will probably be easier to use a library so you can grab everything with a particular class name easily. But if not, at least make sure all of the stuff that needs to be visible is at the same level in the document and your current code should work fine.

Also you don't need <!-- and --> inside a script tag anymore, that was literally for Netscape Navigator 1, Internet Explorer 2, and Mosaic. That in itself may tell you that scripts you find on the net may be too old to really be helpful.

Edit: Also also, you don't need a hidden class AND a visible class. Stuff's visible by default, just use class="hidden" or class="".

me your dad
Jul 25, 2006

I see - thanks. I'll try mucking about with it some more when I go back to work on Monday.

Munkeymon
Aug 14, 2003

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



Does anyone know of a premade plugin or code chunk, preferably for scriptaculous, that I can use to make the content of a div drag-scrollable? Think PDF or google maps style navigation where you click and yank the whole of the content around.

All I can find on Goolge is poo poo about building a drag and drop interface and I know about Draggable, but it's not really meant for this. When I drag the content up past the top and/or left edge of the viewport, the canvas shrinks and the scrollbars become useless. Other than that, it's almost perfect and the snap effect using a callback is letting me do some neat things pretty easily.

Gentle Marmot
Mar 25, 2005
like the sugar
I want to be able to write to a json or xml file from a website using javascript. How would I go about doing something like this? I can open them and read just fine out of them using XMLHttpRequest, but is there a way to write?

Basically what I have is a gui for an application written in javascript using websockets which is then served up on individual webservers that users connect to to fire up this gui. There are a number of default values which I have to change in the javascript file itself to set but I would rather read from a json and have a button to write new defaults to this json if possible. Is what I am thinking of doing feasible?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:

I want to be able to write to a json or xml file from a website using javascript. How would I go about doing something like this? I can open them and read just fine out of them using XMLHttpRequest, but is there a way to write?

Basically what I have is a gui for an application written in javascript using websockets which is then served up on individual webservers that users connect to to fire up this gui. There are a number of default values which I have to change in the javascript file itself to set but I would rather read from a json and have a button to write new defaults to this json if possible. Is what I am thinking of doing feasible?

You will have to send the modified json to the server for writing. This can be done with Ajax, but there will have to be some server side scripting for the actual file ( or database) write.

Adbot
ADBOT LOVES YOU

Gentle Marmot
Mar 25, 2005
like the sugar
What if I stored to json file locally would that simplify things? Could I just read and write to it from within the javascript?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply