Other Pages

Jquery Vs Javascript

Goals

  • Write some straight JavaScript

  • Compare that JavaScript to jQuery

Steps

Step 1

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:

//$("#copyright").click(function(){ 
//  $(this).css('color','purple'); 
//});"

Now if you save the page, refresh, and click the copyright line, nothing should happen.

Step 2

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:

document.getElementById('copyright').onclick = function () { 
   this.style.color = 'purple';
}

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.

Explanation

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.

Next Step: