‹‹ homeUsing jQuery in an Embedded Widget

Markup used on this page:

<head>
<script type="text/javascript" src="jquery-1.0.2.js"></script>
<script type="text/javascript" src="widget.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    $('#pageVer').html('This page uses jQuery ver: ' + $.fn.jquery).click(function() {
        alert($.fn.jquery);
    });
});
</script>
</head>
<body>
    <button id="pageVer" title="Click to retest"></button>
    <button id="widgVer" title="Click to retest"></button>
    ...
</body>    
    

widget.js


// create closure for this widget/gadget
(function() {

    // inside this closure we can create vars and functions
    // that are private and don't polute the global namespace

    // capture the existing jQuery version, if there is one
    var oldJQ = window.jQuery;

    // embed packed jquery library needed for this widget

    // jQuery 1.2.3 - Copyright (c) 2008 John Resig (jquery.com)
    eval(function(p,a,c,k,e,r){e= //... and so on... make sure you end this line with a semicolon;

    // create another closure to which we pass "our" version of jQuery
    (function($) {

        //////////////////////////////////////////////////////
        // BEGIN - widget specific code

            $(document).ready(function() {
            
                $('#widgVer').html('The widget uses jQuery ver: ' + $.fn.jquery).click(function() {
                    alert($.fn.jquery);
                });
            
                setInterval(updateTime, 1000);
                updateTime();
            });

            function updateTime() {
                $('#widget').html(new Date().toLocaleString());
            };

        // END - widget specific code
        //////////////////////////////////////////////////////

        // respect the environment; give back the $ and reset the
        // global jQuery object
        jQuery.noConflict();
        if (oldJQ) window.jQuery = oldJQ;

    })(jQuery); // <-- pass in the jQuery that we embedded above

})();