jQuery for Complete Beginners: Part 1

This is the first part of our new series walking you through the process of learning the hugely popular JavaScript library jQuery from scratch. We’ll start slowly and each week add some more knowledge to your skill set and this will lead us on to doing much cooler stuff with the library. This series is aimed at people who have a strong knowledge of HTML and CSS, so if you don’t have a working experience of those two languages I suggest you learn those before coming back to this.

What is jQuery?

jQuery aims to make JavaScript more accessible for the less ‘hardcore’ developer. For example, there are many cross browser issues with regular JavaScript that jQuery deals with – it does a lot of work behind the scenes to make sure your experience is much more simple and enjoyable. Instead of spending time on the monotonous, boring cross-browser code, you can get straight to work with your cool effects, safe in the knowledge that jQuery is sorting everything out for you.

In Today’s Lesson

Today we’ll start at the very beginning. First we’ll look at how to add jQuery to your pages so you can use it. We will then look at how we select and interact with elements on the page, and then for kicks we will make an element slide across your page. Each week will add a new layer on top of the last, so I suggest you do follow this through. Remember, if you have any questions, please leave them in the comments and I’ll answer them in next week’s edition. So, with no further ado, let’s get started! You can also take a look on what we are going to create today here (Demo).

Including jQuery

Before we can start using jQuery’s functions we need to include the source, that is the file containing the code which makes jQuery tick. You can do this in two ways. Firstly, you can download a copy from jQuery and include it like so:

<script type="text/javascript" src="path/to/jquery.min.js">

If you do it this way, be sure to download the minified version, as it reduces the strain on your server.
The second, and prefered way, is to include it from Google’s Content Delivery Network, or CDN for short. There are two main benefits to doing it this way. Firstly, we can make sure we are always using the most recent version of the library, and secondly it means your server does not have to load the file and it takes up less bandwidth. To include it from the CDN we use similar code to above:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">

That code will always load the most recent version of the library (well, until V2 is out), but you can be much more specific if you wish to and load a certain version:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">

Lets write some Code!

Now we now how to add jQuery to our page we can get writing some! You should include jQuery using one of the two techniques covered above just below the end tag on your page. This way, the file is loaded last, meaning that all the HTML content is loaded first, so we make sure the page’s look & content is loaded first. Below that, add the following code:

<script type="text/javascript"></script>

Inside those tags is where we will write our code. Before we start manipulating and interacting with elements, we will learn how to select elements. If you know CSS, it’s really easy. To select an element with jQuery, we use the $ symbol followed by parenthesis: $(‘your selector goes here’). That selector can be any valid selector, including new CSS3 selectors. For example, to select all divs on my page, it’s as simple as:
$(‘div’). A few more examples follow:

$('div p') //selects all paragraphs that exist within a parent div.
$('#something') //selects the element with an id of 'something'
$('.something') //selects the element(s) with a class of 'something'

You can be as complex as you like: (Note: in the next article we will spend a lot of time looking at much more complex selectors)

$('div p#something a') //selects all anchor elements within a paragraph with an id of 'something' within a parent div.

jQuery’s selector engine is pretty much limitless and in the coming weeks you will learn to harness this and take full advantage. For now, lets keep it simple. In your page, create a new <div> element:

<div id="something">
<p>this is some text</p>
</div>

And also add some CSS to it:

#something {
width: 200px;
height: 200px;
background-color: red;
color: white;
border: 4px solid black;
margin: 100px 0 0 80px;
}

You should be left with something like this:

Make it Move

To end this lesson, we are going to make the div move slowly across the page. Firstly, using our selector knowledge, we can select it:

$('#something')

You could equally use $(‘div’) if you like, but personally I like to be as specific as I can. Once we have the element we can use jQuery’s animate() function to run our animation:

$('#something').animate({'margin-top': '300px', 'margin-left': '400px'},1000);

The animate function takes 3 main arguments, but one of them is optional:

.animate(things to change, speed, callback);

‘Things to Change’ are the properties of the element which we want to animate, in our case it’s the top and left margins. The way we add multiple properties is like so:

.animate({'param': 'value', 'param2': 'value'}, speed, callback)

After each set, you add a comma, apart from after the value of the very last property. ‘Speed’ is the speed at which the animation will run, or: ‘how long will it take before the animation is complete?’. This is in milliseconds (1000 = 1 second). ‘Callback’ is a function that runs after the animation is run. For now we are not using it, but it’s something we will utilise in the future. So, back to our animate() code:

$('#something').animate({'margin-top': '300px', 'margin-left': '400px'},1000);

We change the top margin of the element to 300, from 100, and the left margin is also increased. Open this page, and you should see a smooth animation over the course of a second: And there you have it! I hope you’ve enjoyed your first crash course in jQuery. You can watch the demo here.Any questions, leave them in the comments and I’ll address them in the next post.

Jack Franklin

Jack Franklin is a 17 year old budding web designer & developer living in Cornwall, England who enjoys messing with HTML, CSS, PHP & Javascript. Away from the desk, Jack enjoys badminton, football & snooker.

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. Tushar says

    #something {
    width: 200px;
    height: 200px;
    background-color: red;
    color: white;
    border: 4px solid black;
    margin: 100px 0 0 80px;
    }

    Untitled Document

    $(‘div p’) //selects all paragraphs that exist within a parent div.
    $(‘#something’) //selects the element with an id of ‘something’
    $(‘.something’) //selects the element(s) with a class of ‘something’
    $(‘#something’).animate({‘margin-top': ‘300px’, ‘margin-left': ‘400px’},1000,animate());

    this is some text

    this code is not working if u can tell me about my error then i’ll very grateful to you.

    • SAM says

      Untitled Document

      #something {
      width: 200px;
      height: 200px;
      background-color: red;
      color: white;
      border: 4px solid black;
      margin: 100px 0 0 80px;
      }

      this is some text

      $(‘#something’).animate({‘margin-top': ‘300px’, ‘margin-left': ‘400px’},5000);

  2. Jenitsa says

    What’s Happening i am new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has aided me out loads. I am hoping to give a contribution & aid different users like its helped me. Good job.

  3. sunny says

    Hi,

    Queries !!!

    please explain to me why the code doesnt work when I tried using the jQuery script in the Head section
    and also why do we have to end the script tag while including the js library ????

    thanks in advance

  4. Carter says

    Just now I ran across the web for exactly these kinds of information. Thank to your post that search has to end at this time. You published the post in a very comprehensible way. With this, I added your blogs as one of my personal favorites! Kind regards!

  5. Jim says

    The good thing about the internet and internet transactions is that you never have to look into the face of the person you are dealing with. As such if you have to disappoint them by walking away, you may not feel as guilty. That is how come online car insurance is so much more attractive. To get a car insurance quote, you may have to give some personal information like your name, address, contact numbers, and stuff. Those are understood. Even your date of birth is essential and understood. But if they begin to ask you for payment details at that time, you may want to lose interest in a hurry. They can’t be for real.

  6. mamta says

    hii
    i found this article very helpful as a beginner of Jquery…please telll me where to read about it more…

    Thanks

  7. Alexander Rhett Crammer says

    I tried this a millioun times and it never worked. I even copied and pasted the exact text you gave and it still didn’t work!

    • mina says

      #something{

      width: 200px;
      height: 200px;
      background-color: red;
      color: white;
      border: 4px solid black;
      margin: 100px 0 0 80px;
      }

      this is a text

      $(‘#something’).animate({‘margin-top': ‘300px’, ‘margin-left': ‘400px’},1000);

  8. Cscalcu says

    I have been trying to take one small step at a time in learning jQuery… The first program I wrote is pasted below: The problem I am facing is when I run the applcation and click the button I have an error dialog pop up saying –> “Microsoft JScript runtime error……

  9. walter Earnshaw says

    Thank you for Part 1 of your new tutorial. I am looking forward to Part 2.
    On my own I can’t get my skull around the whole topic – maybe you will be of help.
    It piques me a little – A 77 year old man with a 17 year old teacher showing that you can teach new tricks to an old dog!

    Be seeing you

  10. says

    very nice tutorials., thanks for your explain., can you make all this tutorials to PDF file? Thanks alots of…

  11. says

    Very nice and easy to follow tutorial – great. To make it even more userfriendly, I would suggest to include links to the other parts of the jQuery Series inside the article. So we could easily reach the next article… :).

  12. Tim says

    Thanks for this. I had one problem. When I copied this code in the tutorial, it didn’t work:

    But when I viewed and pasted from the source code of your Demo:

    it worked!

  13. maxine says

    Thanks for the tutorial. I’ve been trying to figure out this JQUERY stuff and your tutorial helped to narrow it down a bit for me by giving me the basics. Every time I google learning Jquery I see your website listed so there must a lot of people out there trying to figure it all out too. I’m just beginning to master html and css, now here comes jquery, ajax, etc.

  14. suresh says

    Nice work.
    It is very useful to HTML Developers and they can learn more about JQUARY
    Thanks Jack

  15. r. clayton says

    The answer the previous question about two moving divs appears to involve the always vexing difference between CSS classes and identifiers: defining and selecting on the something class moves both divs ( http://pastebin.com/RNzJZKwu ), which makes sense if you ignore the fact that both #something divs responded to the first move.

    Today’s question: both divs move horizontally to the right in sync, but the bottom div (“some more text”) appears to move twice as fast vertically down than does the top div (on Iceape 2.0.3 and Opera 10.10). Why the difference?

  16. Ryan Cowles says

    Looking forward to this series! jQuery is something I need to really get into!

  17. r. clayton says

    If I add a second something div and split the movement into horizontal and vertical parts ( http://pastebin.com/wXUsHVdY ), both divs move down but only one moves right (on Iceape 2.0.3 and Opera 10.10). Why aren’t the two div motions identical?

  18. Jack F says

    Hello everyone,

    Thanks for your kind words! I’ll email through the files to the admins of the site and ask them to upload it and add the link.

    To the people who asked – I’ll mention $(document).ready() in Part 2 ;)

    Thanks,

    Jack.

  19. says

    Thanks for making this Tut, Its exactly what I’m looking for and has arrived at just the right time.

    – Shaun

  20. says

    Hi Jack,

    Thanks for this tutorial.
    I’m having trouble getting my code to work though. Not sure where I’m going wrong, any ideas?

    Here’s what I’ve written:

    $(‘#testblock’).animate({‘margin-top': ‘300px’, ‘margin-left': ‘400px’},1000);

  21. says

    Nice tutorial, Jack!
    One thing I’ve been (sort of) looking for is an explanation about the parentheses and bracket combinations. I’m never quite sure if I need them or where to put them…

  22. says

    Nice intro in jQuery. I’m looking forward to the next post.

    A demo would be great of beginners though. And the option to download the files.

  23. Slobodan Kustrimovic says

    Nice, but you should have mentioned $(document).ready so they can use their codes in the header and not get confused why it’s not working. :)

  24. Beth McLain says

    Nice work.. Awesome primer for newbies getting started in jQuery. It covers most of what I was looking for when I got started.

  25. says

    Very nice post, thanks for sharing. As was already mentioned a demo will go a long way to see your code in action.

  26. Remus says

    Nice work Jack but you are missing Demo, I think for the novice users this is very important.
    Good luck for your series.

  27. says

    Hey Jack!

    Great tutorial, but indeed, a demo would be very nice. Both the picture refer to a .png file, a page with the effect would make it even better!

    Waiting for your next post :)