«
»

Chris' Brain

Adventures with jQuery

11.24.06 | Comment?

Man, I never realized that I could actually learn to enjoy Javascript. It looks just like PHP or even *gasp* Ruby code to me at times. :)

For my current paid side project I've been using jQuery to do some cool transformational effects. On the page that shows the details for a villa, there's a little section, sort of a sidebar, that has things like the number of rooms, price, etc. Visitors are then allowed to share the information by sending an email.

So, being a guy who always wants to learn I said "Hell, lemme whip up some Ajax goodness so that we don't have to do any page refreshes." Then I said "How the hell do I do that with jQuery any way." Long story short, I got it to work. I'm finally getting the hang of this stuff. How easy was it? Lemme show you:

First, I put all the different divs that will be displayed into the main page. Perhaps this is sloppy, but I'm just a beginner at this. I then went to the style sheet for that particular page and added in:

CSS:
  1. #email {
  2.  
  3. display: none;
  4.  
  5. }
  6.  
  7. #email_thankyou {
  8.  
  9. display: none;
  10.  
  11. }

That made sure those two divs wouldn't show up until I turned them on.? Then, I created an href of the style in a successful effort to avoid having the page scroll up to the top when they click on the link.? Then, we added in the following jQuery magic:

JAVASCRIPT:
  1. function shareVilla() {
  2.  
  3. $("#details").hide("fast");
  4.  
  5. $("#email").fadeIn("slow"));
  6.  
  7. }

Man, I love helper functions that actually read like English.

So then I made sure to hack an existing form validation script to then use some Ajax and post the data to an external PHP script that will send the email.? Here's what I added in, again in jQuery style:

JAVASCRIPT:
  1. $.post("foo.php",
  2. { send_to: document.res_form.send_to.value,
  3. email: document.res_form.email.value,
  4. from: document.res_form.from.value,
  5. your_email_address: document.res_form.your_email_address.value,
  6. textarea: document.res_form.textarea.value,
  7. villa_description: document.res_form.villa_description.value,
  8. villa_url: document.res_form.villa_url.value},
  9. function(){
  10. $("#email").hide("fast");
  11. $("#email_thanks").fadeIn("slow");
  12. });

Again, I find that code to be very readable which means I can actually go back to it later and figure out what it was doing. So, it works:? content fades in and out, data gets posted to an external script, so all that's left is to test to make sure that the emails actually do get sent out.

A tip of my hat to John Resig for creating a great, compact Javascript library.? Steal from the best, I always say.

Comments are closed.


«
»