Other Pages

jquery_vs_javascript.step

goals do
  goal "Write some straight JavaScript"
  goal "Compare that JavaScript to jQuery"
end

steps do
  
  step do
    message "On the last page, we wrote some jQuery that looked like this. Let's comment it out for now, and see if we can replicate the same functionality in straight JavaScript. Add comment tags before these lines. In JavaScript, the easiest way to comment out a line is to put a `//` at the beginning. Go ahead and try this:"
    source_code :js, <<-JS
//$("#copyright").click(function(){ 
//  $(this).css('color','purple'); 
//});"
    JS
    message "Now if you save the page, refresh, and click the copyright line, nothing should happen."
  end
  
  step do
    message "Underneath the lines you just commented out, let's take a shot at writing the same functionality in straight JavaScript. There are a number of elegant ways to do this; here's one that's not elegant, but it's short:"
    source_code :js, <<-JS
document.getElementById('copyright').onclick = function () { 
   this.style.color = 'purple';
}
    JS
    message "If you save the page, refresh, and click, you should see the same visual result (purple text), but this isn't a great approach for a couple of reasons. Not only is this more typing, and harder to read, it's also easily breakable. (You can only set an element's onclick attribute to one thing, so it might get overwritten by another script on the page and not work later!) jQuery works in a different way, by listening for events, so different functions can all be listening for the same event, and you can add a new response to an event without worrying about overwriting an existing one."
  end
  
end
  
explanation do

  message <<-MARKDOWN

## So Should I Use JavaScript or jQuery?

Don't forget that everything you can do with jQuery, you can do with straight JavaScript.
If you want to start building cool user interface features right away, jQuery will probably
help you do that the fastest. But, long-term, to be great at jQuery, you really need to
understand the language it's written in: JavaScript. It's worthwhile to learn about both.


  MARKDOWN
  
end

next_step 'resources'