tags:

views:

47

answers:

3

I'm incredibly new to jQuery and am wondering if my code will work when deployed to the world and not tested locally.

I have a pretty substantial block of code that populates some form elements among (several) other things. When I place this code into the top of my script just after the document ready portion, it doesn't work. If I place it at the bottom of the script it does work. This makes me a little concerned that the info won't load properly when the page is on the server.

var headBkg = $('#header').css('background-image'); //gets the background image url
$('#header_imgURL').attr( 'value', headBkg ); //populates a form field with the url for later use

What do I need to know about this to be sure I'm not going to implement something that doesn't work on a production server? How can I time this type of thing to work?

$(document).ready(function() {
            // Begin Modal Window //
            // get the height and width of the page
            var window_width = $(window).width();
            var window_height = $(window).height();
            //vertical and horizontal centering of modal window(s)
            /*we will use each function so if we have more then 1
            modal window we center them all*/
            $('.modal_window').each(function(){

                //get the height and width of the modal
                var modal_height = $(this).outerHeight();
                var modal_width = $(this).outerWidth();
                //calculate top and left offset needed for centering
                var top = (window_height-modal_height)/2;
                var left = (window_width-modal_width)/2;
                //apply new top and left css values
                $(this).css({'top' : top , 'left' : left });

            });


            $('.activate_modal').click(function(){                                  
                //get the id of the modal window stored in the name of the activating element

                var modal_id = [$(this).attr('name'), $(this).attr('id')];
                //var 


                // This is the original working code // var modal_id = $(this).attr('name');

                //alert($(this).attr('id'));

                //var theform = $(this).attr('id');
                //use the function to show it
                show_modal(modal_id);
            });

            $('#cancel').click(function(){
                //use the function to close it
                close_modal();
            });

            $('.close_modal').click(function(){
                //use the function to close it
                close_modal();
            });
        //});

        //THE FUNCTIONS
            function close_modal(){
                //hide the mask
                $('#mask').fadeOut(500);

                //hide modal window(s)
                $('.modal_window').fadeOut(500);
            }
            function show_modal(modal_id){
                //set display to block and opacity to 0 so we can use fadeTo
                $('#mask').css({ 'display' : 'block', opacity : 0});

                //fade in the mask to opacity 0.8
                $('#mask').fadeTo(500,0.7);

                //show the modal window
                $('#'+modal_id[0]).fadeIn(500);


                // Use this if statement to dertermine whether to serve up the upload or the other script

                if ( modal_id[1] == "backer")
                {   

                var jForm = $( "#uploadform" );    
                jForm.submit(function( objEvent ){
                    var jThis = $( this );
                    var strName = ("uploader" + (new Date()).getTime());
                    var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );
                    jFrame.css( "display", "none" );
                    jFrame.load(function( objEvent ){
                            var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];
                            var jBody = $( objUploadBody );
                            var objData = eval( "(" + jBody.html() + ")" )
                            var thumb = ('thumbnails/' + eval(jBody.html()));
                            var title = $("#image_title").val(); 
                            //Populates the title hidden field and
                            //will serve as a string for the naming convention
                            var alt = $("#image_alt").val();
                            // alt text could be the same as the title possibly...

                            // ----------- //
                            //Put an if statement to set the elments that need the preview image

                            $("#header").css("background", "url(" + thumb + ") no-repeat center");
                            $("#preview").attr("src", thumb);
                            $("#thebackgroundimage").attr("value", thumb);
                            $("#theimagetitle").attr("value", title );

                            // ----------- //
                    setTimeout(function(){
                            jFrame.remove();
                            },100);
                    });
                $( "body:first" ).append( jFrame );
                jThis
                    .attr( "action", "upload_act_single.cfm" )
                    .attr( "method", "post" )
                    .attr( "enctype", "multipart/form-data" )
                    .attr( "encoding", "multipart/form-data" )
                    .attr( "target", strName );
                });

            // End Image Upload //
                    // In the future this is poulated with the data from the ColdFusion query
                    $('#preview').attr("src", "images/cfr_footwear_header_bkg.jpg");


                }
            }

            // END of the Modal Window script //                   

            // Replace the background image on the header //
            // write this code when the cf query is ready to go //
            //<!---$("#header").css("background-image", "url(<cfoutput>#headerbg#</cfoutput>) no-repeat center"); --->//
            $("#header").css("background", "url(images/cfr_footwear_header_bkg.jpg) no-repeat center");


            //jQuery scroller for the FarmNews on the index page //                    
            $(function() {  
                $(".farmnews").jCarouselLite({  
                        vertical: true,  
                        visible: 4,  
                        auto:2500,  
                        speed:400,
                        hoverPause:true
                    });  
            });

            // jQuery scroller for the mid-page specials // 
            $(function() {  
                $(".slideshow").jCarouselLite({  
                        vertical: false,  
                        visible: 1,  
                        auto:4500,  
                        speed:1000,
                        easing:"easeinout",
                        hoverPause:true
                    });  
            });

            // This is to replace text in the input fields //
            $('.textbox').click(function() {
                if (this.value == this.defaultValue) {
                this.value = '';}
            });
            $('.textbox').blur(function() {
                if (this.value == '') {
                this.value = this.defaultValue;}
            });


            var headBkg = $('#header').css('background-image');
            var win1_img = [$('#window_one img').attr('src'), $('#window_one img').attr('title'), $('#window_one img').attr('alt') ]


            $('#header_imgURL').attr( 'value', headBkg );
            $('#win1_imgURL').attr('value', win1_img[0] );
            $('#win1_imgTitle').attr('value', win1_img[1]);
            $('#win1_imgAlt').attr('value', win1_img[2]);



        });

There's the whole shebang! It's still under development so please ignore my seeminly meaningless comments in places.

+3  A: 

It sounds like the script is executing before the elements exist in the DOM when you place it at the top of the file, after the $(document).ready(function() { ... }); code.

Why not place your code above in $(document).ready(function() { ... }); too?

You can test to see if it'll work using jsbin

Russ Cam
A: 

Is the foobar element loaded when you read the css atribute? Maybe if we see the entire script we can help you

Angel Aparicio
I've added the full code.
Ofeargall
+1  A: 

Javascript code is executed as soon as it is read by the browser. If you put your code at the beginning of the page, the javacript will refer to elements not present yet.

The solution is to execute the code only once the document has been fully processed. The jQuery idiom to do that is to put the code in

$(document).ready(function() {
  // your code goes here
});

or its shorthand

$(function() {
  // your code goes here
});

See this great tutorial for more details: http://www.rebeccamurphey.com/jqfundamentals/#N206EC

Mtgred
So, the full script does currently live inside the document ready function, which is why I thought it strange that the vars didn't load when at the top of the script. I figured when the doc.ready fired everything had a green light.I know some code can execute from the bottom up (actionscript), does javascript/jQuery load from the top down since it's on a page and being rendered by a browser? Sorry if that seems like a silly question.
Ofeargall