jQuery Basics

Before you go any further, there`s something about jQuery you need to know first.

Dollar Sign ($)

The original jQuery code is like this
    //do something here..

By default, jQuery uses "$" as a shortcut for "jQuery" (replace jQuery with dollar sign)
    //do something here..

Using javascript built-in function to select element
<div id="ele">This is a test</div>
var e = document.getElementById("ele");

Using jQuery to select element
<div id="ele">This is a test</div>
var e = $("#ele");


Document Ready

Most of the time we want to run javascripts on page load, we could write the code like this
window.onload = function(){ 
    alert("Document ready!"); 

But there is a catch, window.onload only get triggered when all assets(e.g. images) are loaded, what if we
want to run the codes as soon as DOM hierarchy has been fully constructed? you could use the code like this
    //run your code here


id selector(#id)

jQuery uses id attribute to identify each unique element throughout the page.
ExampleSelect elements with id attribute
Source Code Expand
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- Javascript -->
<script type="text/javascript">
$(document).ready(function (){
    /* select elements and assign to variables */
    var t1 = $("#text1"), t2 = $("#text2"), t3 = $("#text3");
    var b1 = $("#btn1"), b2 = $("#btn2"), b3 = $("#btn3"), b4 = $("#btn4");

    /* bind click event */
        t1.css("color", "orange");       /* change color of text1 to orange */

        t2.css("font-style", "italic");  /* change font size of text1 to 18px */

        /* change text of text3 */ 
        t3.text("George did not give them back car and house"); 
        t3.css("font-size", "20px");

        t1.removeAttr("style"); /* remove all css */
        t3.text("George borrows car and house from them");

<!-- HTML -->
<a name="#id-selector"></a>
<div id="text1">Jhonny has a car</div>
<div id="text2">Marry has a house</div>
<div id="text3">George borrows car and house from them</div>
<button type="button" id="btn1">Select text1</button>&nbsp;
<button type="button" id="btn2">Select text2</button>&nbsp; 
<button type="button" id="btn3">Select text3</button>&nbsp; 
<button type="button" id="btn4">Reset</button>

comments powered by Disqus