Basic Structure
$(document).ready(function(){
$(selector).event(function(){
$(selector).effect();
});
$(document).on('selector', 'event', function(){
$(selector).effect();
});
});
selector and select child\parent element
$('element_type')
$('.class')
$('#element_id')
$('selector:nth-child(4)')
$('selector:last-child(4)')
$('selector:even')
$('selector:odd')
$('selector').parent()
$(this)
event
- mouseenter(function(){})
- mouseleave(function(){})
- click()
- dblclick()
double click
- hover(inFunc, outFunc)
inFunction is required.
- focus()
- keydown() keypress() keyup()
keydown: the key is on its way down
keypress: the key is pressed down
keyup: the key is released
effect
- slideDown(‘fast’)
- slideToggle(‘slow’)
- fadeTo(‘fast’, 0.25)
- hide()
- fadeOut()
- fadeIn()
- animate()
input1: the animation to perform
input2: the time in which to perform the animation
$(document).ready(function() {
$('div').animate({left:'+=10px'},500);
//increasing the distance from the left margin moves something to the right
});
Modifying HTML Elements
- target.append(‘<p>element</p>’)
inserts the specified element as the last child of the target element.
- prepend()
inserts the specified element as the first child of the target element.
- appendTo(target)
- prependTo()
- move element
ele1.after(ele2);
ele1.before(ele2);
- empty()
deletes an element’s content and all its descendants
- remove()
not only deletes an element’s content, but deletes the element itself
- addClass()
- removeClass()
- toggleClass()
if the element has the class, it removes that class; if not, it adds the class.
- height(value) / width(value)
- css(CSS_element, value)
- html()
get/set html content
- val()
get the value of form element
$('input:checkbox:checked').val();
//Get the value from an input
var input = $('input[name=checkListItem]').val();
- clone()
- prop(property, value)
set element property.
There is also a method attr(), but I am quite confused about html attr vs. prop.
Using Ajax get and display json file example
getJSON()
$.getJSON("/json/cats.json", function(json) {
$(".message").html(JSON.stringify(json));
});
Convert Json data to HTML
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);