CMPT 165

Introduction to the Internet
and the World Wide Web

By Hassan S. Shavarani

Unit4: Intro to JavaScript

Topics

  1. Programming and Web Pages
  2. JavaScript Basics
  3. Variables and Functions
  4. The jQuery Library
  5. Working with jQuery
  6. Events and Behaviour
  7. Why doesn't my code work?

Libraries in Programming


JavaScript is full-featured all by itself
but there are many tasks for which a lot needs to be done and are not in the core language

Common Attribute of Programming Languages

the language itself lets programmers solve problems,
but as the language is used, it becomes clear that some tasks must be done often
it would be inefficient for every programmer, or even each project/company to solve these problems separately !!!

developers often publish their solutions to frequently-encountered problems in code libraries (or just libraries)

Linking jQuery

immediately upon importing jquery-3.2.1.js, the variable jQuery will be accessible!

<head>
    <meta charset="UTF-8" />
    <title>Page with a style sheet</title>
    <script src="http://cmpt165.csil.sfu.ca/
                     js/jquery-3.2.1.js" />
</head>

let's take a look at an HTML page linked to jquery-3.2.1.js
containing an alert function call here

Let's get started with jQuery

setup = function() {
    all_paragraphs = jQuery('p')
    all_paragraphs.click(say_hello)
}
jquery_doc = jQuery(document)
jquery_doc.ready(setup)

The string "p" given to the jQuery function is a selector (or jQuery selector to be more specific)

jQuery selectors

designed to work like CSS selectors
because most developers already know
how to use CSS selectors

jQuery selectors vs. CSS Selectors

There are some differences between
CSS selectors and jQuery selectors
but for now you can safely assume they are the same

* The differences are mostly that jQuery extends things so you can specify things in jQuery that won't work in CSS, for more details look at here
After calling the jQuery selector, what it gives back is a jQuery object

Modifying the Page Example

p_click = function() {
    jQuery('#changeme').html('Somebody clicked me.')
}
h1_hover = function() {
    jQuery('#changeme').html('Mouse <em>over</em> the &lt;h1&gt;.')
}
setup = function() {
    jQuery('#changeme').click(p_click)
    jQuery('h1').mouseover(h1_hover)
}
jQuery(document).ready(setup)
* To try this code look at here

Events

An event in HTML is triggered by certain things that the user does, or that happens in the browser, lets look at some event categories:


* here we can see how to attach an event handler in JavaScript code
if not using jQuery event attaching mechanism
* here you can find a reference to the Event Object descriptions
Any Questions?