1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Web Tutorial -- lesson 1 -- jQuery operations

Discussion in 'Programming' started by seductiveapps.com, Oct 26, 2014.

?

Want more?

  1. Yes

    0 vote(s)
    0.0%
  2. No

    0 vote(s)
    0.0%
  1. #1
    In order to assist aspiring web programmers with a quality tutorial on how to setup a javascript + php app, i now introduce my webTutorials at http://seductiveapps.com/webTutorials/lesson__1___theBasics/index.php

    The code, contained in 3 files, reads :

    index.php :
    
    <html>
        <head>
            <title>App test page</title>
    
            <meta name="robots" content="all">
            <meta name="copyright" content="[the owner of seductiveapps.com]">
            <meta name="author" content="[the owner of seductiveapps.com]">
            <meta http-equiv="cache-control" content="no-cache">
            <meta http-equiv="expires" content="0">
            <meta http-equiv="pragma" content="no-cache">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="content-language" content="en">
            <meta http-equiv="content-language" content="english">
    
            <link rel="shortcut icon" href="favicon.ico"/> <!-- create .ico with gimp.org free photoshop app for Windows and Linux (and MacOS?..)-->
    
            <link type="text/css" rel="StyleSheet" media="screen" href="index.css"/>
    
            <script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
            <script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js" type="text/javascript"></script>
           
            <script src="index.source.js"></script>
        </head>
        <body onload="myApp.startApp()"> <!-- a page is an app when put in an iframe! :) -->
            <div id="explanation">
                <pre>
                This simple web game[1] is a demonstration of various modern (2014-Oct) web techniques.
               
                [You're here] Lesson 1 : include jQuery, use it (or, if you must, another set of helper apps --- jQuery works like a charm for me)
                Over time, i'll add more lessons that explain things like jQuery ajax content grabbing, the smarty template engine (which you could replace with your own or another 3rd party template engine), and perhaps a few more things..
               
                [1]
                [1.1] click on a colored field with a word in it to select it
                [1.2] click anywhere on the page to slide the selected colored field to that location
                </pre>
            </div>
               
            <div id="gameBackdrop" style="position:absolute;width:100%;height:100%;opacity:0.001;background:black">&nbsp;</div>
           
            <!-- .gameElement section -->
            <div id="div__a" class="gameElement normal" style="width:100px;height:50px;">
               Hello
            </div>
            <div id="div__b" class="gameElement normal" style="width:100px;height:50px;">
               World
            </div>    
           
           
        </body>
    </html>
    
    Code (markup):
    index.source.js:
    
    var myApp = {
        about : {
            whatsThis : 'shortvarname = longvarname = [description of component / web app]',
            copyright : '(c) and (r) by YOURNAME of http://YOURCOMPANY.com'
        },
        globals : {
            timeTransition : 1500,
            timeFade : 2000
        },
        settings : {
            handlers : {
                gameElement : {
                }
            }
        },
       
        startApp : function () {
            myApp.settings.timeTransition = myApp.globals.timeTransition;
            myApp.settings.timeFade = myApp.globals.timeFade;
       
            jQuery('#gameBackdrop').click(myApp.ui.handlers.gameBackdrop.click);
           
            var 
            ges = jQuery('.gameElement');
           
            ges.click(myApp.ui.handlers.gameElement.click);
            ges.hover(myApp.ui.handlers.gameElement.hover.over, myApp.ui.handlers.gameElement.hover.out);
            jQuery(ges.get().reverse()).each(function (idx, el) {
                var
                p = jQuery(el).position();
               
                jQuery(el).css ( {
                    top : p.top,
                    left : p.left,
                    position : 'absolute'
                } );
            });
        },
       
        ui : {
            handlers : {
           
                // listed in order expected to be used within this app
    
                gameElement : {
    
                    click : function (evt) { // evt = event data
                        // myApp.settings.handlers['div_slideUp'] === myApp.settings.handlers.div_slideUp
                        var clickedEl = myApp.settings.handlers['gameElement'].clickedEl = evt.currentTarget; 
    
                        jQuery('.gameElement').removeClass('selected').addClass('normal');
                        jQuery(clickedEl).removeClass('hover').removeClass('normal').addClass('selected'); 
                    },
                   
                    hover : {
                        over : function (evt) {
                            jQuery(evt.currentTarget).addClass('hover');
                        },
                        out : function(evt) {
                            jQuery(evt.currentTarget).removeClass('hover');
                        }
                    }
                },
               
                gameBackdrop : {
                   
                    click : function (evt) {
                        var 
                        clickedEl = myApp.settings.handlers.gameElement.clickedEl,
                        css = {
                            top : evt.pageY,
                            left : evt.pageX
                        };
                       
                        jQuery(clickedEl).animate(
                            css,
                            myApp.settings.timeTransition,
                            myApp.settings.transitionEasing,
                            function () {
                                myApp.ui.handlers.game.moveOfGameElementDone(clickedEl, evt)
                            }
                        );
                    }
                },
               
                game : {
                    moveOfGameElementDone : function (clickedEl, evt) {
                        alert ('#'+clickedEl.id + ' has moved..');
                    }
                }
            }
        }
    };
    
    Code (markup):
    index.css:
    
    body {
        margin : 0px;
        padding : 0px;
    }
    
    .gameElement {
        margin : 10px;
        padding : 5px;
        border-radius : 10px 5px;
    }
    
    /* the 3 states for a game element: */
    .gameElement.normal {
        background : navy;
        color : yellow;
        font-weight : bold;
    }
    .gameElement.hover {
        background : green;
    }
    .gameElement.selected {
        background : red;
        color : white;
    }
    
    Code (markup):

     
    seductiveapps.com, Oct 26, 2014 IP
  2. seductiveapps.com

    seductiveapps.com Active Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #2
    I've updated the live link with more modern code... - http://seductiveapps.com/webTutorials/lesson__1___theBasics/index.php which is the same btw as seductiveapps.com/webTutorials/lesson__1___theBasics and which you can run on your own windows computer with http://www.wampserver.com/en/ or on ubuntu with a "lamp linux install" google.com searchquery.

    index.php:
    
    <html>
        <head>
            <title>App test page</title>
    
            <meta name="robots" content="all">
            <meta name="copyright" content="[the owner of seductiveapps.com]">
            <meta name="author" content="[the owner of seductiveapps.com]">
            <meta http-equiv="cache-control" content="no-cache">
            <meta http-equiv="expires" content="0">
            <meta http-equiv="pragma" content="no-cache">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="content-language" content="en">
            <meta http-equiv="content-language" content="english">
    
            <link rel="shortcut icon" href="favicon.ico"/> <!-- create .ico with gimp.org free photoshop app for Windows and Linux (and MacOS?..)-->
    
            <link type="text/css" rel="StyleSheet" media="screen" href="index.css"/>
    
            <script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
            <script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js" type="text/javascript"></script>
         
            <script src="index.source.js"></script>
        </head>
        <body onload="myApp.startApp()"> <!-- a page is an app when put in an iframe! :) -->
            <div id="gameBackdrop" style="position:absolute;width:100%;height:100%;opacity:0.001;background:black">&nbsp;</div>
    
            <div id="explanation">
                <h1>SeductiveApps.com's web tutorials - lesson 1 - the basics</h1>
                <p>
                This simple web game[1] is a demonstration of various modern (2014-Oct) web techniques.<br/>
                </p>
             
                <p>
                [You're here] Lesson 1 : include jQuery, use it (or, if you must, another set of helper apps --- jQuery works like a charm for me)<br/>
                Over time, i'll add more lessons that explain things like jQuery ajax content grabbing, the smarty template engine (which you could replace with your own or another 3rd party template engine), and perhaps a few more things..<br/>
                </p>
             
                <p>         
                [1]<br/>
                [1.1] click on a colored field with a word in it to select it<br/>
                [1.2] click anywhere on the page to slide the selected colored field to that location<br/>
                </p>
            </div>
             
            <div id="gameStatus">
            </div>
         
         
            <!-- .gameElement section -->
            <div id="div__a" class="gameElement normal" style="width:100px;height:50px;">
               Hello
            </div>
            <div id="div__b" class="gameElement normal" style="width:100px;height:50px;">
               World
            </div>  
         
         
        </body>
    </html>
    
    
    Code (markup):
    index.source.js:
    
    var myApp = {
        about : {
            whatsThis : 'shortvarname = longvarname = [description of component / web app]',
            copyright : '(c) and (r) by YOURNAME of http://YOURCOMPANY.com'
        },
        globals : {
            transitionEasing : 'easeInOutQuad', // see easings.net
            timeTransition : 800, // all times listed here (4 digits) are in milliseconds
            timeFade : 2500,
            timeToKeepStatusMsgs : 7000
        },
        settings : {
            handlers : {
                gameElement : {
                }
            }
        },
      
        startApp : function () {
            myApp.settings.transitionEasing = myApp.globals.transitionEasing;
            myApp.settings.timeTransition = myApp.globals.timeTransition;
            myApp.settings.timeFade = myApp.globals.timeFade;
            myApp.settings.timeToKeepStatusMsgs = myApp.globals.timeToKeepStatusMsgs;
      
            jQuery('#gameBackdrop').click(myApp.ui.handlers.gameBackdrop.click);
          
            var
            ges = jQuery('.gameElement');
          
            ges.click(myApp.ui.handlers.gameElement.click);
            ges.hover(myApp.ui.handlers.gameElement.hover.over, myApp.ui.handlers.gameElement.hover.out);
            jQuery(ges.get().reverse()).each(function (idx, el) {
                var
                p = jQuery(el).position();
              
                jQuery(el).css ( {
                    top : p.top,
                    left : p.left,
                    position : 'absolute'
                } );
            });
        },
      
        ui : {
            handlers : {
          
                // listed in order expected to be used within this app
    
                gameElement : {
    
                    click : function (evt) { // evt = event data
                        // myApp.settings.handlers['div_slideUp'] === myApp.settings.handlers.div_slideUp
                        var clickedEl = myApp.settings.handlers['gameElement'].clickedEl = evt.currentTarget;
    
                        jQuery('.gameElement').removeClass('selected').addClass('normal');
                        jQuery(clickedEl).removeClass('hover').removeClass('normal').addClass('selected');
                    },
                  
                    hover : {
                        over : function (evt) {
                            jQuery(evt.currentTarget).addClass('hover');
                        },
                        out : function(evt) {
                            jQuery(evt.currentTarget).removeClass('hover');
                        }
                    }
                },
              
                gameBackdrop : {
                  
                    click : function (evt) {
                        var
                        clickedEl = myApp.settings.handlers.gameElement.clickedEl,
                        css = {
                            top : evt.pageY,
                            left : evt.pageX
                        };
                      
                        jQuery(clickedEl).animate(
                            css,
                            myApp.settings.timeTransition,
                            myApp.settings.transitionEasing,
                            function () {
                                myApp.ui.handlers.game.moveOfGameElementDone(clickedEl, evt)
                            }
                        );
                    }
                },
              
                game : {
                    moveOfGameElementDone : function (clickedEl, evt) {
                        jQuery('#gameStatus').html('#'+clickedEl.id+' has moved!').css({display:'none'}).fadeIn(myApp.settings.fadeTime);
                        setTimeout(function() {
                            jQuery('#gameStatus').fadeOut(myApp.settings.fadeTime);
                        }, myApp.settings.fadeTime + myApp.settings.timeToKeepStatusMsgs );
                    }
                }
            }
        }
    };
    
    
    Code (markup):
    index.css:
    
    body {
        margin : 0px;
        padding : 0px;
    }
    
    .gameElement {
        margin : 10px;
        padding : 5px;
        border-radius : 10px 5px;
    }
    
    #gameStatus {
        background : navy;
        color : yellow;
        border-radius : 5px;
    }
    
    /* the 3 states for a game element: */
    .gameElement.normal {
        background : navy;
        color : yellow;
        font-weight : bold;
    }
    .gameElement.hover {
        background : green;
    }
    .gameElement.selected {
        background : red;
        color : white;
    }
    
    
    
    Code (markup):
     
    Last edited: Oct 26, 2014
    seductiveapps.com, Oct 26, 2014 IP
  3. seductiveapps.com

    seductiveapps.com Active Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Load up http://seductiveapps.com/webTutorials/lesson__1___theBasics/index.php, then press F12 in your browser. Do experiment with this code on your own server if you are serious about webcoding. Add "debugger;" to the javascript to see with the debugger behind F12 what your javascript variables are up to, read descriptions on google.com for "html css {css-property}" and try to play with this code yourself. If you don't practice a whole lot, you'll never be good at coding. At least that's my experience. You can also use jsfiddle to share your results with the world, if you don't want to get into running your own webserver. But in a few lessons time I'll have to include PHP, which you can't run on jsfiddle.com, only on paid hosted sites or your own webserver (domain registration costs via godaddy.com for instance, and possibly other costs there like private registration (which you have to buy at the moment you first register a domain name, or your home address is going to be exposed to the world via pesky whowas services))..
     
    seductiveapps.com, Oct 26, 2014 IP
  4. Anveto

    Anveto Well-Known Member

    Messages:
    697
    Likes Received:
    40
    Best Answers:
    19
    Trophy Points:
    195
    #4
    I like the excessive use of underscores and I am pretty sure you could run this locally if you simply change the .php extension to .html

    I don't see how this is a lesson since you are not really explaining anything and the example is not something that's really practical.
     
    Anveto, Oct 26, 2014 IP
  5. seductiveapps.com

    seductiveapps.com Active Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #5
    You
    I follow the basic school model : start with something relatively simple, explaining a few aspects of something complicated (in this case, how to use jQuery for visual interactions, how to bind event handlers, how to communicate between events), but at the same time being ready for more complicated explanations further down the line in the same type of test app (smarty template engine, ajax content loading, etc, etc)..

    The excessive use of underscores is not as excessive as you think either ;)
     
    seductiveapps.com, Oct 26, 2014 IP
  6. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #6
    While the underscores themselves aren't that important, what's worse is that you use camelcase for classnames - CSS should be all lower case, as all html elements should be all lower case. What's more disturbing is that you're pushing Smarty. Why in the world? A template engine is slightly worse than a framework, in that it provides NOT ONE feature not available directly in the underlying language.
    And as @MarkusTenghamn said, this isn't really a tutorial - a tutorial isn't just an example, it's an explanation of why - this fails that. The example works fine, but the concepts aren't explained for the novice - a novice has no idea why you're doing what you're doing, and you're not providing any information apart from the files themselves.
     
    PoPSiCLe, Oct 27, 2014 IP
  7. seductiveapps.com

    seductiveapps.com Active Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #7
    Well, you have to use .className or it won't work, that's why ;) Smarty is seperation of content, layout and code, which is good :) But your comments about 'no explanations = bad', i'll take to heart.
    Anyone else, especially in the group of people who try to learn from the code example i provided, who wants more explanation? I was kinda hoping the code itself would be explanation enough...
     
    seductiveapps.com, Oct 27, 2014 IP
  8. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #8
    Uh, what? Why in the world won't just .classname work? There's no need for the camelCase. Smarty is NOT separation of content, layout and code. Smarty is a template engine which lets you disguise the code to be able to put it directly into the front-end files (.html or whatnot). There's absolutely no reason to use Smarty. None. Whatsoever.
    Here's a couple links:
    http://blog.killtheradio.net/technology/why-i-hate-smarty/
    http://community.sitepoint.com/t/yet-another-reason-smarty-sucks/6982/11

    Smarty is aged, and not really good in any way. If you don't want to just use PHP and html/css and javascript, at least use a proper framework.
     
    PoPSiCLe, Oct 29, 2014 IP
    malky66 likes this.
  9. deli6z

    deli6z Greenhorn

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    21
    #9
    what is your alternative for a smarty ?
     
    deli6z, Oct 29, 2014 IP
  10. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #10
    Plain and simple HTML and PHP, of course. But then again, I've never really understood the "need" for MVC when it comes to PHP - as long as you separate the _business_ logic from the rest of the application, there's no harm in running simple php in the output files.
    I've still to understand how learning and using a completely different language on top of already existing languages able to do everything already, is beneficial. Also, Smarty makes it way harder to update stuff (unless you're actually familiar with Smarty), and adds weight.
    Granted, my previous encounters with Smarty has mainly been via phpBB (which used Smarty at least for earlier incarnations, haven't had to deal with it for a few years, so no idea what they're using now), and it sucks, and complicates so many things - especially integration and compatability.
     
    PoPSiCLe, Oct 29, 2014 IP
  11. seductiveapps.com

    seductiveapps.com Active Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #11
    Look, the .className / .classname declaration is gone from the latest source anyway, and to me, smarty IS seperation of content and app logic.

    If you're only going to heckle my effort here... just don't. you come accross as a grumpy old man..
     
    seductiveapps.com, Oct 29, 2014 IP
  12. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #12
    I am a grumpy old man. But toting deprecated technology (Smarty) is hardly a good point if you're calling me grumpy. Since you're a proponent of Smarty, why don't you present a 5-point list (or something similar) with reasons why one should use Smarty (preferably with a short code-snippet to accompany it and explain what the benefit is)? I would be interested in seeing something like that.
     
    PoPSiCLe, Oct 29, 2014 IP
  13. Anveto

    Anveto Well-Known Member

    Messages:
    697
    Likes Received:
    40
    Best Answers:
    19
    Trophy Points:
    195
    #13
    How to write a tutorial: http://www.wikihow.com/Write-a-Tutorial

    That's all there is too it really, you need to explain things if you want a good tutorial and I think that's all the feedback we need to give you.

    I think we went completely off topic when we started debating whether Smarty is good to use. People still use it maybe it is a good niche that will drive a lot of traffic to his tutorial site.

    Although I wouldn't use it, Smary "facilitates a managable way to separate application logic and content from its presentation" http://smarty.incutio.com/?page=SmartyFrequentlyAskedQuestions#basics-1

    I would learn how to use a header and footer for your php files, then each page you create can include them and reuse the code and each page sort of becomes its own template file in a way. Smarty seems to just make you have to do a lot of extra work unless you have a really complex script and want to use smarty for your templates then it could be a good idea.
     
    Anveto, Oct 30, 2014 IP
  14. seductiveapps.com

    seductiveapps.com Active Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #14
    Ok, i'll take your comments to heart and write (kinda soon, but not immediately) a proper explanation for the code i've submitted so far..

    As for smarty, i'm not a fan of using smarty for everything. But for the basic seperation of business logic and HTML output, it's a good choice imo, although one could use plain PHP string substitution. I'm not using the for-loops in Smarty or any of it's advanced features which i believe to be redundant (already implemented by PHP itself).

    For the moment though, I'm working on a better menu component for my framework, and this requires my full attention.
    I'll write the explanation for my code as soon as i'm done with that.
     
    seductiveapps.com, Nov 4, 2014 IP
  15. seductiveapps.com

    seductiveapps.com Active Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #15
    Ok, i've added documentation to my code examples, which i hope will make the basics of webdesign clear to everyone.
    Once again, i'm open for constructive criticism.

    The URL is still http://seductiveapps.com/webTutorials/lesson__1___theBasics/

    index.php :
    
    <?php
        require_once (dirname(__FILE__).'/functions.php');
            /* after dirname(__FILE).'/', this takes a relative path from the directory *this* file is in.
                this notation serves to let *this* file be included in all sorts of (advanced) ways.
            */
      
      
    ?>
    <html>
        <head>
        <!-- STARTUP, STEP 1 : <head> gets parsed first by the browser, and completely parsed before <body onload="someHandler()" gets called -->
      
            <title><?php echo getTitle()?></title>
                <!-- echo getTitle() is the preferred way of including PHP output into HTML -->
                <!-- <title>someText</title> puts "someText" in the window title for the tab that views this HTML page -->
    
            <meta name="robots" content="all">
                <!-- this lets search engines crawl all of this page -->
            <meta name="copyright" content="[YOURNAME <you@YOURDOMAIN.com>]">
            <meta name="author" content="[YOURNAME <you@YOURDOMAIN.com>]">
            <meta http-equiv="cache-control" content="no-cache">
            <meta http-equiv="expires" content="0">
            <meta http-equiv="pragma" content="no-cache">
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
            <meta http-equiv="content-language" content="en">
            <meta http-equiv="content-language" content="english">
    
            <link rel="shortcut icon" href="favicon.ico"/>
                <!-- create .ico with gimp.org free photoshop app for Windows and Linux (and MacOS?..)-->
    
            <link type="text/css" rel="StyleSheet" media="screen" href="index.css"/>
    
            <!-- include jQuery from a CDN (content delivery network), fastest way according to jQuery.com -->
            <script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
            <script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js" type="text/javascript"></script>
          
            <!-- include the javascript that controls this HTML page: -->
            <script src="index.source.js"></script>
        </head>
        <body onload="myApp.startApp()">
        <!-- STARTUP, STEP 2 : myApp.startApp() gets called as soon as this entire HTML file has reached the browser AND the <head> section is completely loaded up and initialized (any javascript in <head> gets executed BEFORE myApp.startApp() is called -->
        <!-- note : a HTML page is an app when put in an iframe! :) -->
      
      
            <div id="gameBackdrop" style="position:absolute;width:100%;height:100%;opacity:0.001;background:black">&nbsp;</div>
    
            <div id="explanation">
                <h1>SeductiveApps.com's web tutorials - lesson 1 - the basics</h1>
                <p>
                This simple web game[1] is a demonstration of various modern (2014-Oct) web techniques.<br/>
                </p>
              
                <p>
                [You're here] Lesson 1 : include jQuery, use it (or, if you must, another set of helper apps --- jQuery works like a charm for me)<br/>
                Over time, i'll add more lessons that explain things like jQuery ajax content grabbing, the smarty template engine (which you could replace with your own or another 3rd party template engine), and perhaps a few more things..<br/>
                </p>
              
                <p>          
                [1]<br/>
                [1.1] click on a colored field with a word in it to select it<br/>
                [1.2] click anywhere on the page to slide the selected colored field to that location<br/>
                </p>
            </div>
              
            <div id="gameStatus">
            </div>
          
          
            <!-- .gameElement section -->
            <div id="div__a" class="gameElement normal" style="width:100px;height:50px;">
               Hello
            </div>
            <div id="div__b" class="gameElement normal" style="width:100px;height:50px;">
               World
            </div>   
          
          
        </body>
    </html>
    
    
    Code (markup):
    functions.php:
    
    <?php
    
    function getTitle () {
        return 'SeductiveApps.com Web Tutorial part 1';
    }
    
    ?>
    
    Code (markup):
    index.css:
    
    body {
        /* applies to <body> of the HTML this CSS file is incldued into */
        margin : 0px;
        padding : 0px;
    }
    
    .gameElement {
        /* applies to all HTML elements with class="gameElement" or class="hover normal gameElement" or class="normal gameElement" or class="gameElement normal", etc */
        margin : 10px;
        padding : 5px;
        border-radius : 10px 5px;
    }
    
    #gameStatus {
        /* applies only to HTML element with id="gameStatus" */
        background : navy;
        color : yellow;
        border-radius : 5px;
    }
    
    /* the 3 states for a game element: */
    .gameElement.normal {
        /* these settings apply to all HTML elements that (at any particular moment!) have a class="gameElement normal" */
        background : navy;
        color : yellow;
        font-weight : bold;
    }
    .gameElement.hover {
        /* applies to HTML elements with class="gameElement hover" or class="gameElement normal hover" or class="gameElement hover normal" */
        background : green;
    }
    .gameElement.selected {
        background : red;
        color : white;
    }
    
    Code (markup):
    index.source.js:
    
    var myApp = {
        about : {
            whatsThis : 'shortvarname = longvarname = [description of component / web app]',
            copyright : '(c) and (r) by YOURNAME of http://YOURCOMPANY.com'
        },
        globals : {
            transitionEasing : 'easeInOutQuad', // see easings.net
            timeTransition : 800, // all times listed here (4 digits) are in milliseconds
            timeFade : 2500,
            timeToKeepStatusMsgs : 7000
        },
        settings : { // this { character starts a new "folder" inside the myApp variable (myApp.settings, which can be SEEN as myApp/settings)
            handlers : {
                gameElement : {
                }
            }
        },
      
        startApp : function () {
            // transfer the global settings into "current" settings, in order to (in a later tutorial that expands on this tutorial) let the end-user change these settings:
            myApp.settings.transitionEasing = myApp.globals.transitionEasing;
            myApp.settings.timeTransition = myApp.globals.timeTransition;
            myApp.settings.timeFade = myApp.globals.timeFade;
            myApp.settings.timeToKeepStatusMsgs = myApp.globals.timeToKeepStatusMsgs;
      
            // bind the click event for #gameBackdrop (which is the HTML element with id="gameBackdrop") to myApp.ui.handlers.gameBackdrop.click()
            jQuery('#gameBackdrop').click(myApp.ui.handlers.gameBackdrop.click);
                /* in jQuery, all "#someID" means id="someID" in HTML
                    and all ".gameElement" means class="gameElement" in HTML
                */
          
          
            var
            ges = jQuery('.gameElement');
                /* this sets up var ges, which will hold a jQuery object that contains all HTML elements with class="gameElement", that we can work with below here : */
          
            ges.click(myApp.ui.handlers.gameElement.click);
          
            // see http://api.jquery.com/hover/
            ges.hover(myApp.ui.handlers.gameElement.hover.over, myApp.ui.handlers.gameElement.hover.out);
          
            // see http://api.jquery.com/each/
            // this walks over all HTML elements with class="gameElement" and makes these elements have a style (see the jQuery(el).css() call) with position:absolute; and top: and left: set to the position that it's default, position:relative has put it on page loading.
            // in order to move the .gameElements around on the screen, they need to have their position:absolute, and if you'd do this from index.php in the HTML or from index.css, you get all .gameElement positioned at the top-left of the page, overlapping eachother, which is obviously not what you want for a game.
            jQuery(ges.get().reverse()).each(function (idx, el) {
                var
                p = jQuery(el).position();
              
                jQuery(el).css ( {
                    top : p.top,
                    left : p.left,
                    position : 'absolute'
                } );
            });
        },
      
        ui : {
      
            handlers : {
          
                // listed in order expected to be used within this app
    
                gameElement : {
    
                    click : function (evt) { // evt = event data
                        // myApp.settings.handlers['div_slideUp'] === myApp.settings.handlers.div_slideUp
                        var clickedEl = myApp.settings.handlers['gameElement'].clickedEl = evt.currentTarget;
    
                        jQuery('.gameElement').removeClass('selected').addClass('normal');
                        jQuery(clickedEl).removeClass('hover').removeClass('normal').addClass('selected');
                    },
                  
                    hover : {
                        over : function (evt) {
                            jQuery(evt.currentTarget).addClass('hover');
                            /* do a google.com search query : "jquery addclass" */
                        },
                        out : function(evt) {
                            jQuery(evt.currentTarget).removeClass('hover');
                        }
                    }
                },
              
                gameBackdrop : {
                  
                    click : function (evt) {
                        var
                        clickedEl = myApp.settings.handlers.gameElement.clickedEl,
                        css = {
                            top : evt.pageY,
                            left : evt.pageX
                        };
                      
                        jQuery(clickedEl).animate( // do a google.com search for "jquery animate"
                            css,
                            myApp.settings.timeTransition,
                            myApp.settings.transitionEasing,
                            function () {
                                myApp.ui.handlers.game.moveOfGameElementDone(clickedEl, evt) // see [1]
                            }
                        );
                    }
                },
              
                game : {
                    moveOfGameElementDone : function (clickedEl, evt) { // [1]
                        jQuery('#gameStatus')
                            .html('#'+clickedEl.id+' has moved!')
                            .css({display:'none'})
                            .fadeIn(myApp.settings.fadeTime);
                          
                        setTimeout(function() {
                            jQuery('#gameStatus').fadeOut(myApp.settings.fadeTime);
                        }, myApp.settings.fadeTime + myApp.settings.timeToKeepStatusMsgs );
                    }
                }
            }
        }
    };
    
    Code (markup):
     
    Last edited: Nov 4, 2014
    seductiveapps.com, Nov 4, 2014 IP
  16. Anveto

    Anveto Well-Known Member

    Messages:
    697
    Likes Received:
    40
    Best Answers:
    19
    Trophy Points:
    195
    #16
    Better, but you should tell the user how to learn from the example, like "The code is heavily commented on this page and by viewing the source code you could learn from this example" or something along those lines.
     
    Anveto, Nov 5, 2014 IP