Using Javacsript and jQuery to make your static pages interactive.

Recap

So in our last lesson we learned how to add styles to elements in web documents using CSS rules and selectors. You should recall that we looked at the following points, which will be important for our lesson today:

  • Using CSS selectors to select using classes, ids and tag names (.my-class, #md-id and tag respectively).
  • Using CSS rules to add styles to different elements (like color: red;, font-size: 10px and border: 1px solid blue;).

Making pages interactive

So far everything we've seen with HTML and CSS is what we call 'static'. That is to say, we're simply showing text or information on the screen without any interaction or input from the user.

As you know, almost all websites now have a degree of interactivity. Whether that be leaving comments, submitting posts, voting or liking other people's submissions, sending an email via a contact form or any of a thousand other possible interactions.

These interactions are impossible using just HTML and CSS. We need to other languages on top or in combination with HTML and CSS in order to allow users to interact with our pages.

Server side vs client side

If you cast your mind back to the class on learning HTML you'll remember we talked a little bit about servers and clients. A server is the computer from which the client remotely requests a web page.

When we put in place interactions in web pages, there are two types of language we use: server-side scripting and client-side scripting.

Server-side scripting is used for things where data is sent to the server and processed by the server. It could be something like leaving a comment on a web page. A user fills in their comment in the web page, presses 'Submit' and the comment is sent to the server. The server then takes the comment and saves it in the database, to show it to everyone else who sees that page.

Most server-side interactions involve the server processing the data and the web page must be refreshed to get the new information.

Client-side scripting is used for (traditionally) smaller tasks, which provide immediate interaction with the user, and generally don't involve sending information to a server. Something like checking that your email address is correct in the comment-form before the form is submitted. Or maybe opening / closing different sections or pop-ups on a web page.

Unfortunately it's not quite this easy as nowadays many web apps use client-side scripting to send data to a server (without navigating to a new page) and then the server can respond with data and the client-side script can update the page with this new data without a page reload.

For the purposes of this class these exceptions aren't really important but you should still know that they exist.

Some examples of server-side languages

Server side languages, then, are run on the server where they process inputs and send the result to the user via (usually) a web page.

The most common server-side language when we're talking about the web is PHP, but there are some others such as:

  • Perl
  • Python
  • ASP
  • Ruby

Some examples of client-side languages

There is only really one major client-side scripting language used on the web nowadays: JavaScript. JavaScript is part of the W3C standards just like HTML and CSS, and just like HTML and CSS the server sends us the 'raw' JavaScript and then it is interpreted and executed by our browser as the web page loads.

JavaScript or JS for short, is a client-side scripting language and has nothing to do with Java, the server-side language.

So basically for most small / medium-sized websites, PHP = back-end, and JavaScript = front-end

...except that one of the biggest up-and-coming server-side languages is NodeJS. NodeJS is JavaScript, but instead of being sent to the browser and read by the browser, it is interpreted and executed by the server like PHP...

...yes it's confusing even for us specialists...

CommitStrip Javascript back-end strip

Meet JavaScript

JavaScript is, then, a client-side language. It's a real programming language (unlike HTML and CSS) because it contains real logic. With JavaScript we can write little scripts (or mini-programs) which do things like:

"If you click on this button here, change the color of my text to blue".

or

"If I click on this button, check if I have entered text in my form. If I have entered text, submit the form, but if the form is empty, pop up a little error message reminding me to fill out all the fields."

...and meet jQuery, JavaScript's partner in crime

Although JavaScript is part of the web W3C standards like CSS and HTML, more than 90% of sites on the website use it in combination with jQuery. jQuery is a library which is a kind of bundle of all sorts of useful functions and tools to help us write JavaScript more easily and in a more logical way.

There are other libraries too, and you might also hear about Vanilla JS - that means JavaScript without any kind of library to help you.

jQuery helps us write much more quickly and logically, and also helps 'smooth over' all the little differences in how each Browser will interpret code slightly differently (I'm looking at you Safari and Internet Explorer...).

To see what I mean, let's take our first example :

"If you click on this button here, change the color of my text to blue".

In Vanilla JS this would be something like:

document.getElementById('my-button').onclick = function(){
  document.getElementById('my-text').style.color = 'blue';
}

We're basically telling the Javascript to get the element with id my-button. When someone clicks on it, we'll get the 'my-text' element and set the color to blue.

In jQuery this would be a little more readable:

$('#my-button').click(function(){
  $('#my-text').css('color', 'blue');
});

Both of these are strictly equal, but notice a few nice features of the second version:

  • We can use CSS selectors in the $() function to select our HTML elements.
  • We can use the .css function to get and set pretty much any CSS property for any element.

jQuery helps us by making a lot of the complicated things in Javascript totally transparent, and although there is certainly merit in learning Javascript on it's own, for the purposes of this introductory course, we'll be using jQuery to facilitate our learning.

jQuery is a great tool but it does add quite a bit of size to a web page. The compressed library is 86kb, which might not seem like a lot, but every little bit counts when working on the web.

Some developers are moving away from jQuery (or trying to) either to other smaller libraries or to Vanilla JS, but the truth is jQuery is very very practical for a lot of reasons (in a large part the fact that it takes care of most of the browser compatibility issues with JavaScript).

CommitStrip jQuery

Getting started with a programming language

This is a quick introduction to how a programming language works. If you've already written a bit of script or computer programming, you can skip this section, and meet us down at 'Getting started with JavaScript'

For everyone else, this is going to be a quick overview of some of the key concepts in a programming language. Hold on, it's gonna be a quick tour...

Variables

Think back to when you learned algebra in School (yes, I know, don't be afraid it's OK really...).

Let's take a really simple example of a mathematical equation:

a + b = c

In Algebra we use letters to represent numbers, and we do an operation on them. In this case, we add a to b.

A variable in any programming language is like a letter in algebra - it stands for another value.

Take a look at the Javascript below:

var a = 12, b = 9; // In this line I set the values of a and b

var c = a + b; // In this line I set the value of `c` to that of `a` added to `b`

console.log(c); // This just output's the value of `c` to the console

What would be the value of c in this example? What would be logged to the console?

Variables are simply ways of holding and recalling information in the script.

We can use any keyword (except for a few reserved keywords in Javascript) to name the variable:

var foo = 12, bar = 9; 

var result = foo + bar; 

console.log(result); 

Usually we try to use something explicit and clear for the names of our variables, so that reading the code is easy.

Functions

Functions are a little more complex. Functions are like lists of instructions. in most languages functions are written like my_awesome_function(). The brackets at the end indicate 'this is a function'.

We can write functions by using the 'function' keyword and then call them as many times as we like.


// First we define the function 
function openAnnoyingAlert(){

  // everything we want to do has to be put inside the {} in the function

  console.log('I will now open an annoying alert');
  alert('This alert is very annoying');

}

// Now we call our function
openAnnoyingAlert();

Functions are very useful when we want to do the same action or process lots of times in different places.

We can also pass 'parameters' to the function. Parameters are values we put inside the () of the function (in a comma-seperated list if there are many) and they allow us to pass a variable to inside the function, and do something to it.

Take a look at the example below:


// First we define the function 
function openAnnoyingAlert( alertText ){

  // everything we want to do has to be put inside the {} in the function

  console.log('I will now open an annoying alert');
  alert( alertText );

}

// Now we call our function with our text as a parameter
openAnnoyingAlert("This alert is really annoying");

// We can call it a second time with different text
openAnnoyingAlert("This one is two");

What will this code do?

Types of variable

In most programming languages, variables have specific types. In the first example the variable was of type 'Integer' - a whole number.

Notice in the second example how the text we put inside the parameters was encapsulated with " ". This indicates that this variable is a string, that is a string of text.

Some other types of variable are:

  • float: a non-whole number like 1.45 or 3.1415651
  • boolean: a yes / no value which is always expressed as either true or false.
  • array: a list of other variables. This is written in Javascript as [ 'value1' , 'value2']
  • object: an object is a complicated kind of varibale to understand. We won't go into it in this class, but you can have a look at it in your own time if you want.

Control structures

Variables are our 'nouns', and functions are our 'verbs', then control structures are our 'conditionals'. They allow us to apply computer logic to our scripts and programs.

Take a look at the following function:


function testIfGreaterThan10( number ){

  if (number > 10) {
    console.log('This number is bigger than 10');
  } else {
    console.log('This number is smaller or equal to 10');
  }
}

testIfGreaterThan10( 5 );

What will this function print to the console?

if...else...

If / Else statements allow us to check a condition (in this case number > 10) and then perform an action if it is true, and something else if it is false.

The syntax in Javascript is a very common syntax (as above).

for

For loops are slightly more complicated. They allow us to repeat an action a certain number of times.


for (var i = 0; i < 5; i++) {
  console.log("I'm printing to console");
}

This loop will print to the console 5 times.

A for loop has 3 parts inside its bracket:

  • var i = 0: we set our counter variable (by convention called i) to 0.
  • i < 5: we set our loop condition. The loop will repeat as long as this condition is true, so for as long as i is less than 5.
  • i++: we give our loop an instruction to perform at the end of each 'loop'. The instruction here means 'increment i by 1'.

So the loop will run the actions given inside it until i is greater or equal to 5, and after each iteration it will increase i by 1. This means that it will run 5 times.

I made a video explaining this 'Getting to know programming lanugages' a little bit better, and to go over some of the more difficult concepts again!

Getting started with JavaScript and jQuery

Copy-paste the code below into a new HTML file a look at the code below:

<p class="my-p">This is my p</p>
<button id="my-button">
  This is my button.
</button>

Now at the bottom of the page, just before you close the body tag, add the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><script> 

jQuery(document).ready(function(){
  $('.my-p').hide();
})
</script>

The first part of this code loads the Google APIs version of the jQuery library.

The second script tag is where we can write our Javascript.

Just like CSS you can also include your JS in a .js file linked from an external place. For Javascript it's best to put your JS at the bottom of the page rather than the top. You can include it just as we did for the jQuery - with a script tag using the src=URL attribute.

What do you notice about the paragraph of your page?

What's happening here is that your jQuery is saying:

  • When the page is loaded and ready
  • Select the element with the class my-p
  • Hide it.

Try looking at the jQuery from the first part of this lesson, and change the color of the text to 'blue' using the .css() jQuery method.

It is pretty much always the best practice to put your jQuery inside the jQuery(document).ready(function(){ ... }) format. This is because if you execute your jQuery before your page is completely loaded it can cause visual or functional bugs.

Binding to events

So now, using the $('selector') syntax we can select any element just like we do using CSS with jQuery.

We can also use the 'css' method to change the CSS of a given element as soon as the page loads.

Do you remember before we saw that we used the .click() event handler to bind an event to the click action? This meant that every time that element was clicked, the function we bound would fire.

jQuery provides an easy way to access the native JavaScript events and event handlers. When we use an event handler, we tell JavaScript to fire an event every time a certain event happens.

Here are some common events that are useful for binding things in jQuery:

  • onclick - this allows us to fire some actions when an element is clicked in the browser.
  • onchange - this event is fired every time someone changes a form field or a dropdown 'select' menu element.
  • onsubmit - this event is fired when a form is submitted
  • onscroll - this event is fired on the JS window element when the user scrolls with his mouse or trackpad.

There are plenty more, you can check out the others here:

In jQuery you can bind to a lot of these events with some nice shortcut functions like .click() as we saw. .change() binds actions to the onchange event, etc.

Take a look at the example below


jQuery(document).ready(function(){
  $('.my-p').click(function(){
    alert('Don\'t click me!');
  });
});

What will happen when I click on p.my-p ?

NOTE Sometimes in this class I will leave out the jQuery(document).ready(function(){ ... }); part of the code, for brevity. But you should always wrap all your jQuery in like so:


jQuery(document).ready(function(){

  $('.my-p').click(function(){
    alert('Don\'t click me!');
  });

  // Some more code

  $('.my-div').click(function(){
    // Do something else
  });

});

Manipulating the DOM

The goal of using Javascript is to manipulate the DOM (or Document Object Model - basically the web page you see in your browser, all the HTML elements and CSS you can see).

Changing element CSS

We're already seen how we can use the .css() jQuery method to apply color to text. We can pass this element any css parameters we want.

$('.my-p').click(function(){
  $(this).css('padding-left', '10px');
});

In the above example do you see that instead of repeating $('.my-p') a second time, I can use the this keyword in Javascript (wrapped in the $() as with any other selector). this in jQuery refers to the current HTML. In this case it means the element that was 'clicked' because we're in the function 'click'.

this can be a bit confusing, but I'll try to use it to show you how it can work and explain it as we go.

Try using the code above to change the background-color of your .my-p, the text color, the font.

Now take a look at the element in the inspector in Chrome. Can you see in the HTML in the style= attribute that your changes have been applied by the browser?

Showing / Hiding elements

jQuery provides us with a few really nice functions to help us make short-cuts when we display / hide elements.

$('.my-p').click(function(){
  $(this).hide();
});

The above example will set the element to display: none;

$('.my-p').click(function(){
  $(this).show();
});

This will allow us to show the element.

Copy-paste the following HTML :

<p class="my-p">
  Lorem Elsass ipsum et sit nüdle Pellentesque Mauris barapli Carola Gal ! ac semper wie id, placerat tristique dui consectetur adipiscing kuglopf hopla schnaps leo non messti de Bischheim pellentesque sagittis libero, sit mänele jetz gehts los commodo Hans ftomi! sit non amet, hopla und s'guelt knack condimentum quam, Racing. senectus merci vielmols Verdammi so Morbi eleifend ante leverwurscht varius mollis rhoncus baeckeoffe hopla blottkopf, hoplageiss Richard Schirmeck Miss Dahlias amet in, Kabinetpapier bredele dolor Oberschaeffolsheim schneck salu DNA, morbi lacus auctor, Huguette Salut bisamme porta Strasbourg Spätzle libero, elementum Coopé de Truchtersheim météor ullamcorper knepfle gravida Christkindelsmärik Heineken lotto-owe leo ac gal sed geïz purus vielmols, ornare vulputate flammekueche Yo dû. Chulien hop eget bissame munster nullam id quam. Salu bissame gewurztraminer dignissim tellus ornare aliquam Wurschtsalad amet rossbolla Chulia Roberstau réchime kartoffelsalad yeuh. geht's schpeck turpis, rucksack Oberschaeffolsheim sed picon bière habitant Pfourtz ! Gal. kougelhopf ch'ai risus, tellus tchao bissame turpis elit suspendisse hopla mamsell wurscht libero. chambon .
</p>
<button class="my-button">
  Click to apply Javascript
</button>

Now in your JS :

$('.my-button').click(function(){
  $('.my-p').slideUp();
});

What does this Javascript do?

It has the same effect as .hide() but it has a nice slide-up effect.

To show the element you can use '.slideDown()' but the real trick here is to use .slideToggle(). This means 'if the object is up, slide down, if the object is already down, slide up'.

NOTE Javascript, like most programming languages, is case sensitive. That means .slideDown() and .slidedown() and .SlideDown() are not the same. You should use camelCase for your javascript functions and jQuery calls.

Lots of the functions in jQuery have 'toggle' versions. Try out:

  • .toggle()
  • .fadeToggle()
  • .toggleClass()

Adding removing classes

Although we saw how we can use the .css() method to apply CSS directly to the element, it's often more useful and better practice to define our styles in a class in our CSS, and then add/remove the class as necessary to our element via jQuery

$('.my-button').click(function(){
  $('.my-p').addClass('red');
});

Now add a class in your CSS

.red {
  color: red;
}

Try this out. What happens if you use 'toggleClass' instead of 'addClass'.

Changing element text

Another thing you might like to do it set content for any given event.

You can use the .text() jQuery method to set the text of an element. You should pass the text as a parameter to this function.

$('.my-button').click(function(){
  $('.my-p').text('New paragraph text');
});

Try it out!

Changing element HTML content

You can also change HTML content instead of just text using the .html() function. It works just like .text().

$('.my-button').click(function(){
  $('.my-p').html('<strong>This is some HTML content!</strong>');
});

As well as using .text() and .html() to set HTML and Text inside elements, we can also use them without a parameter to fetch the current text or HTML of an element.

$('.my-button').click(function(){
  var pText = $('.my-p').text();
  console.log('The text currently in this paragraph is: ' + pText);
});

Some more advanced examples

Here are some examples of jQuery using more advanced structures. All these structures and examples build on what we've seen above.

Using control structures with jQuery

Copy the HTML and try out the JS below:

<p class="my-p">
  Lorem Elsass ipsum et sit nüdle Pellentesque Mauris barapli Carola Gal ! ac semper wie id, placerat tristique dui consectetur adipiscing kuglopf hopla schnaps leo non messti de Bischheim pellentesque sagittis libero, sit mänele jetz gehts los commodo Hans ftomi! sit non amet, hopla und s'guelt knack condimentum quam, Racing. senectus merci vielmols Verdammi so Morbi eleifend ante leverwurscht varius mollis rhoncus baeckeoffe hopla blottkopf, hoplageiss Richard Schirmeck Miss Dahlias amet in, Kabinetpapier bredele dolor Oberschaeffolsheim schneck salu DNA, morbi lacus auctor, Huguette Salut bisamme porta Strasbourg Spätzle libero, elementum Coopé de Truchtersheim météor ullamcorper knepfle gravida Christkindelsmärik Heineken lotto-owe leo ac gal sed geïz purus vielmols, ornare vulputate flammekueche Yo dû. Chulien hop eget bissame munster nullam id quam. Salu bissame gewurztraminer dignissim tellus ornare aliquam Wurschtsalad amet rossbolla Chulia Roberstau réchime kartoffelsalad yeuh. geht's schpeck turpis, rucksack Oberschaeffolsheim sed picon bière habitant Pfourtz ! Gal. kougelhopf ch'ai risus, tellus tchao bissame turpis elit suspendisse hopla mamsell wurscht libero. chambon .
</p>
<select>
  <option>Choose a setting</option>
  <option value="yes">Activated</option>
  <option value="no">Deactivated</option>
</select>
<button class="my-button">
  Click to apply Javascript
</button>

jQuery(document).ready(function(){

  $('.my-button').click(function(){

    // read the value of the select. if it is set to 'yes' then continue
    if ($('select').val() == "yes") {
      $('.my-p').css('color', 'red');
    }
  });

});

This select means that the button will only work when the select is set to 'Activated'.

Notice two things:

  1. Firstly, the jQuery method .val() allows us to get the value of a form element. This might be a input at which point val() will return us the text entered into the field. Or it could be a select at which point it will return the value of the option currently selected.
  2. In the if the condition is not using = but ==. Using 1 = is used for setting the value of a variable. To test a value against another, we use ==. === is used to test the value and the type.

Processing data

We can also use JavaScript to, for example, validate the input fields in a form to check they are filled out.

<form class="form">
  <input class="name" name="name" type="text"> 
  <input class="address" name="address" type="text"> 
  <input class="age" name="age" type="number"> 
  <input type="submit" class="submit">
</form>

jQuery(document).ready(function(){

  $('.form').submit(function(){
    // We hook into the 'submit' event to check the form

    // Find all the inputs inside the form, 
    // except for the submit button, and 
    // for each of them run the function below:
    $(this).find('input').not('input[type=submit]').each(function(){
      if ($(this).val() == '') {
        // If this field is empty, alert user
        alert('The field '+$(this).attr('name')+ ' is empty!');
      }
    })

    // This trick stops the form from being submitted in the normal HTML way. 
    return false;
  });

});

Here we used a few new functions, the .find() jQuery function that finds children elements for the current element matching by the selector given, the .not() method which removes a given selector from the matched set of elements (in this case, we don't want to check the submit button), and the .attr() method which gets and sets any attributes on the HTML element selected.

Mainpulating strings

We can also use jQuery to do some string manipulation:

<form class="form">
  <input class="name" name="name" type="text"> 
  <input class="address" name="address" type="text"> 
  <input class="age" name="age" type="number"> 
  <input type="submit" class="submit">
</form>

<div class="my-list">

</div>

When we submit the form we'll add the information to the list:


jQuery(document).ready(function(){

  $('.form').submit(function(){
    // We hook into the 'submit' event to check the form

    // Create a new variable which will contain our text string
    var stringToAdd = '';

    // Create a variable to check if form has validated : 
    var formHasErrors = false;

    // Find all the inputs inside the form, 
    // except for the submit button, and 
    // for each of them run the function below:
    $(this).find('input').not('input[type=submit]').each(function(){
      if ($(this).val() == '') {
        // If this field is empty, alert user
        alert('The field '+$(this).attr('name')+ ' is empty!');
        formHasErrors = true;
      } else {
        // Take current string, add the new value, and set it to be the new string. 
        stringToAdd = stringToAdd + ' ' + $(this).val();

      }
    });

    if (formHasErrors == false) {
      $('.my-list').append(stringToAdd + '<br>');
    }

    // This trick stops the form from being submitted in the normal HTML way. 
    return false;
  });

});

Exercises

Ungraded Exercise : CSS manipulation

This is an ungraded exercise for practice only, you don't need to submit it for grading

Given the HTML file below, using jQuery

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript Exercise Base</title>
        <style>
        h3 {font-family: helvetica;}
        body {background-color: #ededed;}
        .main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
        .content {background-color: white; padding: 40px;}
        footer {text-align: center;}
        #output {background-color: #F2F5F1;}
        </style>
    </head>
    <body>
        <div class="main">
        <h2>Javascript Exercises</h2>
            <div class="content">
              <h3 class="sub-title">Make Placeholder Text Great Again!</h3>

              <p class="paragraph">Lorem Ipsum is the single greatest threat. We are not - we are not keeping up with other websites. He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured.</p>

              <p class="paragraph">An ‘extremely credible source’ has called my office and told me that Barack Obama’s placeholder text is a fraud. The other thing with Lorem Ipsum is that you have to take out its family. The other thing with Lorem Ipsum is that you have to take out its family.</p>

              <button class="my-button">Button</button>

            </div>

            <h4>Output</h4>

            <div id="output">

            </div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script> 

        jQuery(document).ready(function(){

        });

        </script>
    </body>
</html>
  1. Change the color of the text of the paragraphs to red
  2. Change the color of the <h3> heading to orange

  3. When I click the button, change the <h3> heading to italic.

  4. Add a CSS class which makes the paragraph text bold. When I click the button, toggle the bold text.

  5. Add a second button. When I click this button, toggle hide / show all the paragraphs and the sub-titles.

  6. Create a 3rd button. When I click on it, using the method .remove(), delete the paragraphs of text.

Ungraded Exercise : Processing Data

This is an ungraded exercise for practice only, you don't need to submit it for grading

Given the HTML file below:

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript Exercise Base</title>
        <style>
        h3 {font-family: helvetica;}
        body {background-color: #ededed;}
        .main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
        .content {background-color: white; padding: 40px;}
        footer {text-align: center;}
        #output {background-color: #F2F5F1;}
        .left, .right {
          float: left;
          width:  40%;
        }
        </style>
    </head>
    <body>
        <div class="main">
        <h2>Javascript Exercises</h2>
            <div class="content">
              <input type="text" class="my-input">

              <button class="set-button">Set</button>
              <button class="my-button">Add</button>

              <select>
                <option>Choose left or right</option>
                <option value="left">Left column</option>
                <option value="right">Right column</option>
              </select>

            </div>

            <h4>Output</h4>

            <div id="output"> 

            </div>

            <div class="left">

            </div>
            <div class="right">

            </div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script> 

        jQuery(document).ready(function(){

        });

        </script>
    </body>
</html>
  1. When I click on the button 'Set', read the text entered into the 'input' and log it to the console.

  2. When I click on the button 'Set', put whatever the 'input' text is to the div with id='output'.

  3. When I click on the button 'Add', add the content of the 'input' field to the div (that is, keep the previous content and add the input text). Don't replace the existing text.

  4. When I click on the button 'Add', read the current value of the 'select' and log it to the console.

  5. When I click on the button 'Add', add the current content of 'input' to the div 'left' if the select is set to left, or 'right' if the select is set to right.

Graded Exercise : Accordion

This is a GRADED EXERCISE. It is for practice, if you submit it you will get a grade and a comment. These DO NOT count towards your grade for this class

Given the following HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript Exercise Base</title>
        <style>
        h3 {font-family: helvetica;}
        body {background-color: #ededed;}
        .main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
        .content {background-color: white; padding: 40px;}
        footer {text-align: center;}
        #output {background-color: #F2F5F1;}
        .left, .right {
          float: left;
          width:  40%;
        }
        </style>
    </head>
    <body>
        <div class="main">
        <h2>Javascript Exercises</h2>
            <div class="content">

            </div>

        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script> 

        jQuery(document).ready(function(){

        });

        </script>
    </body>
</html>
  1. Using what you learned in the last two classes about CSS and HTML, create the following layout:

Blocks layout

Make sure there is:

  • A link over the Section titles set to '#'
  1. Set up the JavaScript so that when I click on the link, the content underneath the section header is toggled between hidden and shown. Hint You can use .toggle() or .slideToggle(), in combination with $(this) and .next() to select the next sibling element of the clicked element.

  2. Now modify the CSS so that the elements start by being hidden when the page is loaded.

  3. Now modify the JavaScript so that when I click on an un-opened section, it opens, and any other already-opened sections will close. Hint You can use .is(':visible') to check if an element is visible or not in the DOM. It returns a boolean (true or false).