Author: agrublev

There is a small list of the things that you need to memorize to do well on the Final Exam:

  • Header
    • SVG logo is simply an img tag with a src and a width attribute
    • Apply flex, justify-content (space-between), and align-items (center)
    • Add padding to the top and bottom (20px 0)
    • The buttons in the right navigation need
      • To be selected directly with CSS (not the wrapping div) .menu a
      • Use display: inline-block (proper way to apply padding)
      • Add padding
      • Remove the text-decoration (set to none)
      • Border needs 3 property definitions:
        • Width = 1px
        • Style = solid
        • Color = green (or black or any color)
        • Resulting in: border: 1px solid green;
  • Hero requires a background image, background-size cover, and padding (90px 90px 60% 90px)
    • background: url(http://somewhere.com/myimage.jpg) no-repeat;
    • background-size: cover;
  • The left column needs a width of about 30% and will contain a form which needs 3 tags
    • Open close form tag
    • Input tag (can be empty, and it’s a self-close tag like img)
    • Button tag (with text Go inside)
  • In the left column, the list with fontawesome icons needs you to  copy the code from the fontawesome page I provide but also needs you to add the link tag from the fontawesome Getting Started page from the header navigation in their website!
  • The footer should have two immediate children (logo and footer-nav)
    • The footer-nav also has two immediate children nav-left and nav-right
    • The anchor buttons inside the left and right nav need to be display: block; with a border-bottom

If you remember these instructions you should do quite well!

jQuery for Beginners

The 6 Line Starter Template

<script src="http://code.jquery.com/jquery-latest.min.js"></script>  
<script>  
$(function(){
    // jQuery Code Here  
});  
</script>

Paste these lines right above the </body> of your page and you have access to all of jQueries abilities!

Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to “query (or find)” HTML elements (same as a CSS selector)
  • A jQuery action() to be performed on the element(s) (like hiding)

Example:

$(this).hide() //- hides the current element.

$("p").hide() //- hides all <p> elements.

$(".test").hide() //- hides all elements with class="test".

$("#test").hide() //- hides the element with id="test".

jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to “find” (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It’s based on the existing CSS Selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().

Actions

Let’s hide all paragraphs on a page:

$("p").hide();

What are Events?

All the different user’s actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

  • moving a mouse over an element
  • scrolling the page
  • resizing the browser
  • clicking on an element

The term “fires/fired” is often used with events. Example: “The click event is fired, the moment you click with the mouse”.

Here are some common DOM events:

Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload

jQuery Syntax For Event Methods

In jQuery, most DOM events have an equivalent jQuery method.

To assign a click event to all paragraphs on a page, you can do this:

$("p").click();

The next step is to define what should happen when the event fires. You must pass a function to the event:

$("p").click(function(){
  // action goes here!!
});

Common Events and Actions

click()

The click() method attaches an event handler function to an HTML element.

The function is executed when the user clicks on the HTML element.

The following example says: When a click event fires on a <p> element; hide the current <p> element:

Example:

$("p").click(function(){
    $(this).hide();
});

jQuery hide() and show()

With jQuery, you can hide and show HTML elements with the hide() and show() methods:

Example:

$("#hide").click(function(){
    $("p").hide();
});

$("#show").click(function(){
    $("p").show();
});

jQuery toggle()

With jQuery, you can toggle between the hide() and show() methods with the toggle() method.

Shown elements are hidden and hidden elements are shown:

Example

$("button").click(function(){
    $("p").toggle();
});

See the Pen backToBasics by Angel Grablev (@agrublev) on CodePen.

Full list of actions

Traversing the dom

Often you need to get creative with selecting the right element. jQuery offers a huge selection of actions to traverse (navigate the dom) from the current selector.

For example, if we want to click on a dropdown button and activate the closest dropdown content element we can:

$(".open-dropdown").click(function(){  
    $(this).closest(".dropdown-content").slideToggle();  
});

Other useful traverse actions:

  • parents(“selector of parent to find”)
  • find(“selector of ethe lement to find inside currently selected element)
  • parent() // selects immediate parent element
  • siblings() // selects all of the siblings of the selected element (like all other list items)
  • children() // selects all immediate children of the element

Full list with examples

Checking things (filtering)

We can also filter the results from our selector. For example if we want to get all .button elements but only get the ones with a class .email.

$(".button").is(".email").addClass("email_icon");

Some other filters:

  • first() // get the first matched
  • last() // get the last
  • not(“selector to ignore”)

Full list of filters

Manipulating the dom

Sometimes we want to remove or add new elements to the page.

For example, after the user registers we may want to add a profile image in the header:

See the Pen appendMe by Angel Grablev (@agrublev) on CodePen.

Append adds the new element right before the closing of the selected element. There are other methods like:

It can be a nightmare to write HTML inside of the append(“STRING”). Especially because you have to constantly remember to use double or single quotes depending on what you use to wrap the entire html element with. But we do have some options! First, let’s review the issues:

  • Need to use single quotes around the element and double quotes inside where you add attributes
  • To write the HTML on multiple lines so it’s legible we need to use the string concatenation ‘+’
  • To add any variables from javascript we need to also use string concatenation ‘+variable+’
  • It’s hard to edit the HTML

Advanced variable usage:

We can use some JavaScript hacks to make it easier to support multiple lines and easier to work with code. But it’s not ideal!

See the Pen templates by Angel Grablev (@agrublev) on CodePen.

Using a script tag:

One option is to use a script tag with a special type so the page doesn’t try to run the code. Then select the script tag and get its HTML content with jQuery. Then we can go about changing text or attributes.

See the Pen templates by Angel Grablev (@agrublev) on CodePen.

We can achieve a similar effect by adding an html element with our template, hiding it, then using jQuery to duplicate it and append it everytime we need to use the template.

Literals:

We can use the special ` slanted quote to define the HTML and even add multiple lines, it’s called Template Literals and of course, Internet Explorer does not support it!

There are hundreds of plugins/libraries that actually make working with templates into a fun experience.

https://github.com/BorisMoore/jquery-tmpl

https://github.com/janl/mustache.js

http://handlebarsjs.com/

http://idangero.us/template7/#.WxCKsFMvyOE

And of course it comes built into Angular/Vue/React and other libraries.

Examples of using what we learned

Plugins

jQuery plugins allow us to do a lot of amazing things without having to write almost any code!

http://vanity.enavu.com/

jQuery UI

Voting time http://x.co/votejs

https://alvarotrigo.com/pagePiling/

https://alvarotrigo.com/fullPage

http://www.thepetedesign.com/demos/tiltedpage_scroll_demo.html

http://git.blivesta.com/animsition/

http://scrollme.nckprsn.com/

https://www.adchsm.com/slidebars/

http://rubentd.com/gifplayer/

http://vodkabears.github.io/vide/

https://mntn-dev.github.io/t.js/

Modals

http://izimodal.marcelodolce.com/#modal-default

http://jquerymodal.com/

Dropdowns

https://www.jqueryscript.net/menu/jQuery-Plugin-To-Create-Multi-level-Bootstrap-Dropdowns-Bootstrap-Submenu.html

https://www.jqueryscript.net/menu/jQuery-Plugin-To-Toggle-Bootstrap-Dropdowns-On-Hover.html

Many ways to find them!

https://www.sitepoint.com/jquery-popular-plugins-list/

 

Exercise: Midterm Prep Puzzle

In the following pen, you will need to add the correct class from the pre-defined classes inside the correct elements.

CodePen Link

Basically, look at the available classes, for example

This would be the styling that we would want to apply to the header of our website. In the html, the following element appears to be the correct header that needs this styling:

So we would add the class two to it like this:

And our preview will now look like this:

One class may be used many times, and some elements may not need a class at all!

Building a simple website from scratch

In this tutorial we’ll build the exact same website from the midterm. It contains the following elements:

  1. Header: With a logo and a menu
    1. The menu should have black buttons with white text
  2. A two column main element
    1. The left column should have a title and a vertical navigation
    2. The right column should contain a title and a paragraph of text

The final product should look like this:

Creating a project inside WebStorm

You can either create a project from the welcome screen

Or if you’re already inside a project go to File -> New -> Project

Replace where it says “untitled” with your project name

like this

No spaces! Just text characters.

Then click the create button.

Starting our project with the needed files

We’ll first need our index.html as this is the file our server will always look for to show to the user first (even if you have 100 other pages).

Right click on the little folder with the name you chose for the project, then select New -> HTML File

You should now see an index.html in the left column of your editor

Now we repeat the process to create a stylesheet called style.css (please always use lowercase characters, no spaces, and try to name the files for each website the same! For example, your stylesheet can be named main.css or style.css, but those are really the only names you should use!)

Adding your stylesheet in the HTML

For us to use a stylesheet (as there can be 10 available stylesheets in a big project for each page) we need to link it from the html file using the link tag.

The link tag should go immediately before the closing of the head tag.

It contains two attributes, rel (relationship, it’s a stylesheet) and href (which is the path to the stylesheet file).

If we created a folder called css then the href would be href=”css/style.css” meaning we’re referencing the folder and then the file inside it.

As a sanity check, making sure our stylesheet is now linked we can simply make the body background black. When we preview our html page the background should be black.

And then from within our index.html file we click the browser icon from the top right:

Great, we’re all set here, let’s erase the sanity code from style.css.

To make it easier to look at both our html and css at the same time, you can simply right click on the style.css tab in your editor and choose split vertically

Then close the tab on the left side that says style.css leaving it only on the right-hand side.

 

Adding the initial HTML markup

The very first thing we should tackle is each section of our website. In this case, we’re creating a simple website with two sections, a header and a main (which has the two columns).

Keeping in mind all our code goes inside the body element! We use a class to identify each section, allowing us to reference them later when we apply styling.

Filling in the sections

Now we can start filling in each section with markup based on our website design. In the header, we have a logo and a menu. The menu contains buttons (anchor links).

And the main section contains two columns:

Each column has a title

In the left column we add a vertical menu, and in the right a simple paragraph.

Here is the final code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="header">
        <h1 class="logo">
            Logo
        </h1>

        <div class="menu">
            <a href="https://google.com">
                Go To Google
            </a>
            <a href="https://microsoft.com">
                Go To Microsoft
            </a>
        </div>
    </div>

    <div class="main">
        <div class="left-col">
            <h2>Welcome</h2>
            <div class="left-menu">
                <a href="https://google.com">
                    Go To Google
                </a>
                <a href="https://microsoft.com">
                    Go To Microsoft
                </a>
            </div>
        </div>
        <div class="right-col">
            <h2>Great stuff</h2>
            <p>Right column text</p>
        </div>
    </div>
</body>
</html>

Adding our styling

To make our webpage look the same in every browser we can include the normalize.css library. We add it the same way we add our style.css, with a link tag, but we can use a CDN link instead of storing it in our project folder.

Very important to notice that we add the link tag before our style.css, this ensures our styles override those of the normalize.css! This is the same logic as when we add a framework. Styles declared lowed in the document are more important.

Now we can focus on getting the website to look correctly. I will again do this section by section. Starting with the header.

The header contains two immediate children, .logo and .menu which should appear next to each other as columns. To do this we’ll apply:

  1. display: flex; // making its immediate children display as columns
  2. justify-content: space-between; // forcing the columns to spread out to each side of the page adding space between them
  3. align-items: center; // now we can center the items inside vertically, because our logo will be much higher than the menu items and we want it to look nice

Which will look like this:

Converting Anchor Links into Buttons

To make our navigational links appear as buttons (larger clickable area, custom colors, etc) we have to select the actual anchor tag with our CSS. Otherwise the browser will always apply its own styling that we can’t override.

Here is how we select the anchors inside the .menu div:

By selecting .menu div first, then adding a space, and then entering the name of the anchor tag a, we are telling the browser to select all anchor elements inside the div with a class menu.

Allowing us to apply the following important styles:

  1. display: inline-block; // By default an anchor is display inline, which is great when it appears amonst text. But as a button it needs to be able to display as a button with extra padding inside it. To do this we use inline-block
  2. text-decoration: none; // The browser adds an underline to all links, so we need to remove this (if we want)
  3. padding: 10px 20px; // Padding should typically be less on top and bottom than left and right. So we set top/bottom to 10px and left/right to 20px. We use padding on the anchor because we want the clickable area to be nice and large. If we used margin, or added padding to the wrapping element, the clickable area would only be the text of the anchor
  4. color: white; // Changing the text color
  5. background: black; // Changing the background color

Let’s review what we have so far:

Great, the header is in great shape. Let’s move to the .main element with the two columns. Step 1, make the immediate children display as columns:

Now we need to add styling to the buttons in the left column navigation, almost identical to the ones in the header, but I want the buttons to be display block, which will make them take up the full horizontal space in the left column. And add some spacing underneath with margin-bottom:

Result

Looking great, a couple more small styling improvements and we’re done.

Adding padding to our columns

We don’t want the right column to be directly touching the left column, so we can simply add some padding to the columns to give them a little breathing room:

Here we use a special css selector, by declaring each selector and then adding a comma between the next selector we can select multiple selectors and apply the same styling. So we’ll add 15px padding to the left column, right column, and the header. Result will look like this:

And now we just want to add a gray background to the left column:

Here is the final CSS code:

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.menu a {
    display: inline-block;
    text-decoration: none;
    padding: 10px 20px;
    color: white;
    background: black;
}

.main {
    display: flex;
}

.left-menu a {
    display: block;
    margin-bottom: 3px;
    text-decoration: none;
    padding: 10px 20px;
    color: white;
    background: black;
}

.left-col, .right-col, .header {
    padding: 15px;
}

.left-col {
    background: gray;
}

 

That’s it! You’ve created a basic website 🙂

jQuery Exercises