JQuery

From Wiki
Jump to navigation Jump to search

http://learn.jquery.com/

Selectors

  • type: $('table')
  • attribute: $('[date="2015-04-21"]')
  • class: $('.even')
  • id: $('#main')

Filters

  • $('tr:eq(0)') finds the first row in a table
  • $('tr:gt(0)') finds all rows after the first
  • :even finds all even-numbered elements in a selection
  • :odd odd-numbered elements
  • :last last element
  • :empty elements that have no children
  • :focus the focused element
  • :not(selection) elements that don't match selection
  • :contains(text) element that contain certain text
  • input field selectors: :hidden, :text, :checkbox, :password

Combinations

  • $('tr.even') Rows with class 'even'
  • $('#tasks tr:first') The first row of a table with id 'tasks'
  • $('#tasks').find('tr:first') Same thing
  • $('tr:first', '#tasks') Same thing; second argument specifies DOM sub-tree to search
  • $('section:eq(1) table tr:last td') All table cells in the last row of all tables in the second section
  • $('select[name="category"] > option') All option elements that direct children of a particular select

Example

HTML

<html><head><title>Button Magic</title>
    <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
    <script type='text/javascript' src='jquery.js'></script>
    <script type='text/javascript' src='script.js'></script>
    </head><body>
         <div><br/><strong>Click Me!</strong></div>   
    </body>
</html>

stylesheet.css

div {
    height: 60px;
    width: 100px;
    border-radius: 5px;
    background-color: #69D2E7;
    text-align: center;
    color: #FFFFFF;
    font-family: Verdana, Arial, Sans-Serif;
    opacity: 0.5;
}

script.js

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


To Do List Example

HTML

<h2>To Do</h2>
<form name="checkListForm">
    <input type="text" name="checkListItem"/>
</form>
<div id="button">Add!</div>
<br/>
<div id="list"></div>

script.js

$(document).ready(function(){
    $('#button').click(function(){
        var toAdd = $('input[name=checkListItem]').val();
        $('#list').append('<div class="item">' + toAdd + '</div>');
    });
    $(document).on('click', '.item', function(){
        $(this).remove()
    });
});