jQuery For Complete Beginners

jQuery For Complete Beginners – Datatypes and Selectors

So you’re new to front-end development? Feeling proficient with HTML and CSS, but JavaScript is the one thing that you’re struggling with?

Whether you like it or not, JavaScript or jQuery knowledge is increasingly demanded from every front-end developer.

It’s time to learn how it works and start creating more interactive websites.

This post walks you through all the things you need to know to be able to start using jQuery plugins and libraries, and wow your boss or clients.

Introduction

There are thousands of places on the internet to help you get started with jQuery, but here is all I think you need to know to be able to build websites like this or this.

Nothing less, nothing more than that.

This post is a part of jQuery For Complete Beginners Series
Learn everything you need to know about jQuery before you can create awesome interactive websites using GreenSock or ScrollMagic.
1. Datatypes and Selectors
2. Click, Hover And ToggleClass Events
3. Console.log(), scrollTop(), resize()
4. Custom Functions, If Statement

What you’ll learn today:

  • How to include jQuery in your project
  • How to select elements on the page
  • How to create variables and functions

Get your milk bottle ready and lets dive in.

Why jQuery?

jQuery For Complete Beginners

jQuery is by far the most popular JavaScript library and helps you to easily target any elements on the page.

jQuery’s slogan ‘Write less, do more’ is exactly why you should be using it.

You can use pure JavaScript, but the benefit of using jQuery is that you don’t have to worry about cross-browser compatibility.

jQuery 2.x supports Internet Explorer 9+. If you need to also support the older browsers (I feel sorry for you) you will need to use jQuery 1.x version.

Including jQuery

To include a jQuery in your project simply download it from jquery.com and include the following code snippet right before the closing body tag:

    <!-- Firstly link to the core jQuery library -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')</script>

    <!-- Followed by any jQuery plugins -->
    <script src="js/greensock/TweenMax.min.js"></script>

    <!-- And your custom code in an external file at the end -->
    <script src="js/_main.js"></script>
</body>
</html>

This will try to download the jQuery from the googleapis.com server first, and if it can’t find it then it will load your local jQuery file.

The order of loading these files is very important.

jQuery first, then all plugins, then your own script.

_main.js is a blank file called after jQuery and the jQuery plugins.

That’s the file where you will be writing all your custom code.

Don’t mess up the order.

If you load _main.js before jquery, it would be like putting your pants first and then your undies.

I guess you could do it, but trust me, it feels better the other way.

Starting with jQuery

Having all your custom jQuery code inside of an external file helps to keep everything in one place, similar to an external CSS stylesheet.

$(document).ready(function() {
    //start writing your javascript code here
});

Writing all your code inside of the $(document).ready function will make sure that the code is executed after the page is fully loaded and will prevent any conflicts with other javascript code inside other script tags.

JavaScript Datatypes

jQuery For Complete Beginners

When building an interactive website, you will need to understand the different JavaScript datatypes.

There is quite a few types, but the most commonly used would be a simple text, number, boolean (true or false) or piece of html.

$(document).ready(function() {

    // This is how you create a variable
    var something = 1;
    var something = 1;

    // or even better

    var something = 1,
        something = 1;

});

You can define variables on their own line or even better by separating them by comma.

Defining all your variables at the top of the page is a good idea. This will make it easy to reuse them later on in your functions.

Now to the multiple variable types.

var pageWidth = 500,                         // Number
    message = 'this is our new message',     // String
    html = '<strong>content</strong>',       // htmlString
    animating = true,                        // Boolean - true or false
    object = {},                             // Object
    array = [1,2,3];                         // Array

Number is a number value, which you might have seen when defining a speed or duration of some plugins.

String is simply a piece of text, e.g. a success message displayed after submitting a form.

htmlString is similar to String but also contains html tags.

boolean defines whether something is true or false.

objects and arrays work pretty much the same and simply put they are both a collections of things.

There is quite a few more datatypes, but I’ve found myself reusing the types above most of the time.

Read more about all the other jQuery datatypes, objects and arrays.

jQuery Selectors

jQuery For Complete Beginners

jQuery offers all the selectors you already know from CSS, but also includes additional advanced selectors, which will help you to target any element(s) on the page.

<div id="page-content">
    <h1>jQuery Selectors for Beginners</h1>
    <p id="intro"><strong>This is an intro paragraph</strong> of a simple demo explaining jQuery selectors to the complete beginners. Selecting the right elements on the page is the first step in learing jQuery.</p>

    <h2>Header Level 2</h2>
    <ol>
        <li>Lorem <a href="https://www.ihatetomatoes.net">ipsum</a> dolor sit amet, consectetuer adipiscing elit.</li>
        <li>Aliquam tincidunt mauris eu risus.</li>
    </ol>
    <ul id="gallery" class="clearfix">
        <li class="galleryItem">
            <img src="img/img_ihatetomatoes.png" /></li>
        <li class="galleryItem">
            <img src="img/img_ihatetomatoes.png" /></li>
        <li class="galleryItem">
            <img src="img/img_ihatetomatoes.png" /></li>
    </ul>
    <h3>Header Level 3</h3>
    <ul>
        <li>Lorem <span class="highlight">ipsum dolor</span> sit amet, consectetuer adipiscing elit.</li>
        <li>Aliquam <a href="https://www.ihatetomatoes.net/blog/">tincidunt</a> mauris eu risus.</li>
    </ul>
    <h3>Header Level 3</h3>
    <p>We will be <span class="highlight">targeting individual items</span> on this page. We'll target html elements directly, selecting them by ID or class.</p>
</div>

Assuming we have a page containing the above html, below are the selectors which would help you to target the elements.

You wrap your selector in $('') like this:

CSS Selectors

$('h1') // Selects the h1 element
$('#intro') // Selects our intro paragraph
$('#page-content') // Selects the page content wrapper
$('#gallery li') // Selects every list item within the gallery
$('.galleryItem') // Also selects every list item within the gallery

In the last two examples you can see that there’s multiple ways to select the same element.

From my own experience working on more complex interactive websites I prefer to use id instead of class.

Here are some basic jQuery selectors.

jQuery Selectors

//selects the first list item within the gallery
$("#gallery li").eq(0)

//selects the second list item within the gallery
$("#gallery li").eq(1)

//selects the last list item within the gallery
$("#gallery li").eq(-1)

// selects the list item containing a word 'dolor'
$("li:contains('dolor')")

// selects all links to https://www.ihatetomatoes.net
$("a[href='https://www.ihatetomatoes.net']")

// selects link who's href starts with https://www.ihatetomatoes.net
$("a[href^='https://www.ihatetomatoes.net']")

// selects all links inside any ol on the page
$("#page-content ol").find("a")

// this would select li and p elements
$(".highlight").parent()

// this would select ul which is a parent of span with class highlight
$(".highlight").parents("ul")

.eq() uses the 0-based indexing, which means that .eq(0) will select the first element and .eq('1') will select the second element.

:contains() selects an element who’s content contains the specified text.

element[attribute='value'] selects every element who’s attribute ( id, href etc.) matches the specified value.

element[attribute=^'value'] selects every element who’s attribute ( id, href etc.) starts with a specified value.

.find() searches for a specific element inside of an element.

.parent() selects a direct ancestor of an element, one level up the DOM tree.

.parents() similar to .parent(), but it would select all the ancestor elements up the DOM tree all the way to the html element.

Similarly you can use .siblings(), .child(), .next(), .nextAll() and many more.

For more advanced jQuery selectors visit the jQuery documentation.

Playground

jQuery For Complete Beginners

Use to following CodePen demo to select different elements on the page.

Experiment with the selectors you’ve learned in the previous section, or try something completely new!

Note that I’ve also used the .add() to add additional elements to the set of matched elements. Read more about .add() here.

Conclusion

Knowing how to target individual elements on the page is a first step into building a more interactive website.

It will enable you to start using more advanced plugins and libraries such as GreenSock or ScrollMagic.

Let me know if you have any questions in the comments below and in the next article we’ll cover the following:

  • How to trigger a function on click
  • How to trigger a function on hover
  • How to toggle a CSS class

Until then, keep learning and keep your milk bottle safe.

jQuery click, hover, toggleClass events

10 thoughts on “jQuery For Complete Beginners – Datatypes and Selectors

  1. anees anees

    thank you for this article, Its a very good article for beginning, Im wait a new article, and more advance notes, code, any think from you, I like your Lesson and article …

    Reply
  2. Lohith

    Hi Petr,

    Thanks for the very helpful blog its really helpful for the beginner like me. I was getting afraid of JQuery in learning as i am poor in coding and programming but your tutorial building confidence that i can learn it. Thanks once again,

    Could explain exact difference between these two statements,

    // selects all links to https://www.ihatetomatoes.net
    $(“a[href=’https://www.ihatetomatoes.net’]”)

    // selects link who’s href starts with https://www.ihatetomatoes.net
    $(“a[href^=’https://www.ihatetomatoes.net’]”)

    Your help is much appreciable,

    thanks

    Reply
    1. Petr Tichy Post author

      Hi Lohith, thanks for the comment.

      This would select all links on a page that link to https://www.ihatetomatoes.net.
      $(“a[href=’https://www.ihatetomatoes.net’]”)

      This would select all links that start with https://www.ihatetomatoes.net, that means that also links to subpages such as https://www.ihatetomatoes.net/blog/ or https://www.ihatetomatoes.net/store/ would be selected.
      $(“a[href^=’https://www.ihatetomatoes.net’]”)

      Hope that makes sense now.

      Reply
  3. Waddell

    Hi Petr,

    I’m new to this and I understand the I will have an HTML file then a _main.js file. I put the text below in my _main.js file, but I don’t see any change to the first of the three images.

    $(document).ready(function() {
        //selects the first list item within the gallery
        $("#gallery li").eq(0)
    });
    

    1) Should the first image highlight?
    2) How do I know the .html file identifies the .js file? ()

    Thank you for your help.

    Reply
    1. Petr Tichy Post author

      Hi Waddell, the code you posted only “selects” the item.

      If you want to change its style, you would need to add something like this:

      $(“#gallery li”).eq(0).css('color','green');
      

      And the best way to validate if the js file is referenced correctly is to add an alert or console.log into it.

      console.log('JS files is loaded');
      // or
      alert('JS files is loaded');
      
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>