Note: the $ sign is frequently used to represent the object of Jquery in jquery coding.
1) Download the Jquery library
2) Make a separate file with the extension of .js in a javascript directory (can call it js for instance).
Put the downloaded JQuery.js file in there.
Note for other external script files: External scripts cannot contain
-you can do this for multiple .js files as needed
4) Write jquery code in .js file
========================
Syntax:
$('elementorObjectSelector').propertyOrMethod(function(){ code };
----------
Note: Generally a good idea to have a script that stops the code from running until the document is finished loading:
$(document).ready(function() {
//$(JQuery code) when the document has finished loading;
});
===================================
-To get element:
$('elementName').method();
-------------
-To get the id Ex:
with id of 'heading':
$('h1#heading').method();
----------------
-To get a class:
-All classes: $(.className).method();
with a classname
$('h1.className').method();
-------------------
-To get child elements:
$('parentName childName').method();
Ex:
$('p span').method();
-To grab specific child element:
$('h1 p:first').method(); //this grabs the first
child in
$('h1 p:last').method(); //gets the last child in the parent
$('h1 p:even').method(); //grabs even numbered children from parent
$('h1 p:odd').method();
-Choose every child at a specific interval:
use nth-child():
Ex: $('h1 p:nth-child(3n)').method(); //grabs every 3rd
in
---------------------
-get element by type:
use the colon ':'
$(':type').method(); //ex: $(':button').method(); --selects all buttons
-------------------
-Select attributes:
Select all attributes href in page:
$('[href]').method();
Select the value of the attribute:
syntax: $('[attributeName]').method();
//use the brackets to select an attribute.
$('a[href="link.com"]').method();
---------------------------
==========================
EVENTS:
-Mouse Events:
-click():
$('#btnIdName').click(function(){
alert('Button Clicked');
})
Note: this is shorthand for the 'on' method;
(the click method runs the full 'on' method behind the scenes:
$('#btnIdName').on('click', function() {
//code runs;
});
---------
Example using on click method to hide an element when another is clicked:
$('#btnId').on('click', function() {
$('.otherClass').hide();
});
-Toggle button function example:
$('#btnId').on('click', function() {
$('.otherClass').toggle();
});
to specify what happens when toggled:
$( "#target" ).toggle(function() {
alert( "First handler for .toggle() called." );
}, function() {
alert( "Second handler for .toggle() called." );
});
----------------------
-Double Click Event :
$('#btnId').dblclick(function(){
$code to run when double clicked;
});
------------------------
-Mouse Hovering:
$('#btnId').hover(function(){
$code to run when mouse hovers on #btnId;
});
Note: .hover() is a shorthand combination of mouseenter() and mouseleave() methods.
----------------------
-Mouse move:
$('#btnId').mousemove(function(){
$code to run when mouse is moved;
}
-------------------
-Mouse up/Mouse Down:
executes functions when mouse is clicked (mousedown) and stops when it's released, and when mouse click is released (mouseup).
Ex:
$('#btnId').mousedown(function(){
$code to run when mouse first clicked and stops when released;
}
$('#btnId').mouseup(function(){
$code to runs when mouse click released;
}
** You can combine mouse down and mouse up.
-------------------
======================
To Work with the target of the event's properties, pass in 'e' to the function of the method being used:
-Grab information about what is clicked on the page:
pass in an 'e' parameter to the function and then access the properties with e.currentTarget.propName.
Ex:
$('#elementId').click(function(e){
alert(e.currentTarget.id); -returns id of clicked element
alert(e.currentTarget.innerHTML); //returns the text in between tags of the element clicked.
alert(e.currentTarget.outerHTML); //returns the tags info etc.
alert(e.currentTarget.className); //returns class name
}
-------------
Coordinates:
work with coordinates using e.clientX or e.clientY for X/Y coordinates of the mouse
Ex:
$('document').mousemove(function(e){
$('elementOnPage').html('e.clientY + e.clientX');
//this displays the xy coordinates when the mouse moves on the screen continuously updated. (.append adds each event to a list)
)};
===============
FORM EVENTS:
-Focus events (when you click into an )
You can trigger events when the user clicks on a field input etc:
$('input').focus(function(){
alert("focus");
});
-----
Ex: change the baackground color of the input field when user clicks in it:
**Use 'this' (without quotes!!) in the code to indicate whatever object element is being clicked in:
$('input').focus(function(){
$(this).css('background', 'blue');
});
//grabs all inputs but targets the one being clicked with 'this'.
---------------
-Blur event (the opposite of focus, when user clicks out of the ):
To change background color back when user clicks outside of the input field:
$('input').blur(function(){
$(this).css('background', 'white'(or whatever Body Is);
});
--------------------
-KEYUP and KEYDOWN: .keyup() .keydown()
$('input').keyup(function(){
console.log('keyup');
});
-To get the data that's being taken in with the keyup:
$('input').keyup(function(e){
console.log('e.target.value');
});
//returns the actual value on keyup (the key on the keyboard being pressed).
------------------
-CHANGE: .change()
Run code when there is a change (i.e. on a select menu)
$('select#gender').change(function(){
alert('changed!');
});
// alerts user when the drop down menu selection changes.
-------------------
-FORM SUBMIT EVENTS using .submit():
$('#form').submit(function(e){
e.preventDefault();
console.log('message');
}
//preventDefault pauses the form from being submited and allows access to form data entered by the user.
-To get values of the inputs:
$('input#name').val(); //returns the value of the input with id of 'name'
=============================
DOM MANIPULATION:
Adding and changing CSS properties of elements:
-Change the color of an element:
$('p.pClass').css('color', 'red'); //changes
class to red color.
Note: to affect multiple CSS props on an element, wrap code as an object using {}:
Ex:
$('p.pClass').css({color: 'red', background: 'white'});
-------------
-Add or Remove Classes:
$('p.pClass').addClass('newClassToAdd'); //this adds the class to
with pClass class.
$('p.pClass').removeClass('newClassToAdd'); //removes the specified class from
. pClass
-To toggle a class when an element is clicked on (for ex, to change it's appearence based on what's in the css file):
$('p.pClass').click(function(){
$('element').toggleClass('classAddedWhenClicked');
});
----------------
-set or get values with .text and .html:
$('element').html('
This adds HTML code to the element
');
$('element').text('this displays as text in the element');
----
-Get the text and html values when method parameter is left blank:
alert($('element').text()); //alerts the text value of the element
-----------------------
-APPEND AND PREPEND: .append() .prepend()
add values to or before elements selected.
-you can also append other elements to other elements:
Ex: $('element1').appendTo('element2');
Works with prependTo() as well.
-----
Note: append and prepend work inside parent elements generally. To place elements outside of a parent (div or ul for instance), use:
.before() and .after()
$('ul').before('
Hello
'); //this places the h4 before the
and not inide it.
-----
.empty() - takes all the inner elements out of a selector:
$('ul').empty();
//removes all child elements and inner elements from the unordered list, but the
parent element is still there, just empty.
------
.detach()
To remove
or elements entirely, use .detach():
$('ul').detach(); //the element is removed from the DOM.
-----
-Set attributes of elements: .attr()
Syntax:
$('element').attr('attribute', 'value');
Ex: $('a').attr('target', '_blank');
//sets target attribute of anchor links to '_blank'.
------
-Access attributes and Perform functions on attributes:
alert($('a').attr('href')); //alerts the link url to the user
------
-Remove Attributes with .removeAttr():
$('element').removeAttr('attribute');
-------------------
-WRAP(); - wraps tags around elements:
$('p').wrap('
');
//this takes the
elements and wraps each of them in
tags
Note: the closing tag is automatically included
-wrapAll(); -groups all the elements together and wraps them in the tag selected.
$('p').wrapAll('
'); //wraps
tags around grouped
elements
---------------------
-Assign a function to a keyup event:
$('#newItem').keyup(function(e) {
var code = e.which; (<---this property holds value of the keypress)
if(code == 13){
e.preventDefault();
$('ul').append('
'+e.target.value + '
');
{
}
Note: 13 is the keycode number for enter used in the if statement condition. e.which gets the keycode from the keypress and compares it to the desired key for the method to run. e.preventDefault() stops the keypress from doing what it normally would and instead the .append() runs to add the value to the target ('ul') when enter is pressed.
//This inserts a new item to a list when the user presses enter after entering text into the field.
----------------------------------
-Working with Arrays on JQuery:
var myArray = ['1','2','3','4','5'];
-use $.each() to loop through an array:
takes two parameters- index(i) and value(val):
$.each(myArray, function(i, val){
console.log(val); //logs each item in the array
}
Example appending items to a list in the DOM:
$.each(myArray, function(i, val){
$('#users').append('
'+val+'
');
});
//appends each item in the index to an unordered list as a list item.
-------
To select elements and put them into an array:
var newArray = $('ul#list li').toArray();
----------------------------------------
-EFFECTS AND ANIMATIONS:
-.fadeOut():
$('button').click(function(){
$('#buttonDiv').fadeOut();
});
//fades out the buttons inside the div. Can set parameters to fast, slow, or milliseconds: i.e. fadeOut('fast'); fadeOut('slow'); fadeOut(3000);
-also takes an optional callback function that occurs when fadeout is done:
$('button').click(function(){
$('#buttonDiv').fadeOut('fast', function(){
$('button').text('It's Gone');
});
});
//When the button div fades out, the text of the button is changed to 'It's Gone'.
-------
-fadeIn() same process as with fadeOut()
--------
-fadeToggle() - fades in on one event call, and out on another or vice versa:
$('button').click(function(){
$('#buttonDiv').fadeToggle();
});
//the button div will fadeout on click and when clicked again, fade back in.
----------------
-.slideUp() / .slideDown / .slideToggle:
the element will slide up or down to disappear or show.
$('button').click(function(){
$('#buttonDiv').slideUp();
});
-To stop the slide:
$('#buttonstop').click(function(){
$('#buttonDiv').stop();
});
//this stops the sliding when clicked
--------------------
ANIMATION:
(You can animate anything using the css properties that are numeric or numeric like (i.e. '500px').
-$('#moveButton').click(function(){
$('#moveDiv').animate({
left: 500
});
});
//this modified the CSS property of moveDiv; The animation will slide the element to the new position.
//the moveDiv will move 500 to the right when moveButton is clicked.
Note: there is no semicolon after the css mod. Also: the element in the main.css must be set to position: relative;
**When setting CSS properties use object literal syntax ({} with commas separating values).
To move it back:
$('#moveBackBtn').click(function(){
$('#moveDiv').animate({
left: 0
});
});
//this sets the CSS property back to 0 where it was before.
--------
You can modify the size and other properties with animation as well:
**When setting CSS properties use object literal syntax ({} with commas separating values).
$('#moveBackBtn').click(function(){
$('#moveDiv').animate({
left: 0,
height: '300px',
width: '300px',
opacity: '0.5'
});
});
//this animates a change of height, width and opacity in addition to position.
If you want the element to return to original size with an event, then reset the values with another code block and call.
----------
This code moves the moveDiv around the screen in a square when moveBtn is clicked
$('#moveBtn').click(function(){
$('#moveDiv').animate({
left: 300
});
});
$('#moveBtn').click(function(){
$('#moveDiv').animate({
top: 300
});
});
$('#moveBtn').click(function(){
$('#moveDiv').animate({
left: 0,
top: 300
});
});
$('#moveBtn').click(function(){
$('#moveDiv').animate({
left: 300,
top: 0
});
});
==================================
===========================
MISC:
-If you need to run JS code at the top of the body in the html code, you can use:
$(document).ready(function() {
//code that you want to run when the document has finished loading;
});