(4)jQuery & JSON

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

DOM nodes

In the HTML DOM (Document Object Model), everything is a node: The document itself is a document node. All HTML elements are element nodes. All HTML attributes are attribute nodes. Text inside HTML elements are text nodes.

evt.target

The evt.target property can be used to access just the clicked on element $( 'article' ).on( 'click', function( evt ) { console.log( evt ); }); *evt.target* $( 'article' ).on( 'click', function( evt ) { $( evt.target ).css( 'background', 'red' ); });

event.type

to find what event happened - useful if listening to a target for multiple events

event.pageX and event.pageY

to know where on the page the click occurred - helpful for analytics tracking

Example of adding

var family1, family2, bruce, madison, hunter; family1 = $("#family1"); family2 = $("<div id='family2'><h1>Family 2</h1></div>"); bruce = $("<div id='bruce'><h2>Bruce</h2></div>"); madison = $("<div id='madison'><h2>Madison</h2></div>"); hunter = $("<div id='hunter'><h2>Hunter</h2></div>"); family2.insertAfter(family1); family2.append(bruce); bruce.append(madison); bruce.append(hunter);

variables in jQuery

var lucky = 7; var name = "Codecademy"; var $p = $('p'); // stores the result of a jQuery selector $('p') in the variable $p .

evt.preventDefault()

line instructs the browser not to perform the default action anchor link $( '#myAnchor' ).on( 'click', function( evt ) { console.log( 'You clicked a link!' ); }); *preventDefault()* $( '#myAnchor' ).on( 'click', function( evt ) { evt.preventDefault(); console.log( 'You clicked a link!' ); });

using two element selectors EXAMPLE click a button and make other elements do something

$(document).ready(function() { $('button').click(function() { $('.vanish').fadeOut('slow'); }); });

calling jQuery in script.js file *document ready*

$(document).ready(function() { jQuery magic; }); $(document).ready(function() { $('item').eventHandler(); });

click event handler EXAMPLE

$(document).ready() { $("#getMessage").on("click", function(){ // message goes here }); } *When our click event happens, we can use jQuery to update an HTML element *SCRIPT* $(document).ready(function() { $("#getMessage").on("click", function(){ *$(".message").html("Here is the message");* }); }); *HTML* <div class="container-fluid"> <div class = "row text-center"> <h2>Cat Photo Finder</h2> </div> <div class = "row text-center"> <div class = "col-xs-12 well message"> The message will go here </div> </div> <div class = "row text-center"> <div class = "col-xs-12"> <button id = "getMessage" class = "btn btn-primary"> Get Message </button> </div> </div> </div>

using keyword this in jQuery EXAMPLE

$(document).ready(function() { $('div').click(function() { $(this).fadeOut('slow'); }); }); // Instead of using fadeOut() on all 'div's, we're just using it on this div, where this refers to the div you're clicking on.

some jQuery function mouseenter() -- when the mouse hovers over element fadeTo() -- fades the element at some speed to some opacity fadeIn() hide() -- makes element disappear mouseleave() -- when mouse leaves element

$(document).ready(function() { $('div').mouseenter(function() { $('div').fadeTo('fast', 1); }); $('div').mouseleave(function() { $('div').fadeTo('fast', 0.5); }); });

using variables EXAMPLE set a var for target that targets the 4th element of a li

$(document).ready(function() { var $target = $('li:nth-child(4)'); $target.fadeOut('fast'); });

$p versus $('p')

$p is just a variable name. "hey, this variable contains a jQuery object." We could call $p anything we want: $paragraph, paragraph. It's just helpful for people reading our code to see $p, since this is a concise way of saying "hey, there's a 'p' jQuery object in here." $(), on the other hand, is magic. This is the function in disguise that creates jQuery objects. If you're making a jQuery object, you gotta use it!

selectors in jQuery *!!*

*Anything you can target with CSS, you can modify with jQuery.*

monitorEvents(elementToWatch);

*Use only in Chrome Dev Tools* If you use it in the JavaScript file, it will cause a reference error.

.appendTo()

appendTo() that allows you to select HTML elements and append them to another element. *Note: it's removed from original and moved to new element $("#target2").appendTo("#right-well");

Adding child elements

.append() .preprend()

.html()

.html() that lets you add HTML tags and text within an element $("#target4").html("<em>#target4</em>");

Adding sibling elements

.insertBefore() .insertAfter()

.remove()

.remove() that will remove an HTML element entirely $("#target1").remove();

how is jQuery included in a page

<script></script> - local - jQuery official - CND (content delivery network, like Google) recommend CDNs and use minified version min.js

how to monitor

1. target element to listen to ^^.on() 2. event we want to react to ^^ function 3. actions to take in response e.g. $('#my-input').on('keypress', function() { console.log('The event happened'); }); e.g. $('#my-input').on('keypress', function() { $('body').css('background-color', '#222fff'); }) e.g. $('#my-button').on('click', function() { $('#mybutton').remove(); $('body').addClass('success'); });

Convert JSON Data to HTML Now that we're getting data from a JSON API, let's display it in our HTML with a .forEach() loop. First, let's declare an html variable with var html = "";. Then, let's loop through our JSON, adding more HTML to that variable. When the loop is finished, we'll render it. --- from example "event click handler"

<script> $(document).ready(function() { $("#getMessage").on("click", function() { $.getJSON("/json/cats.json", function(json) { var html = ""; *json.forEach(function(val) { var keys = Object.keys(val); html += "<div class = 'cat'>"; keys.forEach(function(key) { html += "<strong>" + key + "</strong>: " + val[key] + "<br>"; }); html += "</div><br>"; });* $(".message").html(html); }); }); }); </script>

Prefilter JSON If we don't want to render every cat photo we get from our Free Code Camp's Cat Photo JSON API, we can pre-filter the json before we loop through it. --- from example "event click handler"

<script> $(document).ready(function() { $("#getMessage").on("click", function() { $.getJSON("/json/cats.json", function(json) { var html = ""; *json = json.filter(function(val) { return (val.id !== 1); });* json.forEach(function(val) { html += "<div class = 'cat'>" html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>" html += "</div>" }); $(".message").html(html); }); }); }); </script>

Render Images from Data Sources We've seen from the last two lessons that each object in our JSON array contains an imageLink key with a value that is the URL of a cat's image. When we're looping through these objects, let's use this imageLink property to display this image in an img element. --- from example "event click handler"

<script> $(document).ready(function() { $("#getMessage").on("click", function() { $.getJSON("/json/cats.json", function(json) { var html = ""; json.forEach(function(val) { html += "<div class = 'cat'>"; *html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";* html += "</div>"; }); $(".message").html(html); }); }); }); </script>

Get Geolocation Data Another cool thing we can do is access our user's current location: longitude and latitude.

<script> *if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $("#data").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude); }); }* </script> <div id = "data"> <h4>You are here:</h4> </div>

function someFunction() { // Do interesting things } $(someFunction) or $(function(){ // Do interesting things })

A function passed into the jQuery object runs on document.ready, which occurs after the DOM has been loaded. If you include your script in the <head> normally, it will run as soon as it's downloaded, which will occur before the DOM has built the elements you want your script to run against. So your script wouldn't be able to do anything. You could include your script at the bottom of the <body>, but that would mean that the download could potentially start later in the load process, slowing down the initial page render. Pass your function into the jQuery object. Now, you can include your script in the <head> and it won't run until the DOM has been built and the elements that you want to manipulate are on the page. http://api.jquery.com/jquery/#jQuery3

event delegation

But what about when the target doesn't exist yet? We'll listen to events that hit a parent element, and pay attention to the target of those events. Event Delegation with jQuery uses the same code we've been using, but passes an additional argument to the "on" method. e.g. watch container element for clicks, check if click event's target is an article element $( '.container' ).on( 'click', 'article', function() { ... }); e.g. listen to one element ul#room and check if target element is a list item $( '#rooms' ).on( 'click', 'li', function() { ... });

event.key

Code to learn what key was pressed - invaluable if you need to listen for a specific key

target an element in the DOM in your script file

DOM element $("div").fadeOut(1000); Element ID $('#green').fadeOut(1000); Element Class $('.button').someAction

linking jQuery script - error $ is not defined

I moved the jQuery CDN link above the script.js file and it worked. e.g. <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript" src="script.js"></script> </head>

*JQUERY*

JavaScript library - understand how the library is built - jQuery selectors - DOM navigation methods

What is jQuery?

a function and an object because in JS a function = an object not a language

JSON

Most web APIs transfer data in a format called JSON. JSON stands for JavaScript Object Notation. JSON is nothing more than object properties and their current values, sandwiched between a { and a }. (You've already been using JSON whenever you create a JavaScript object.) These properties and their values are often referred to as "key-value pairs".

jQuery activity - passing a function to a function

One of the nice things about jQuery is that you can give a function just about anything as an input—even another function! On Click, Fade Out $(document).ready(function() { $('div').click(function() { $('div').fadeOut('slow'); }); });

The Convenience Methods http://api.jquery.com/category/events/

Shortcut codes e.g. $('#my-input').keypress (function() { console.log('The event happened'); }); *eliminates .on()

REMEMBER!

Start with the function keyword Inputs go between () Actions go between {} Inputs are separated by commas. Inputs can include other functions!

keyword 'this' in jQuery

The this keyword refers to the jQuery object you're currently doing something with. Its complete rules are a little tricky, but *the important thing to understand is if you use an event handler on an element—that's the fancy name for actions like .click() and .mouseenter(), since they handle jQuery events—you can call the actual event that occurs (such as fadeOut()) on $(this), and the event will only affect the element you're currently doing something with (for example, clicking on or mousing over).*

e, evt, event

The target element calls the callback function when the event occurs. When this function is called, jQuery passes an event object to it containing information about the event. This object holds a ton of useful information that can be used in the body of the function. This object, which is usually referenced in JavaScript as e, evt, or event, has several properties that you can use to determine the flow of your code.

.prop()

allows you to change the properties of an element (HTML) $("#target1").prop("disabled", "true");

.target:odd selector .target:even .

You can also target all the even-numbered or odd-numbers elements $(".target:odd").addClass("animated shake");

$ (jQuery) & how to use the $ (jQuery)

a character that is a pointer to what you typed before (???) it's just a function (???) $ ===> jQuery collection - an array-like object (like an array with additional methods) additional methods e.g. - pass strings $(string) - pass functions $(function) - DOM element $(DOM element) $ - the dollar sign operator, also called a bling jQuery starts all functions with it

Finding DOM elements for article-list class all siblings of h1 all kids of article list all parents of article list that are divs

articlelist = $(".article-list"); h1 = articlelist.siblings("h1"); kids = articlelist.find("*"); parents = articlelist.parents("div"); universal selector = *

.children()

children() that allows you to access the children of whichever element you've selected $("#right-well").children().css("color", "orange");

.clone() (with .appendTo() creates a copy a copy and moves it)

clone() that makes a copy of an element $("#target5").clone().appendTo("#left-well");

selecting by traversing the DOM

e.g. $("#Name).parent() $("#Name).parent(#NameParents) $("#Name).parents() ^^ parents, grandparents, greatgrandparents $("#Name).children() $("#Name).find() ^^children, grandchildren, etc. $("#Name).siblings() ^^have same parents

jQueries methods patterns

e.g. attributes > modifies HTML attributes like class ( something ) > tells what to pass in ([ optional_parameter]) > means optional to include

What are browser events?

e.g. link clicks fill out form

vanilla JS manipulating the DOM

e.g. inserting a new DOM node 1. create an element 2. set attributes and content of the new node 3. select the soon-to-be parent of the new node 4. insert the new node as a child of the parent node

jQuery manipulating the DOM

e.g. inserting a new DOM node 1. one function that includes all the JS steps

.each()

function numberAdder() { var text, number; text = $(this).text(); number = text.length; $(this).text(text + " " + number); } $('p').each(numberAdder);

Ajax

how to update HTML with the data we get from these APIs using a technology called Ajax

jQuery API documentation

http://api.jquery.com/

event types

https://developer.mozilla.org/en-US/docs/Web/Events#Categories

targeting HTML elements

jQuery can target the body element as well. $("body").addClass("animated fadeOut"); $("body").addClass("animated hinge");

select by tags/ classes/ ids selectors (jQuery)

jQuery object $ selector ("") $("tag") $(".class") $("#id") *can use apostrophe rather than quotation mark selectors http://api.jquery.com/category/selectors/

.target:nth-child(n) selector

jQuery uses CSS Selectors to target elements. target:nth-child(n) css selector allows you to select all the nth elements with the target class or element type $(".target:nth-child(3)").addClass("animated bounce");

.parent()

parent() that allows you to access the parent of whichever element you've selected $("#target1").parent().css("background-color", "red");

DOM traversal methods

provided by jQuery to move around the DOM tree

$(document).ready()

runs such that all of the code inside of it executes only once our page has finished loading

Get JSON with the jQuery getJSON Method *Once you've added this, click the "Get Message" button. Your Ajax function will replace the "The message will go here" text with the raw JSON output from the Free Code Camp Cat Photo API. --- from example "event click handler"

script> $(document).ready(function() { $("#getMessage").on("click", function(){ *$.getJSON("/json/cats.json", function(json) { $(".message").html(JSON.stringify(json)); });* }); });

compound selector

select 2+ elements $('p, li').fadeTo('slow', 0);

APIs - or Application Programming Interfaces

tools that computers use to communicate with one another

monitorEvents($0); unmonitorEvents($0);

tracks mouse movement

.attr() .first()

var navList, firstItem, link; navList = $(".nav-list"); firstItem = navList.children().first(); link = firstItem.find("a"); link.attr("href", "#1"); CAN'T THIS BE SHORTENED?


संबंधित स्टडी सेट्स

Inleiding in de Psychologie Gray&Bjorklund Deel 11 Hoofdstuk 9-17

View Set

Pharm Made Easy: Reproductive & Genitourinary System

View Set

Life in Modern Britain- Citizenship GCSE

View Set