10/11/2018

Exercise 17

The Child Selector

The child selector targets elements immediately inside of the parent element.

Think of it as if you control your children, but your grand children totally ignore the rules.

div > a {/* css rules */}

Child vs Descendant

div a {/* css rules */}

Applies to every a

div > a {/* css rules */}

Applies only to the a immediately after the div

jQuery .css()

We can retrieve and modify an element's css value using jQuery's .css() method.

Retrieving values

You can get the current value of a CSS property in jQuery by passing a string into the .css() method.


    var x = $('element').css('height'); // Retrieves the css height of the element
                

    var x = $('element').css('backgroundColor'); // Retrieves the color value of the element
                

    var x = $('element').css('background-color'); // Retrieves the color value of the element
                

Setting Values

There are two ways to set CSS using jQuery. The first method is to pass in two strings.


$('element').css('background-color', '#aa0000');    
$('element').css('padding', '20px');    
    

$('element').css('background-color', '');    //Resets property
$('element').css('padding', '');    //Resets property
    

Setting Values Continued

You can set multiple CSS values by passing in a javascript object


$('element').css({
    backgroundColor: '#aa0000',
    padding: '20px'
});    
//////// or
$('element').css({
    'background-color': '#aa0000',
    'padding': '20px'
});    

    

jQuery Class Manipulation

Manipulating an object's class in jQuery is very similar to what you would do in vanilla JavaScript.

.addClass()

Adds a class to an jQuery object.


        $('element').addClass('active');
        

.removeClass()

Removes the class from the element


        $('element').removeClass('active');
        

.toggleClass()

Add the class if the element doesn't have it and removes the class if it does have it.


        $('element').toggleClass('active');

.hasClass()

Returns a boolean value of true or false base on if the element has the matching class.


        var x = $('element').hasClass('active');
        console.log(x);  //outputs true or false;

Traversing with jQuery

Traversing your DOM allows you to write code that wont interfere with other parts of your application.

.find()

The .find() method allows you to run a selector within a specific context. It will search its descendants.

A highly performant example


    var frm = $('.myForm');

    frm.find('input[type="text"]').on('blur', validate);            
    frm.find('select').on('change', validate);            
    frm.find('button').on('click', submit);            
            

See the Pen UA-ITR-jQUery-Find by Jon (@Middaugh) on CodePen.

.closest()

The .closest() method checks the current element first and then searches up the DOM until it finds the first element that matches.

.closest() API

Example of how the search works

Example


        $('.btn').closest('div').hide();    
        

    

.parent() and .children()

These are useful for only searching above the object or below the object.

.parent()

.children()

See the Pen UA-ITR-jQUery-Clossets by Jon (@Middaugh) on CodePen.

jQuery .filter()

The jQuery .filter() method takes the current jQuery object and reduces the set based on the following.

  • A selector
  • A function
  • A DOM element
  • A jQuery Selection

Filtering with a selector.


    var inputs = $('input');
    var textInputs = inputs.filter('[type="text"]');
    var checkBoxes = inputs.filter('[type="checkbox"]');
            

Filtering with a function


    var inputs = $('input');
    var fifthInput = inputs.filter(function(index){
        if (index === 4){
            return true;
        }
        return false;
    });
            

Even and Odd Selectors

These are jQuery specific selectors. They do not take advantage of the browser's built in selector system.



    var evens  = $('li:even'); 

    var odds  = $('li:odd'); 

            
Even Odd

Recommended usage

This selector doesn't take advantage of the faster native selector engine inside of JavaScript. The documentation recommends you select your elements and then use .filter() to get your desired result set.



    var listItems = $('li');            
    var evenItems = listItems.filter(':even');
    var oddItems = listItems.filter(':odd');
            
            

See the Pen UA-ITR-Even-Odd by Jon (@Middaugh) on CodePen.

Questions?

Tips for debugging code.

We all get stuck from time to time with broken code. We know what it needs to do, but don't know why it isn't doing what we expect.

Don't assume there is something wrong with the browser.

Your computer doesn't hate you.

Batch your work.

Don't write 20 or 30 lines of code without testing what you have written.

Batch your work into smaller units to understand what is going on.

Bugs are easier to find when they are small.

Example

I want to validate a form field when I click a button.


            $('btn').on('click', function(){
                console.log('click worked');
            });
            

I test that my click is working before continuing with my work.


            $('btn').on('click', function(){
                console.log($('input').val());
            });
            

Read the documentation.

Using a third party library can be hard at times. Good libraries provide good documentation, examples and demos. Study them to understand how they should be used.

Read your error messages

Most error messages by your editor or browser point you to the exact line that is broken.

If you can't tell what's going on, copy and paste that into Google.

Use caution when copy and pasting examples.

You lose understanding when copy and pasting someone else's code.

Manually type out code instead of copying it.

Take advantage of your tools

Use Google Chrome's Debugger

Find "linters" for your editor

Remember Errors are opportunities to learn.

You wont learn anything if everything worked the first time you try it.

JavaScript Callbacks

Callbacks are functions passed into other functions as parameters. These functions are intended to be used inside of the functions they are passed into.

Examples

Can someone tell me what this will do?


    function myCallback()
        console.log('Operation Complete');
    }            

    function addSomething(x, y, onComplete){
       var z = x + y;
       console.log(z);
       onComplete();
    }

    addSomething(1, 3, myCallback);

            

We've been doing callbacks already.


    document.getElementById('id').addEventListener('click', function(){
        //Callback
    });
            

    $('button').on('click', function(){
        //This is a callback
    });            
            

Using callbacks for the UI


    $('button').on('click', function(){
         //Click Event
         $('.container').slideDown('fast', function(){
             //Slide Down Callback
             $(this).find('p').fadeIn('fast', function(){
                 //Fade in Callback
             });
         });
    });            
            
Previous JSFiddle example

The Blur Event

The Blur event is triggered when an element has lost focus.

Primarily used on inputs.

Example


    
    $('input').on('blur', function(){
        //event triggered.
    });
            

Example

See the Pen UA-ITR-jQUery-Blur by Jon (@Middaugh) on CodePen.

Hover

The hover events allow you to add JavaScript to elements as the user uses their mouse to move around them.

A full hover event uses two event listeners.

Syntax


        var elm = $('.my-element');     

        elm.on('mouseenter', function(){
            //Code executed when the mouse goes over an element
            $(this).addClass('hover');
        });

        elm.on('mouseleave', function(){

            //Code executed when the mouse exits the element. 
            $(this).removeClass('hover');
 
        });
        
    

A lot of js frameworks will add the hover class for you.

See the Pen UA-ITR-jQUery-Hover by Jon (@Middaugh) on CodePen.

jQuery Data Attributes

Data attributes allow you to store arbitrary information in your HTML elements for later use.

Basic Data Attribute Usage

Setting an attribute in HTML

<div data-[name]>


    

    

Getting a data attribute in JavaScript


        var div = $('div')

        var color = div.data('color'); //Finds and converts data-color

        console.log(color); // logs '#000';

        var type= div.data('type');
        
        console.log(type); //logs 'My Data Type'
        
    

Example

See the Pen UA-ITR-jQUery-Data by Jon (@Middaugh) on CodePen.

Setting a data attribute

We can dynamically add and update a data attribute as we need to.


                
    $('.element').data('color', 'red');

                

Example

See the Pen UA-ITR-jQUery-Data2 by Jon (@Middaugh) on CodePen.

You can use more than just Strings and Numbers with data attributes

  • Objects
  • Functions

Example

See the Pen UA-ITR-jQUery-Data2 by Jon (@Middaugh) on CodePen.

Exercise 17

>