Skip to content

Instantly share code, notes, and snippets.

@jennli
Last active February 25, 2016 23:12
Show Gist options
  • Save jennli/6f54618973d42685534c to your computer and use it in GitHub Desktop.
Save jennli/6f54618973d42685534c to your computer and use it in GitHub Desktop.

JQuery

  • makes managing DOM easier
  1. select elements
  2. manipulate selected elements
  3. add even listeners to selected elements
$('img').hide();
$('a').on('click', function(){console.log('that tickles')});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My First jQuery Page</title>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        $("h1").html("Welcome to jQuery");
      });

    </script>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
  </head>

  <body>
      <h1>Welcome to My HTML Page</h1>

  </body>
</html>

Elements, attributes, contents, id, class

<div id="my-div" class="my-class" width="50">

selector

  • jQuery selectors are just CSS selectors

css selectors

  1. tagName
  2. .class
  3. #id
  4. ancestor descendant
  5. selector1, selector2,
  6. img
  7. img.large
  8. #reset-button
  9. ul#homework li
  10. img, a
  11. #reset-button, #bublish-button

$

  • this '$' is a normal function that takes a string as an argument.
  • the argument should be a css selector
var $ = function(name) {console.log("hello " + name);};
  • it returns a wrapped set

Exercise

  • select all black shapes
$(".black.shape")
[<div class="small black square shape"></div>, 
<div class="medium black square shape"></div>, 
<div class="medium black square shape"></div>, 
<div class="medium black square shape"></div>]
$(".shape").length
  • count number of shapes
$(".shape").length
16

attr

  • get value of src attribute
$('img').attr('src');
  • set the value of src attribute
$('img').attr('src', 'www.google.com/logo.png');

Manipulation

$('.container').html();
$('.container').html('new html code');

Traverse

  • parent
$('#link-a').parent();
  • children
//select all the shapes in the purple container using 'children'
  $('#purple-container').children('.shape');

hide and show

$('a').hide();
$('a').show();

Mouse Event handler

  • most common events: 'click', 'mouseenter', 'mouseleave'
$('selector').on('event', function(){})
  • exercise
$('.shape').on('click', function(){console.log('shape is clicked')});
$('.blue.circle').on('mouseenter', function(){console.log('blueshape go away!')});
$('.blue.circle').off('mouseenter', function(){console.log('blueshape go away!')});
$('.blue.shape').on('mouseleave', function(){console.log('blueshape goodbye!')});
$('tr').on('mouseenter', function(){$(this).attr('class', 'highlight')})
$('tr').on('mouseleave', function(){$(this).attr('class', 'highlight')})

Document ready

  • script will get loaded before loading every other elements in the page is loaded.
  • In order for the script to work on all elements on the document, use the document.ready to wrap around all jquery scripts
$(document).on('ready', function() {}

More Selectors

Attribute selectors

  • strictly euqal
$('a[href="http://www.facebook.com"]')
  • partially matching
$('a[href*=".com"]').attr('class', 'highlight')
  • not equal
$('a[href!="http://www.google.com"]').hide();

Pseudo Selectors

:first-child

$('tbody > :first-child')
$('tr':first-child)

:last-child

$('tbody > :last-child')

:even

  • jquery starts counting from 0, so even will include the 1st, 3rd, 5th element
$('#green-container .shape:even').remove()

:odd

$('tr:odd').attr('class', 'highlight')

Attributes - working with class

  • add class to a given attribute
$('a').addClass('highlight')
  • remove class
$('a').removeClass('highlight')
  • toggle class (add or remove)
$('a').removeClass('highlight')
  • hasClass
$('body').addClass('my-own-class')
[<body class="my-own-class">​…​</body>]
$('body').hasClass('my-own-class')
true
  • $(this).children
$('.container').on('click', function(){$(this).children('.shape').addClass('highlight')})
  • Shrink Ray
$('.shape').on('click', function(){ 
if($(this).hasClass('small')){
  $(this).hide();
  } 
else if($(this).hasClass('medium')){
  $(this).removeClass('medium'); 
  $(this).addClass('small');
  } 
else if($(this).hasClass('large')){
  $(this).removeClass('large'); 
  $(this).addClass('medium');
  } 
});

val

  • dynamically get the value in a form
$("input[type='text']").val()
$('input[type="submit"]').on('click', function(){
  $('#form-message').html($('input[type="text"]').val());  
});

append and prepend

  • append add to the end of the very last element
  • prepend add to the beginning of the first element
$('body').append("<p>Hello World</p>")
$('input[type="submit"]').on('click', function(){ 
    $('#form-message').append($('input[type="text"]').val()); })
$('tbody').prepend('<tr><td>0</td><td>-</td></tr>')

find, prev, next

  • find
$('#orange-container').find('.red.shape');
$('#green-container').find('.circle').addClass('black');
  • prev
$('.small.red.circle').prev('.shape').remove();
  • next
$('.grey.shape').next('.shape').hide();

Effects: toggle, fadeOut, fadeIn, slideUp, slideDown

  • toggle
$('#button-1').on('click', function() { $('#green-container').toggle(5000); })
[<button id="button-1" class="button">​Button 1​</button>]
  • fadeOut
$('#button-2').on('click', function() { $('#button-message').fadeOut(5000); })
  • fadeIn
$('#button-3').on('click', function() { $('#button-message').fadeIn(5000); })
  • slideUp
$('#button-4').on('click', function() { $('#green-container').slideUp(5000); })
  • slideDown
$('#button-4').on('click', function() { $('#green-container').slideDown(5000); })

Keypress Event

  • key press
$(document).on('keypress', function(event){
  var charcode = event.which;
  var key = String.fromCharCode(charcode);
  console.log('key ' + key + ' was pressed');
  })
$(document).on('keypress', function(event){
  var charcode = event.which;
  var key = String.fromCharCode(charcode);
  if (key === "b"){ $('.blue.shape').toggle(1000); }
  })
  • keyup
$('input[type="text"]').on('keyup', function(event){
  $('#form-message').html(14 - ($(this).val().split('').length) + " chars remaining");
})
  • keydown

submit event

  $("form").on("submit", function(){
     var color = $("input[type = 'text']").val();
     var validColors = ["red", "grey", "blue", "green", "black"];
     if(!validColors.includes(color)) {
       alert("invalid color");
      // console.log(color);

     } else {
       $("." + color).remove();
      // console.log(color);
       var color = $("input[type = 'text']").val("");
     }
   });

Event bubbling

  • click on a child element will bubble up all the way to the document
  • can use
event.stopPopagation();

Default actions

  • override default actions
event.preventDefault();
  • return false will do both preventDefault and stop propagation

Delegated event

  • listner does not get added to newly added elements
$('.container').on('click', '.shape', function(){...});
  • useful for dealing with AJAX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment