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
SuckerPunched
Dec 20, 2006

keveh posted:

That still returns the value of the window on load unfortunately.

:edit:

Sorry, that did work. I just had to change window.offsetWidth to document.body.offsetWidth

Thanks

Yeah sorry, I should have been more clear. Glad you got it working!

Adbot
ADBOT LOVES YOU

Metonymy
Aug 31, 2005
I'm using jQuery with Django, and I'm trying to wrap my head around unobtrusive javascript.

Back in the day, I would have done something like:

code:
{% for item in items%}
<div class="item" onclick="javascript:clickItem('{{item.id}}')"> {{ item.title }} </div>
{% endfor %}
I'd prefer to attach the event handler to all divs that match the "item" class, like so:
code:
$(document).ready(function(){
        $(".item").click(function(event){
      clickItem(WHERE DO I STORE THIS ITEM ID);
      });
What I'm having a hard time with, though, is where I get the item ID if I need to make a call back to the database. I don't want to put some bogus attribute on the DIV element, but if I don't, how do I associate the item that's being clicked with its database ID in future javascript calls?

Or to make the problem even more abstract, lets say I want my clickItem() function to iterate over all the "items" that have a certain class (e.g. "expanded"), and make an AJAX call with all their ids as an argument...where do those IDs hang out, and how do I associate them with the "item" divs on my page?

Metonymy fucked around with this message at 23:49 on Jul 10, 2009

Xenos
Jun 17, 2005

Metonymy posted:

What I'm having a hard time with, though, is where I get the item ID if I need to make a call back to the database. I don't want to put some bogus attribute on the DIV element, but if I don't, how do I associate the item that's being clicked with its database ID in future javascript calls?

divs have an id attribute, store the object's id in that. After you do that, you can do this:

code:
$(document).ready(function() {
    $('.item').click(function(event) {
        clickItem($(this).attr('id'));
    });
});

Metonymy
Aug 31, 2005

Xenos posted:

divs have an id attribute, store the object's id in that. After you do that, you can do this:

code:
$(document).ready(function() {
    $('.item').click(function(event) {
        clickItem($(this).attr('id'));
    });
});

Yeah, I guess that's what I was trying to avoid, since it seems like you're including some database back-end stuff in the markup. Realistically though, I didn't see a way to get around it. I guess there's a limit to how much separation you can achieve between script and markup.

Metonymy fucked around with this message at 00:12 on Jul 11, 2009

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

Metonymy posted:

I'm using jQuery with Django, and I'm trying to wrap my head around unobtrusive javascript.
The problem with just using the ID to store the raw item.id is that there's a high risk of having duplicate IDs on the page. Of course you can use something like id="item-{{ item.id}}, but there's still the possibility. My two favorite ways of doing this are:

1) Using a hidden input field, so your markup would look something like this:
code:
HTML:
<div class="item">
   <input type="hidden" name="id" value="{{ item.id }}" />
    {{ item.title }}
</div>

JS:
$(document).ready(function()
{
    $('.item').click(function(event)
    {
        clickItem($("[name=id]", this).val());
    });
});
2) You generally want to maintain the functionality even if Javascript is disabled, so what I commonly do is implement the basic functionality first without Javascript, where your markup would look something like this:
code:
<a class="item" href="/checkItem/{{ item.id }}>
    {{ item.title }}
</a>
And then enhance the functionality with JS:
code:
$(document).ready(function()
{
    $('a.item').click(function(event)
    {
        var id = /checkItem\/(\w+)/i.exec($(this).href())[1];
        clickItem(id);
        return false;
    });
});
Note that I usually don't use a regex to parse the ID out of the href, but instead use the href directly with an additional parameter to specify the format I want the result in, like so:
code:
$.getJSON($(this).href(), { return: "json" });
However, you obviously need to change your checkItem function to work correctly with that input.

supster fucked around with this message at 01:02 on Jul 11, 2009

cletus42o
Apr 11, 2003

Try to imagine all life as you know it stopping instantaneously and every molecule in your body exploding at the speed of light.
College Slice
I have a Facebook application, and I also use some Facebook Connect features on my site.

Using the FB JavaScript library, I can get a list of the current user's friends. Unfortunately, this list is only obtained client-side, so I need to see if I can capture it.

I created a page to be called via an AJAX call in jQuery, _ajax_fb_friends.cfm -

code:
	<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
	
	<script type="text/javascript"> 
		//<![CDATA[ 
		var api_key = 'MY API KEY'; 
		var channel_path = '../connect/'; 
		FB_RequireFeatures(["Api"], function(){ 
			// Create an ApiClient object, passing app's API key and 
			// a site relative URL to xd_receiver.htm 
			FB.Facebook.init(api_key, channel_path); 
			var api = FB.Facebook.apiClient; 
			// require user to login 
			api.requireLogin(function(exception){ 
				//document.getElementById('_traceTextBox').innerHTML = "Current user id is " + api.get_session().uid; 
				// Get friends list 
				//5-14-09: this code below is broken, correct code follows 
				//api.friends_get(null, function(result){ 
				// Debug.dump(result, 'friendsResult from non-batch execution '); 
				// }); 
				api.friends_get(new Array(), function(result, exception){ 
				document.write(result); 
				}); 
			}); 
		}); 
		//]]> 
	</script>
But as you can see, I am trying to use document.write() to output the data.

Then, my jQuery on my main page -

code:
			$.post("#runModJS('#Base.strRequestURL#modules/_ajax_fb_friends.cfm')#", 
				{ x: 0 },
				function(data) {
					$.post("#runModJS('#Base.strRequestURL#modules/_ajax_fb_friends.cfm?mode=set')#", 
						{ x: data },
						function(data) {
							var donothing = 1;
						});
				 });
The #runModJS()# function returns the proper path for the post to the file. I could just be doing a get for the first call, but I copied my own code from elsewhere and figured it should still work just fine doing a post.

As you can see, I'm calling it first with no URL parameter, which runs the code from my first code block. Then I want to pass the data on to a second post, which actually would post that data back to the same file, which would save it to a database.

However, it doesn't seem like the first call is getting the data. Does document.write() not work for this? I might be tackling this wrong - so I'm open to suggestions. Thanks!

edit - nevermind, I'm an idiot. I don't know why I didn't just do the Facebook JS call in my page, and then just post the result from it to my page. No reason to use a post/get ajax to get that data when I could get it immediately. Oh, well, at least posting about it sparked that revelation.

cletus42o fucked around with this message at 04:51 on Jul 11, 2009

Save the whales
Aug 31, 2004

by T. Finn

Metonymy posted:

Yeah, I guess that's what I was trying to avoid, since it seems like you're including some database back-end stuff in the markup. Realistically though, I didn't see a way to get around it. I guess there's a limit to how much separation you can achieve between script and markup.

It seems to fit with what the w3c says about the purpose of the id attribute. I think it's perfectly fine.
http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

supster posted:

code:
<a class="item" href="/checkItem/{{ item.id }}>
    {{ item.title }}
</a>

This is definitely the right approach - normal anchor hrefs with jquery added on top.

I just wanted to make mention of the fact that with Django the href should actually be abstracted away in the url conf or the object itself, so you should be using either:

code:
<a class="item" href="{% url check_item item.id %}">

or

<a class="item" href="{% item.get_absolute_url %}">
Django plus Jquery rocks!

Metonymy
Aug 31, 2005

jupo posted:

This is definitely the right approach - normal anchor hrefs with jquery added on top.

I just wanted to make mention of the fact that with Django the href should actually be abstracted away in the url conf or the object itself, so you should be using either:

code:
<a class="item" href="{% url check_item item.id %}">

or

<a class="item" href="{% item.get_absolute_url %}">
Django plus Jquery rocks!

Thanks, Supster/Jupo. I appreciate it. The href story makes a lot of sense.

I'm really, really, impressed with jQuery, especially on top of a well-developed framework like Django. I've seen a lot of people cheerleading for things like jQuery and Ruby for a long time, and now I can see why.

Metonymy
Aug 31, 2005
Lets say I'm using a jQuery AJAX call to pull some JSON and then populate a div with that information using a grim text concatenation ("<div class='gubbawumps'>...") and then a jQuery append(). It seems like the right way to do this is probably with a jQuery.load() and have a page get rendered that contains the HTML I want, rather than trying to generate one in text in javascript. Any thoughts? It's a relatively sizable chunk of content with a lot of markup.

Follow-up: under what circumstances would you use an append()? Stuff with little to no markup?

Metonymy fucked around with this message at 18:57 on Jul 17, 2009

Ned
May 23, 2002

by Hand Knit

Metonymy posted:

Lets say I'm using a jQuery AJAX call to pull some JSON and then populate a div with that information using a grim text concatenation ("<div class='gubbawumps'>...") and then a jQuery append(). It seems like the right way to do this is probably with a jQuery.load() and have a page get rendered that contains the HTML I want, rather than trying to generate one in text in javascript. Any thoughts? It's a relatively sizable chunk of content with a lot of markup.

Follow-up: under what circumstances would you use an append()? Stuff with little to no markup?

There is nothing wrong with turning JSON into markup.

Kekekela
Oct 28, 2004

Metonymy posted:

Lets say I'm using a jQuery AJAX call to pull some JSON and then populate a div with that information using a grim text concatenation ("<div class='gubbawumps'>...") and then a jQuery append(). It seems like the right way to do this is probably with a jQuery.load() and have a page get rendered that contains the HTML I want, rather than trying to generate one in text in javascript. Any thoughts? It's a relatively sizable chunk of content with a lot of markup.

Follow-up: under what circumstances would you use an append()? Stuff with little to no markup?

While I see the allure of doing the whole page at once I've generally found it more practical to go with an approach more like what you're talking about with the append() statements. Its definitely something where I feel like my approach is a work in progress though, not claiming to have the "right" way.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
I'm dynamically adding a listener to elements, but I need it to be called before any other listener on those elements. Is there a way to manipulate which order listeners get called? Is it even possible to get references to all listeners on an object?

drat you events. :(

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL

Mercator posted:

I'm dynamically adding a listener to elements, but I need it to be called before any other listener on those elements. Is there a way to manipulate which order listeners get called? Is it even possible to get references to all listeners on an object?

drat you events. :(

The order of event handler execution in jQuery is based on the rules of property enumeration in Javascript, which are undefined by the spec and vary wildly from browser to browser. In general, handlers are called in the same order in which they are attached, but there are a number of special cases where this does not happen.

In order to get a particular handler to execute first, it would need to be the first in property enumeration order of the internal handler hash for that element.

Unfortunately, there is no simple way to achieve this. After reading your question I had a poke around the event subsystem in jQuery 1.3.2, and actually tried writing a little plugin to do what you are asking. The strategy was to retrieve a list of the current handlers, unbind them all, bind your new handler, and then reattach the old ones. It didn't work in chrome, because chrome enumerates integer-keyed properties in numerical order rather than order of assignment; the keys used in the event system are based on the internal jQuery guids of the handlers; and these handlers are incremented in the order that the handlers are originally attached.

In other words, if a handler has already been attached, it is really hard to reliably move it to the back of the queue without essentially rewriting the event subsystem.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
Thanks for looking. I was looking into the direction of an event manager like you suggested but you did a much better job of researching this.

It is kind of strange that the DOM level 2 spec specifically doesn't define this part of events handling at all. It seems like such a helpful and easy thing to implement.

A quick glance over the level 3 specs doesn't mention anything like this either. Argh.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Mercator posted:

A quick glance over the level 3 specs doesn't mention anything like this either. Argh.

Oh?

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

Mercator posted:

Thanks for looking. I was looking into the direction of an event manager like you suggested but you did a much better job of researching this.

I wrote something like this about 5 years ago when i was learning JS.

http://jupo.org/scripts/lime/src/events.js

The code's really old and it probably has some other dependencies but the basic gist is to have a custom function for adding events that takes a dom id and a handler and stores your handlers against each id, attaching the custom handler to the dom element one time only that raises all your handlers *in order*.

cLin
Apr 21, 2003
lat3nt.net
For the code here:
code:
	$("#expand").click(function() {
		toggle_all_on();
	});

	function toggle_all_on() {
	$(".toggle_container").show();
	$(".trigger").not(".active").addClass("active").toggle(function(){
	$(this).addClass("active");
	}, function () {
	$(this).removeClass("active");
	});
	}
Would I just need to have a link as <a href="#" id="expand">expand</a> for it to call the function?

geetee
Feb 2, 2004

>;[

cLin posted:

Would I just need to have a link as <a href="#" id="expand">expand</a> for it to call the function?


Almost! Just add "return false;" below "toggle_all_on();"

cLin
Apr 21, 2003
lat3nt.net
What does that do? I thought return false was usually only for switches, loops or if statements.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

cLin posted:

What does that do? I thought return false was usually only for switches, loops or if statements.

Keep the HREF from being triggered. If your have href="#" near the bottom of the page and *don't* return false from the function, the page will jump back up to the top if it was scrolled.

Pardot
Jul 25, 2001




What is more popular, return false or event.preventDefault()?

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
return false

cLin
Apr 21, 2003
lat3nt.net

Lumpy posted:

Keep the HREF from being triggered. If your have href="#" near the bottom of the page and *don't* return false from the function, the page will jump back up to the top if it was scrolled.

Oh perfect. So for those websites with modal windows as a login, do they just have the link to the actually login file in case the user doesn't have javascript and just place the return false at the end of the function call?

MrMoo
Sep 14, 2000

SuckerPunched posted:

I've found myself incredibly unimpressed with jQuery UI. Bloated, overly complicated, and buggy as hell. And worst of all, even at it's smallest size, it's still a GIGANTIC file. 100's of KB is not acceptable to me, for what it provides.

That's why they have a online service to download custom versions:

http://jqueryui.com/download

Alternatively just link to Google's hosted minified version.

I'm finding the tabs and dialog extremely convenient but I can't say I use anything else.


supster posted:

Has anyone used uploadify before? Anyone have a better suggestion for a simple file upload plugin with a progress bar?

Didn't most of these break with Flash 10? This one has absolutely zero backward compatibility and is doing jack poo poo in Chrome.

I like using Gears and dropping back to traditional upload form. Yahoo apparently have some fancy version supporting drag & drop but I haven't checked it out. I did like the Yahoo! Photos Uploader add-on for Firefox but drat that was a lot of code using raw socket handling in JavaScript.

http://developer.yahoo.com/yui/examples/uploader/uploader-advanced.html

MrMoo fucked around with this message at 09:11 on Jul 21, 2009

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

Avenging Dentist posted:

Oh?

:cool:

jupo posted:

I wrote something like this about 5 years ago when i was learning JS.

http://jupo.org/scripts/lime/src/events.js

The code's really old and it probably has some other dependencies but the basic gist is to have a custom function for adding events that takes a dom id and a handler and stores your handlers against each id, attaching the custom handler to the dom element one time only that raises all your handlers *in order*.

I'm going to keep this in mind when the indeterminable firing order is going to drive me nuts. :) Thank you.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

cLin posted:

Oh perfect. So for those websites with modal windows as a login, do they just have the link to the actually login file in case the user doesn't have javascript and just place the return false at the end of the function call?

If they are good designers of websites and care about not loving people w/o javascript, then yes. :)

sim
Sep 24, 2003

MrMoo posted:

That's why they have a online service to download custom versions:

http://jqueryui.com/download

Alternatively just link to Google's hosted minified version.

I'm finding the tabs and dialog extremely convenient but I can't say I use anything else.

jQuery UI core + tabs and dialog is still 134.01 kb minified. While I agree it works great for throwing in some quick and easy interface elements, it is extremely bloated. Also I've noticed some slow load times from Google's hosted code on occasion. I know its supposed to cache, but every once in awhile it seems to hang and I definitely don't want that on a piece of core functionality like jQuery and jQuery UI.

geetee
Feb 2, 2004

>;[

Lumpy posted:

If they are good designers of websites and care about not loving people w/o javascript, then yes. :)

Enter the COBOL Confessional
I feel kind of bad for all the people without JavaScript that I gently caress over. I'm not working after hours for free if my job doesn't want to pay for poo poo to be done right.

Ned
May 23, 2002

by Hand Knit

geetee posted:

Enter the COBOL Confessional
I feel kind of bad for all the people without JavaScript that I gently caress over. I'm not working after hours for free if my job doesn't want to pay for poo poo to be done right.

Don't feel bad for them. These people make an active choice to deny you revenue streams and make your job more difficult.

Are you going to work really hard for a customer who comes into your restaurant and orders a water with a shitload of lemons and a baked potato or are you going to spend your time on the people who order steak and cocktails?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
You know, your argument boils down to "I'm lazy and don't care about writing things properly". Writing Javascript that degrades gracefully is also important for when (not if) you have a Javscript bug. If it degrades gracefully, everything still works, more-or-less.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

Avenging Dentist posted:

You know, your argument boils down to "I'm lazy and don't care about writing things properly". Writing Javascript that degrades gracefully is also important for when (not if) you have a Javscript bug. If it degrades gracefully, everything still works, more-or-less.
No - it boils down to him not getting paid to do the work so he won't do it. Appalling, I know.

Ned
May 23, 2002

by Hand Knit

Avenging Dentist posted:

You know, your argument boils down to "I'm lazy and don't care about writing things properly". Writing Javascript that degrades gracefully is also important for when (not if) you have a Javscript bug. If it degrades gracefully, everything still works, more-or-less.

In the publishing industry we can't make any money off of people who have javascript turned off. It costs money to send these people content. We have a host of writers, editors, IT staff, web developers all involved with getting quality content out there. Our only way of seeing revenue is when people view ads. Do you enjoy spending time and money on people who have no intention of letting you earn a few cents off of them?

I am hardly lazy and I do write things properly. I just don't feel it should be a mantra to make things nice for people who intentionally disable javascript. Should a convenience store owner be nice to people who come in and read magazines without ever buying anything?

I mean, it is your time and your money so feel free how to develop in the way you feel. But in this industry people who don't have javascript enabled cost you money.

Kekekela
Oct 28, 2004
edit: never mind, gratuitous

Kekekela fucked around with this message at 23:07 on Jul 21, 2009

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

supster posted:

No - it boils down to him not getting paid to do the work so he won't do it. Appalling, I know.

It's easier to write code that degrades gracefully, so this makes no sense whatsoever.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

Avenging Dentist posted:

It's easier to write code that degrades gracefully, so this makes no sense whatsoever.
Might want to take a look at your own argument then. You're telling him to not be lazy, but yet it's easier to write code that degrades gracefully?

Anyway it's absolutely not true. Maybe in the most trivial cases (lol photo gallery) it's simple to degrade gracefully, but in most real world cases it requires significant extra presentation logic.

I hope you realize that I'm not arguing against writing unobtrusive code that degrades gracefully. I am just saying that if you're working on a client's project and unobtrusive JS is not a part of their requirements and they refuse to pay for the time to design, write, and test it then it's in your best personal interest to not do it.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

supster posted:

Might want to take a look at your own argument then. You're telling him to not be lazy, but yet it's easier to write code that degrades gracefully?

Laziness does not imply "doing the thing that is the easiest", it implies "doing the thing that appears to be the easiest on the very short term".

Save the whales
Aug 31, 2004

by T. Finn

cLin posted:

Oh perfect. So for those websites with modal windows as a login, do they just have the link to the actually login file in case the user doesn't have javascript and just place the return false at the end of the function call?

Exactly. It can also be used for confirmation dialogs (which I generally only use in admin pages).

code:
<a href="/admin.jsp?action=delete-everything" 
   onclick="return confirm('Are you sure you want to delete everything???');">Delete everything</a>

Found Your Answer
Jul 9, 2004

That's like killing a unicorn!
Is there a way in jQuery (or maybe this is just javascript in general? jQuery will make it easier, anyway) to make a textarea always start with a certain uneditable line? For instance, if I wanted my textarea to start with "The text here is not editable because" and then the text after that was editable, how would I do that?

The only way I can think is to just make it so that there is javascript running constantly to see if the first ten characters (or however many that my intro text is) are equal to the phrase I want it to begin with, and if not, reset the value of the textarea to my original phrase.

Adbot
ADBOT LOVES YOU

MrMoo
Sep 14, 2000

windwaker posted:

For instance, if I wanted my textarea to start with "The text here is not editable because" and then the text after that was editable, how would I do that?

Context first, why?

  • Locked thread