lmari’s blog

Data analytics, machine learning & front end development

jQuery

f:id:lmari:20190518152315j:plain

jQuery

  • Prerequisite: HTML, CSS3 (use same selectors, id, class), JavaScript
  • DOM manipulation, Ajax (low, get, post)
  • Download jQuery 3.4.1-  https://jquery.com/download/
  • CDN without Internet, build simple UI
  • Use selectors to grab headings. $ represents jQuery. Dot . represent class
  • Github Notes

Index.html

<title>jQuery Crash Course</title>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<style>

body{

font-size:17px;

font family: arial;

background: #f4f4f4;

line-height: 1.5em;

}

header {

background:#333;

color:#fff;

padding:20px;

text-align: center;

border bottom: 4px #000 solid;

margin-bottom: 10px;

}

#container{

width:90%;

margin:auto;

padding:10px;

}

</style>

<div id="container>

<h1 id="heading1">Heading One</h1>

<p id="para1">Here we have only two switched reference voltages: 0 and 1.0000. (As we shall show later, we can tweak the high end even if this voltage is not precise.) <span>Here we have added a number of flip-flops such as CMOS types 4013</span> (which come two to a chip). </p>

<h1 class"heading2">Heading Two</h1>

<p class="para2">Insipidity the sufficient discretion imprudence resolution sir him decisively. Proceed how any engaged visitor. Explained propriety off out perpetual his you. Feel sold off felt nay rose met you. </p>

<ul id="list">

<li>List item</li>

<li>List item</li>

<li>List item</li>

</ul>

<input type= "button" value="Button 1">

<input type= "submit" value="Button 2">

<input type= "text">

<a href="http://google.com">Google</a>

<a href="http://yahoo.com">Yahoo</a>

</div>

<script>

$('h1').hide();

</script>

 

1. Selectors

Insert between <script></script> mauve

 

Hide entire Heading One paragraph from HTML

$('h1').hide();

 

Hide only the text "Heading One" from HTML 

$('h1#heading1').hide(); 

 

$('.heading2').hide();

 

Change contents inside <span></span> into red. Has to be within <p></p> to work

$('p span').css('color', 'red');

 

Turn all text inside <span></span> red

$('span').css('color', 'red');

 

Turn first listed item yellow

$('ul#list li':first').css('color', 'yellow');

 

Turn alternate rows gray

$('ul#list li':even').css('background-color', #cccccc');

 

Remove item dot on rows

$('ul#list li:nth-child(3n)').css('list-style', 'none');

 

Hide all buttons

$('button').hide();

 

Hide submit button

$(':submit').hide();

 

Target attributes. Turn all links to red

$('[href]').css('color', 'red');

 

Target attribute values. Turn yahoo link green

$('a[href="http://yahoo.com"]').css('color','green');

 

Hide everything in page

$('*').hide();

 

 

2. Events

  • Shows pop up window with command
  • Put bold command into script
  • Same effect -----> $('#btn1').on('click', function(){alert('Button Clicked!');

<div id="container">

<h3>Mouse Events</h3>

<button id="btn1">Button 1</button>

<button id="btn2"></button>

<p class="para1"></p>

<h1 id="coords"></h1>

<hr>

<form id="form">

<label>Name</label><br>

<input type="text" id="name" name="name">

<br>

<label>Email</label><br>

<input type="text" id="email" name="email">

<br>

<label>Gender</label><br>

<select id="gender" name="gender">

<option value="male">Male</option>

<option value="female">Female</option>

</select>

<br>

<input type="submit" value="Submit">

</form>

<script>

$('#btn1').click(function(){alert('Button Clicked!');});</script>

<title>jQuery Crash Course</title>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

$(document).ready(function(){put command above here});

 

Click button 1, hide the paragraph text

$('#btn1').on('click', function(){$('.para1').hide();

 

Click button 2, show hidden paragraph text

$('#btn2').on('click', function(){$('.para1').show();

 

Button 1 both show and hidden

$('#btn1').on('click', function(){$('.para1').toggle();

 

Double click toggle

$('#btn1').dbclick(function(){$('.para1').toggle();

 

Hover

$('#btn1').hover(function(){$('.para1').toggle();

 

is actually short hand for:

 

$('#btn1').on('mouseenter', function(){$('.para1').toggle();

$('#btn1').on('mouseleave', function(){$('.para1').toggle();

 

Other commands

mousemove

mousedown

mouseup

 

Optional parameter. Gives information

$('#btn1').click(function(e){alert(e.currentTarget.id);

 

See mouse coordinates as mouse move. Interactive applications

$('document).on('mousemove', function(e){$('#coords').html('Coords: Y: ' +e.clientY+" X: "+e.clientX);

 

Change form color with mouseover

$('input').focus(function(){$(this).css('background', 'pink');});

$('input').blur(function(){$(this).css('background', 'white');});

 

Key in, key out

$('input').keyup(function(e){console.log(e.target.value);

 

$('select#gender').change(function(e){alert(e.target.value);}); -----> $('select#gender').change(function(){alert('Changed');});

 

Submitted form

$('#form').submit(function(e){

e.preventDefault();

console.log('Submitted');

 

3. DOM Manipulation

  • Document Object Model, logical structure of documents and the way a document is accessed and manipulated
  • Application programming interface (API) for HTML and XML documents
  • DOM representation 

f:id:lmari:20190518152345g:plain

 

<header> <h1>jQuery Crash Course | DOM Manipulation</h1> </header>

       <div id="container">

<button id="btn1">Button 1</button>

<p class="para1">This is a paragraph</p>

<p class="para2">This is another paragraph</p>

<div id="myDiv"></div>

<input type="text" id="newItem">

<ul id="list">

<li>List Item 1</li>

<li>List Item 2</li>

<li>List Item 3</li>

<li>List Item 4</li>

</ul>

<a href="http://google.com">Google</a>

<ul id="users"></ul>

</div>

 

<script>

$(document).ready(function(){

$('#newItem').keyup(function(e){

var code = e.which;

if(code == 13){

e.preventDefault();

$('ul').append('<li>'+e.target.value+'</li>');

}

});

 

 

});

});

</script>

 

Red font on paragraph 1

$('p.para1').css('color', 'red');

 

Red font with gray background on paragraph 1

$('p.para1').css({color:'red',background:'#ccc'});

 

Apply class inside defined in <style> tag

$('p.para2').addClass('myClass');

 

$('p.para2').removeClass('myClass');

 

Toggle class with push of button 1

$('#btn1').click(function(){

$('p.para2').toggleClass('myClass');

});

 

Add text below (and) change to larger font in myDiv

$('#myDiv').text('Hello World');

$('#myDiv').html('<h3>Hello World</h3>');

 

Pop up Hello World

alert($('#myDiv').text());

 

Add item to the end of list (or beginning of list)

$('ul').append('<li>Append List Item</li>');

$('ul').prepend('<li>Prepend List Item</li>');

 

Append: Paragraph 2 move above paragraph 1

$('.para1').appendTo('.para2');

$('.para1').prependTo('.para2');

 

Before (or after) ul, not as listed item

$('ul').before('<h4>Hello</h4>');

$('ul').after('<h4>World</h4>');

 f:id:lmari:20190518152408j:plain

 

Empty takes all inner element (ul) out in between

$('ul').empty();

 

Detach takes inner element away and detach from the DOM

$('ul').detach();

 

Open new browser in google link

$('a').attr('target', '_blank');

 

Pop up with 'google.com'

alert($('a').attr('href'));

 

Link in same window, attribute gone

$('a').removeAttr('target');

 

Put paragrapghs in <h1>. Tip: No need to put </h1> tag

$('p').wrap('<h1>');

$('p').wrapAll('<h1>');

 

e.which get keyup value. Keep adding to list. Reload will disappear

$('#newItem').keyup(function(e){

var code = e.which;

if(code == 13){

e.preventDefault();

$('ul').append('<li>'+e.target.value+'</li>');

 

Display listed item below

var myArr = ['Brad', 'Kelley', 'Nate', 'Jose'];

$.each(myArr, function(i, val){

$('#users').append('<li>'+val+'</li>');

});

 

List item in console

var newArr = $('ul#list li').toArray();

$.each(newArr, function(i, val){

console.log(val.innerHTML);

 

4. Effect & Animation

<header>

<h1>jQuery Crash Course | Effects & Animate</h1>

</header>

<div id="container">

<button id="btnFadeOut">Fade Out</button>

<button id="btnFadeIn">Fade In</button>

<button id="btnFadeTog">Fade Toggle</button>

<hr>

<button id="btnSlideUp">Slide Up</button>

<button id="btnSlideDown">SlideDown</button>

<button id="btnSlideTog">Slide Toggle</button>

<button id="btnStop">Stop</button>

<hr>

<div id="box"><h1>Hello World</h1></div>

<hr>

<button id="moveLeft">Move Left</button>

<button id="moveRight">Move Right</button>

<button id="moveAround">Move Around</button>

<div id="box2"></div>

</div>

<script>

$(document).ready(function(){

$('#btnFadeOut').click(function(){

$('#box').fadeOut(3000, function(){

$('#btnFadeOut').text('Its Gone');

});

});

</script>

 

Fade out slowly

$('#box').fadeOut('slow');

 

3000ms = 3 seconds to fade out

$('#box').fadeOut(3000);

 

Button text changed to 'Its Gone'

$('#btnFadeOut').text('Its Gone');

 

Fade out. Click Fade in comes back in

$('#btnFadeIn').click(function(){

$('#box').fadeIn(3000); });

 

Fade Toggle button keeps fading in and out

$('#btnFadeTog').click(function(){

$('#box').fadeToggle(1000);});

 

Slide up and down

$('#btnSlideDown').click(function(){

$('#box').slideDown(3000); });

 

$('#btnSlideUp').click(function(){

$('#box').slideUp(3000);});

 

$('#btnSlideTog').click(function(){

$('#box').slideToggle(3000); });

 

Stop button can stop action

$('#btnStop').click(function(){

$('#box').stop(); });

 

Red box 2 apply animate. Make sure box2 position is relative in <style> 

 

  • MoveRight means move left
  • Bigger and more transparent when clicked move right

 

$('#moveRight').click(function(){

$('#box2').animate({

left: 500,

height: '300px',

width:'300px',

opacity: '0.5'

});

});

 

$('#moveLeft').click(function(){

$('#box2').animate({

left: 0,

height: '100px',

width: '100px',

opacity:'1'

});

});

 

Red box moves around in a square

$('#moveAround').click(function(){

var box = $('#box2');

box.animate({

left: 300

});

box.animate({

top: 300

});

box.animate({

left:0,

top: 300

});

box.animate({

left: 0,

top:0

});

    });

});

 

5. Ajax

  • Asynchronous JavaScript and XML
  • Web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page
  • Use JSON instead of XML (eXtensible Markup Language)

install node.js

npm install live-server -g

  • NPM live-server
  • -g means global, access from everywhere
  • Problems with chrome if not installed

 

Check version

node -v

npm -v

 

Navigate to location of index.html

 

RUN live-server --port=8000

127.0.0.1:8000

<header>

<h1>jQuery Crash Course | Ajax</h1>

</header>

<div id="container">

<div id="result"></div>

<ul id="users"></ul>

<h3>Add Post</h3>

<form id="postForm" action="https://jsonplaceholder.typicode.com/posts">

<input type="text" id="title" placeholder="Title"><br>

<textarea placeholder="Body" id="body"></textarea><br>

<input type="submit" value="Submit">

</form>

</div>

Load method: Load test.html in same directory 


$(document).ready(function(){

$('#result').html(data);

});


Then pop up window to say 'it went fine' or point out error

$(document).ready(function(){

$('#result').load('test.html', function(responseTxt, statusTxt, xhr){

if(statusTxt == "success"){

alert('It went fine.');

} elseif (statusTxt == "error"){

alert("Error: "+xhr.statusText);

}

});

 

Get method

$.get('test.html', function(data){

$('#result').html(data);

}

 

Get json file users.json, put as listed items

$.getJSON('users.json', function(data){

$.each(data, function(i, user){

$('ul#users').append('<li>'+user.firstName+'</li>');

   });

});

 

Sample json codes at jsonplaceholder.typicode.com/posts

 

Ajax method is most flexible. Default method is GET

$.ajax({

    method:'GET',

    url: 'https://jsonplaceholder.typicode.com/posts',

    dataType: 'json'

}).done(function(data){

    console.log(data);

    $.map(data, function(post, i){

          $('#result').append('<h3>' + post.title+'</h3><p>'+post.body+'</p>');

      });

});

 

Add Post request

$('#postForm').submit(function(e){

e.preventDefault();

var title = $('#title').val();

var body = $('#body').val();

var url = $(this).attr('action');

$.post(url, {title:title, body:body}).done(function(data){

console.log('Post Saved');

console.log(data);

});

});