JavaScript

  • JS is another webpage element — beyond HTML/CSS — that can get sent to browser
  • You put it in a <script> tag, or you can call it from external file.
  • JS script tags usually go at the bottom of the page, just above </body>.
  • JS is about modifying behavior and handling interaction
  • JS relies heavily on the DOM -- which is the family tree of a webpage. Look at HTML through the Inspector to undertsand the hierarchy.

jQuery

  • jQuery is a framework to make it way easier to write JS. Like Bootstrap is a framework for HTML/CSS.
  • jQuery is a HUGE toolbox.
  • We're going to learn one tiny use case, which is more than enough to be dangerous

The power of nested CSS

  • By simply adding one class to one element, we can introduce almost any dynamic behavior we want by making heavy use of nested selectors.
  • We can write CSS rulesets that don't have any affect when the page is loaded, but become important once a single class is added somewhere on our page.
  • e.g. ul.active li img { border: 1px solid red; } will only work when the <ul> has a class of active.
  • jQuery gives us an easy way to add classes to elements when a particular interaction occurs.

Formulate interactions like this:

When ELEMENT gets INTERACTION, apply CLASS NAME to TARGET.

Some common interactions

Lots more listed in the jQuery API.

Mouse interactions

  • click
  • mouseover (hover)
  • mouseout (end hover)
  • hover (takes two functions: on hover start, on hover end)

Mouse interactions

  • focus (element gains focus)
  • blur (element leaves focus)
  • change (change text in an input)
  • select (select text in an input)
  • submit (submit a form)

Window interactions

  • scroll
  • resize

Keyboard interactions

  • keypress

jQuery boilerplate templates

Tips

  • Don't forget to include jQuery
  • You can include as many statements as you want inside the jQuery "ready" function. That is, in the example above, line 1 and 5 need to be there only once, and you can insert as many of lines 2-4 in there as you want.
  • You can also include as many class additions as you want inside the function for an interaction.
  • Instead of addClass, you may use removeClass or toggleClass.
  • Use this to refer to the element being interacted with.
  • You can include a comma-delited list to target more than one element.

Examples

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(function() {
  $('.my-button').click(function() {
    $('.big-box').addClass('blue');
  });

  $('.show-modal').click(function() {
    $('.screen').addClass('visible');
    $('.modal').addClass('visible');
  });

  $('input[type=text], input[type=textarea]').focus(function() {
    $(this).addClass('active');
  });
});
</script>