Home

ABCs of OOP Objects

jQuery Example

A. Create An Object:

  1. Open Dreamweaver (or your favorite editor) and create a new page.
  2. In Code View, create a blank pair of <div> tags between the pair of <body> tags:
<body>
    <div></div>
</body>

NOTE: This is an invisible object (container). To "see" it, we need to give it some CSS properties.

  1. Write the following CSS ID selector between a pair of <style> tags within the <head> tag:
<style>

#myBox{
 height:100px; 
 width:100px; 
 background-color:black;
 color:white;
 position:absolute;} 

</style>

NOTE: The position:absolute name/value pair causes the <div> tag to "float" above the page so that it can be animated later.

  1. Add the following line of code below other closing </script> tag to connect to a remote jQuery framework:

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

    NOTE: You could also download a local copy of the jQuery framework from jQuery.com and link it to your page instead.

B. Give Object A Name:

  1. In Code View, give the <div> tag an ID name:

  2. <div id = "myBox"></div>

  3. (Optional) Add a small amount of text between the <div> tags:

    <div id="myBox">My Box</div>

C. Talk To Object and Tell Object To Do Something:

  1. Copy the JavaScript example if you did it earlier OR follow the same steps in the JavaScript example (with the advanced steps being optional) and then change the following code at the beginning and ending of the main code block:

    Change window.onload = function( ) TO $(document).ready(function(e)

    AND

    Change }; //End of onLoad function TO }); //End of $(document).ready

    CAUTION:
    Notice the extra parenthesis that is needed to close the $(document).ready method.

  2. Preview the page in a browser.

    TEST RESULT: It behaves just like its JavaScript counterpart.

  3. Change the JavaScript object reference to a jQuery object reference.

    Change document.getElementById("myBox").style.left = currentXPos + "px";

    TO

    $("#myBox").css("left", currentXPos);

    NOTE: Notice that the jQuery uses a simple reference to the object ($("#myBox")) instead of the long JavaScript object reference (document.getElementById("myBox")); Also, notice that JavaScript uses object.style.css_property = value + "px"; and jQuery uses object.css("css_property",value).

  4. Preview the page in a browser again:

    TEST RESULT: It behaves just like the previous example but it uses the jQuery reference which is easier to learn and write.
< Previous Topic     Next Topic >

© 2015. RMCS. All rights reserved.