jQuery For Complete Beginners

jQuery For Complete Beginners – Custom Functions, If Statement

Still with me?

Still determined to learn jQuery and start building more interactive websites with GreenSock or ScrollMagic?

Keep reading and learning, it’s worth it.

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 run a function
  • How to to pass data to a function
  • How to write a simple if statement
  • How to create a simple navigation

Let’s do this!

What is a jQuery function?

jQuery For Complete Beginners

The word function might sound like it is very geeky and scary, but don’t be scared.

Think about functions as a way to group your code.

Function is a block of code which lets you perform a particular task.

Splitting your code into functions makes it easier to read and keeps your code organized.

A simple function would like this:

function highlightItem(){
    $('#gallery li').addClass('active');
}

This function will add class .active to the list item in #gallery.

You can name your functions any way you like, but keep it descriptive so you know what task it is performing.

Run A Function

jQuery For Complete Beginners

You can run your function on a page load or when a specific event is fired (e.g. user clicks onto something).

Read more about click and hover events.

$(document).ready(function() {
    highlightItem();
});

This code would run our function on page load and would add class active to all gallery items.

Try it in the CodePen demo at the bottom of this post.

The functions called straight on a page load usually contain some sort of setup or initial tasks.

Trigger A Function

jQuery For Complete Beginners

Another option is to run your function based on a specific event (e.g. on a click).

var $galleryElement = $('#gallery li');

$galleryElement.on('click', function() {
    highlightItem();
});

function highlightItem(){
    $('#gallery li').addClass('active');
}

This would add class active to all gallery items, but what we want to do is to only highlight the item the user just clicked onto.

That’s where passing data to a function comes in very handy.

Pass Data To A Function

jQuery For Complete Beginners

$(this) inside of a click function refers to the element the user clicked onto.

We can simply create a new variable $item inside of the click function and pass it through to the highlightItem() function like this:

$galleryElement.on('click', function() {
    var $item = $(this);
    highlightItem($item);
});

function highlightItem($item){
    $item.toggleClass('active');
}

We are also changing the addClass() to toggleClass() to toggle between the active class and no class.

The above code would add or remove a class .active from the element we’ve just clicked onto.

Pretty cool, huh?

Simple Navigation

jQuery For Complete Beginners

Now we have a simple highlighting working, but what if we want to also make a simple navigation with previous/next buttons?

Executing the highlightItem() function on the navigation items click would mean that $(this) would refer to the previous/next buttons and wouldn’t really work.

We’ll need to work out which element to pass through to the highlightItem() function.

The Next Button

Lets firstly work out the next button.

// Next button
$nextLink.on('click', function() {
    var activeItemIndex = $('#gallery').find('li.active').index(),
        newIndex = activeItemIndex + 1,
        $item = $galleryElement.eq(newIndex);

    highlightItem($item);
});

activeItemIndex is the index of the item with a class active.

On page load activeItemIndex refers to the index of the element which has the class hardcoded in the html.

We are creating a newIndex which is activeItemIndex plus 1.

At the end we are passing the item whose index matches the newIndex to the highlightItem() function.

The Previous Button

This will work exactly the same way as $nextLink, the only difference is that we are subtracting 1 instead of adding.

// Prev button
$prevLink.on('click', function() {
    var activeItemIndex = $('#gallery').find('li.active').index(),
        newIndex = activeItemIndex - 1,
        $item = $galleryElement.eq(newIndex);

    highlightItem($item);
});

Now this works fine, but we could and should optimize it even more. The problem is that we are repeating quite a lot of the code for both buttons.

Always Try To Keep Things Simple

jQuery For Complete Beginners

When you think about it, both buttons are doing exactly the same thing. The only difference is that $prevLink is subtracting 1 and $nextLink adding 1.

We could combine both into one click function and have a simple if statement inside of it. Like this:

// Navigation Links Click
$prevLink.add($nextLink).on('click', function() {
    var activeItemIndex = $('#gallery').find('li.active').index();

    if($(this).attr('id') == 'nextLink'){
        newIndex = activeItemIndex + 1;
    } else {
        newIndex = activeItemIndex - 1;
    }

    $item = $galleryElement.eq(newIndex);

    highlightItem($item);
});

We are targeting both navigation links using .add() and adding 1 to activeItemIndex for the link with an id=“nextLink”.

If the link doesn’t have this id we are subtracting 1.

Simple right? When you break down even the most complex projects, you realize that it’s all just simple math and thinking.

Nesting If Statements

jQuery For Complete Beginners

We can take it even one step further and stop the navigation when we reach the first and last items.

This can be done by nesting another if statement and checking for the activeItemIndex value.

// Navigation Links Click
$prevLink.add($nextLink).on('click', function() {

    // Prevents jumping to the top of the page
    event.preventDefault();

    var activeItemIndex = $('#gallery').find('li.active').index();

    if($(this).attr('id') == 'nextLink'){

        if( activeItemIndex < 2 ){
            newIndex = activeItemIndex + 1;
        }

    } else {

        if( activeItemIndex > 0 ){
            newIndex = activeItemIndex - 1;
        }

    }

    $item = $galleryElement.eq(newIndex);

    highlightItem($item);
});

Now we are only adding 1 when the activeItemIndex is less then 2 and removing 1 when it’s greater then 0.

We’ve also included event.preventDefault();, this keeps the page at the current position. The links href is # which would scroll the page to the top by default.

You Are Ready!

jQuery For Complete Beginners

Now that we’ve covered:

you are ready to step up and build more interactive websites.

You should be able to quickly grasp libraries such as GreenSock and ScrollMagic and create some awesome interactive websites.

There is still so much to learn, but you have a good base and the courage to keep on earning.

Remember, you learn the most when you are doing things that you’ve never done before.

Good luck!

Playground

jQuery For Complete Beginners

Open the demo on CodePen and explore the code yourself. You should understand every single line of code by now.

How cool is that? From the initial WTF a few days ago, you can now read and write custom jQuery code. Well done!

4864

Conclusion

Creating a simple image gallery like in our example, can be your first step in understanding how jQuery works.

Explore the CodePen demo or create your own image gallery with a simple navigation.

Share your CodePens in the comments below or ask any questions related to the jQuery For Complete Beginners series.

One thought on “jQuery For Complete Beginners – Custom Functions, If Statement

  1. Asif Hussain

    It’s pretty nice series to learn jQuery basics. I really enjoy reading it. I learn a lot looking for more… I’ve also wish to start a series to learn AJAX in the same fashion.

    Reply

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.