JavaScript - Combine Functions Into One Function?
Note: major noobage here I'm sure... but can't seem to figure this out...
How do I make these three functions into one script? Much love if you can help! Code: <script type="text/javascript"> setTimeout('yourFunction();', 2500); function yourFunction(){ document.getElementById('hide').style.display='block'; } </script> <script type="text/javascript"> setTimeout('yourFunction2();', 8000); function yourFunction2(){ document.getElementById('hide').style.position='fixed'; } </script> <script type="text/javascript"> setTimeout('yourFunction3();', 8500); function yourFunction3(){ document.getElementById('hide').style.margin='0 -310px'; } </script> <script type="text/javascript"> setTimeout('yourFunction4();', 15500); function yourFunction4(){ document.getElementById('hide').style.margin='0 610px'; } </script> Similar TutorialsI am try to make a form that appears to be multi page. I am trying to use a button to hide one div and display another at the same time my script is head Code: <script language=javascript type='text/javascript'> function hidediv(pass) { var divs = document.getElementsByTagName('div'); for(i=0;i<divs.length;i++){ if(divs[i].id.match(pass)){//if they are 'see' divs if (document.getElementById) // DOM3 = IE5, NS6 divs[i].style.visibility="hidden";// show/hide else if (document.layers) // Netscape 4 document.layers[divs[i]].display = 'hidden'; else // IE 4 document.all.hideShow.divs[i].visibility = 'hidden'; } } } function showdiv(pass) { var divs = document.getElementsByTagName('div'); for(i=0;i<divs.length;i++){ if(divs[i].id.match(pass)){ if (document.getElementById) divs[i].style.visibility="visible"; else if (document.layers) // Netscape 4 document.layers[divs[i]].display = 'visible'; else // IE 4 document.all.hideShow.divs[i].visibility = 'visible'; } } } </script> body Code: <form name="PublicOrderPage" action="save_client_information.php" onsubmit="return validateForm()" method="post"> <div id="div1" style="width:600px; height: auto;background: yellow;"> <table width="600" border="0"> <tr> <legend><h3 style="padding-left:172.5px;">Required Client Information</h3></legend> </tr> <tr> <td style="padding-left:25px;"><b>Name:</b></td> <td><input type="text" name="client_name" id="client_name" value="<?php echo $_POST['client_name']; ?>" /></td> <td style="padding-left:25px;"><b>Home Phone:</b></td> <td><input type="text" name="client_home_phone" id="client_home_phone" value="<?php echo $_POST['client_home_phone']; ?>" /></td> </tr> </table> <br/> <table width="270" border="0"> <tr> <td style="padding-left: 180px;"><b>Email:</b></td> <td><input type="text" name="client_email" id="client_email" value="<?php echo $_POST['client_email']; ?>" /></td> </tr> </table> <br/> <table> <tr> <td style="padding-left:280px;"><input name="save_client_info" type="button" value="Next" onclick="hidediv('1');shwodiv('2');" > </td> </tr> </table> </div> <div id="div2" style="width:600px; height: auto;background: yellow; "> <table width="600" border="0"> <tr> <legend><h3 style="padding-left:172.5px;">Required Site Information</h3></legend> </tr> <tr> <td style="padding-left:25px;"><b>Site Street:</b></td> <td><input type="text" name="site_street" id="site_street" value="<?php echo $_POST['site_street']; ?>" /></td> <td style="padding-left:25px;"><b>Site City:</b></td> <td><input type="text" name="site_city" id="site_city" value="<?php echo $_POST['site_city']; ?>" /></td> </tr> </table> <br/> <legend><h3>Inspection Type</h3></legend> <table width="270" border="0"> <table width="602" border="0"> <tr> <td width="252"><input type="checkbox" name="cb_full_home" id="cb_full_home" <?php if ($_POST['cb_full_home']) echo 'checked="checked"'; ?> /> Full Home</td> <td width="150"><input type="checkbox" name="cb_4_point" id="cb_4_point" <?php if ($_POST['cb_4_point']) echo 'checked="checked"'; ?> /> 4 Point</td> </tr> <tr> <td ><input type="checkbox" name="cb_condominium" id="cb_condominium" <?php if ($_POST['cb_condominium']) echo 'checked="checked"'; ?> /> Condominium</td> <td ><input type="checkbox" name="cb_wind_mit" id="cb_wind_mit" <?php if ($_POST['cb_wind_mit']) echo 'checked="checked"'; ?> /> Wind Mit</td> </tr> <tr> <td ><input type="checkbox" name="cb_roof_cert" id="cb_roof_cert" <?php if ($_POST['cb_roof_cert']) echo 'checked="checked"'; ?> /> Roof Cert</td> <td ><input type="checkbox" name="cb_drywall" id="cb_drywall" <?php if ($_POST['cb_drywall']) echo 'checked="checked"'; ?> /> Drywall</td> </tr> <tr> <td><input type="checkbox" name="cb_reinspect" id="cb_reinspect" <?php if ($_POST['cb_reinspect']) echo 'checked="checked"'; ?> /> Re-Inspect</td> <td><input type="checkbox" name="cb_followup" id="cb_followup" <?php if ($_POST['cb_followup']) echo 'checked="checked"'; ?> /> Follow-Up</td> </table> <img src="CaptchaSecurityImages.php" /> Security Code: <input id="security_code" name="security_code" type="text" /> <br /> <input name="save_client_info" type="submit" value="Save" /> </div> </form> When the next button is used I would Like to Hide Div1 And Display Div2 so that it looks as if it is a new page. Any help would be greatly appreciated. Hi everyone, i thought about following code snippet: Code: var newfunc = function() { //... } func = (function (oldfunc,newfunc) { return function () { oldfunc(); newfunc(); } }(func || function(){},newfunc)) There is a function "func" and with the above method i want to add a new function "newfunc" to this function, so when i call "func" in the futur, both functions will be executed. It works good, but suppose i want to add multiple functions to func, each time with the described method...could there be a problem with the stack? As far as i understand, the program creates something like a wrapper-function each time, that contains the two functions it combines. So in the case of adding 3 functions, a call of "func" would lead to this: call "wrapper 2", call "wrapper 1", call func1, call func2, call func3, call func 4. The really poor graphic should illustrate what i mean __________ F1|....|....| __|W1|....| F2|....|....| __|___|W2| ...|F3 |....| ...|___|___| ..........| F4| ..........|___| Has anyone an idea, if my thoughts on that are correct oder if this behaviour could be a problem? And is there probably a better way to combine functions, so that all functions would be in one column? Thanks and Greetings! moon-safari Hi, I would like to do something like this: Code: function searchLocations(count) { var found = false; var input = document.getElementById('autocomplete').value; var inp = input.toLowerCase(); var count = 0; for (var j = 0; j < gmarkers.length; j++) { gmarkers[j].hide(); var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); count++; } } if (count==1) myclick(j); if (count>1) centerZoom(); if ( ! found ) alert("No matches found. Please check your spelling or refine your search."); } on this page here, but the functions - myclick(j); and centerZoom(); aren't getting called. I tried it with switches here, but that only made things worse. I know the functions work because if I put them two } up, they get called, but that takes them out of the if statements. Those if (count...) statements have to be where they are so that "count" will get the right value. Any ideas? Is it possible to make a variable available to other functions outside a function So to make it global from within a function without using a callback Code: function() { var something = 'hello'; } function(something) { document.write(something); } something like that possible?? Hello, Our website is built in ASP.NET and uses a content management system. The CMS came with a wealth of JavaScript files and I decided to use one of these files for form validation. Although the file is over 2,300 lines, from what I can tell it is supposed to return true if the form is valid and false otherwise. The problem is that a function inside that file seems to get to a certain point, and somehow quit and return true no matter if the form is valid or not. I am calling this JS from an ASP.NET button control. When the button is clicked, a JS function ValidateForm(document.forms[0]) is called. My ValidateForm function calls another function inside the JS file (which calls another, and another...). No matter what, when that second function is called and executed, code execution stops at some point and the form submits (postbacks). I can see that the validation is working just before the postback, but it is not preventing the form from being submitted, and it also stops executing any code after it. Here is my code: ASP: Code: <asp:Button ID="SubmitBtn" runat="server" Text="Submit Form" CausesValidation="false" CssClass="submit_button" OnClientClick="FmValidate(document.forms[0]); return false;" OnClick="SubmitBtn_Click" /> My Javascript: Code: function FmValidate(formObj) { var strError = ''; var e = null; if (strError == '' && 'function' == typeof design_validateHtmlForm) { alert('before'); // this line causes execution to stop - located in external JS file // code states "Returns first invalid element, or null." e = design_validateHtmlForm(formObj); alert("e is " + e); if (e) { strError = e.title; } return false; } } In my ASP.NET button, changing the OnClientClick method to "return false" will prevent form submission, but "return FmValidate(formObj);" will not if that function calls design_validateHtmlForm(formObj). I receive the message box saying "before" but I never receive the second one. I have debugged using Fire bug, but the code seems to cycle through each element on the page and stepping through the code is not realistic (I have done so for 20-minute stretches). I am wondering if anyone has any ideas what code I could look for that would stop execution and return true no matter what, or how I could begin debugging this monster. Hey all, I am confused about the true difference between the two below examples. Code: first example: // Demonstrating a problem with closures and loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = function() { document.write(theItem + “ < br / > ”); } } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed. I have a couple of problems with this example: 1) I thought a closure is a function that is returned - the inner function is not returned above. 2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function. 3) The guy says the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment. Second example: Code: // A correct use of closures within loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); function writeItem(word) { return function() { document.write(word + “ < br / > ”); } } // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = writeItem(theItem); } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray. QUESTION: This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved? I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index? Thanks for response I am trying to display some images in, say, 500ms intervals, but I want to loop through images, so I use a for loop and setTimeouts and function calls... Code: for (i=0;i<=5;i++) { setTimeout(DisplayTheImage, 500); } (a var that increments the image like image[x] is somewhere else) but I think all I accomplish is that while the above code calls the function 5 times alright, all five function calls occur simultaneously. Right? Eh, I want the function to be called 5 times, but at five different times, namely in 500ms intervals. I thought the function would wait to finish (500 ms) then another call and so on. How can I do that? Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. Is there a way to check for A , else check for B? The code in Red is what I need to put together. [This is an event calendar. problem is it double prints the event dates.Original problem is here. http://www.codingforums.com/showthread.php?t=186671] Thanks for looking! Code: /* Function List: yearly(calendarDay) Creates the yearly calendar, highlighting the date specified in the calendarDay parameter. writeMonthCell(calendarDay, currentTime) Writes the yearly table cell containing a monthly calendar. writeMonth(calendarDay, currentTime) Creates the calendar table for the month specified in the calendarDay parameter. The currentTime parameter stores the time value of the current date. writeMonthTitle(calendarDay) Writes the month name in the monthly table writeDayNames() Writes the weekday title rows in the calendar table daysInMonth(calendarDay) Returns the number of days in the month from calendarDay writeMonthDays(calendarDay, currentTime) Writes the daily rows in the monthly table, highlighting the date specified in the currentTime parameter. writeDay(weekDay, dayCount, calendarDay, currentTime) Write the opening and close table row tags and the table cell tag for an individual day in the calendar. */ function yearly(calDate) { if (calDate == null) calendarDay=new Date(); else calendarDay = new Date(calDate); var currentTime = calendarDay.getTime(); var thisYear = calendarDay.getFullYear(); document.write("<table id='yearly_table'>"); document.write("<tr><th id='yearly_title' colspan='4'>"+thisYear+"</th></tr>"); var semMonth=calendarDay.getMonth(); var monthNum; if (semMonth <6) { monthNum = -1 } else { monthNum = 5; } for (var i=1; i<=2; i++) { document.write("<tr>"); for (var j=1; j<=3; j++) { monthNum++; calendarDay.setDate(1); calendarDay.setMonth(monthNum); writeMonthCell(calendarDay, currentTime); } document.write("</tr>"); } document.write("</table>"); } function writeMonthCell(calendarDay, currentTime) { document.write("<td class='yearly_months'>"); writeMonth(calendarDay, currentTime); document.write("</td>"); } function writeMonth(calendarDay, currentTime) { document.write("<table class='monthly_table'>"); writeMonthTitle(calendarDay); writeDayNames() writeMonthDays(calendarDay, currentTime); document.write("</table>"); } function writeMonthTitle(calendarDay) { var monthName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var thisMonth=calendarDay.getMonth(); document.write("<tr>"); document.write("<th class='monthly_title' colspan='7'>"); document.write(monthName[thisMonth]); document.write("</th>"); document.write("</tr>"); } function writeDayNames() { var dayName = new Array("S", "M", "T", "W", "R", "F", "S"); document.write("<tr>"); for (var i=0;i<dayName.length;i++) { document.write("<th class='monthly_weekdays'>"+dayName[i]+"</th>"); } document.write("</tr>"); } function daysInMonth(calendarDay) { var thisYear = calendarDay.getFullYear(); var thisMonth = calendarDay.getMonth(); var dayCount = new Array(31,28,31,30,31,30,31,31,30,31,30,31); if ((thisYear % 4 == 0)&&((thisYear % 100 !=0) || (thisYear % 400 == 0))) { dayCount[1] = 29; } return dayCount[thisMonth]; } function writeMonthDays(calendarDay, currentTime) { var weekDay = calendarDay.getDay(); document.write("<tr>"); for (var i=0; i < weekDay; i++) { document.write("<td></td>"); } var totalDays = daysInMonth(calendarDay); for (var dayCount=1; dayCount<=totalDays; dayCount++) { calendarDay.setDate(dayCount); weekDay = calendarDay.getDay(); writeDay(weekDay, dayCount, calendarDay, currentTime); } document.write("</tr>"); } function writeDay(weekDay, dayCount, calendarDay, currentTime) { //my var lines .ID and events. var ID = ( calendarDay.getFullYear() * 10000 + calendarDay.getMonth() * 100 + 100 + calendarDay.getDate() ); // This is where you put in the appointments. follow pattern [YYYYMMDD,"start time - End time : message"], var events = [ [20100130,"4pm - 10 pm : Beer fest"], [20100320,"10am - 6 pm : the next fest"], [20100425,"8am - 2 pm : the other fest"], ]; //end of events // end of my var declaration if (weekDay == 0) document.write("<tr>"); // this code is to write my buggy events. IDs are fine.events are the bug //my for line for(var sep = 0; sep < events.length; sep++) { //end of my for line // writes the events to the date if (events[sep][0] == ID) { document.write("<td id="+ID+" class='monthly_dates'><div class='eventday' title='" + events[sep][1] + "'>"+dayCount+"</div></td>"); } } // my } for, for var sep //end of my buggy lines //normal day writing if (calendarDay.getTime() == currentTime) { document.write("<td class='monthly_dates' id='today'>"+dayCount+"</td>"); } else { document.write("<td id="+ID+" class='monthly_dates'>"+dayCount+"</td>"); } if (weekDay == 6) document.write("</tr>"); } I have this java function that will show the div based on whatever u select. Each div is a different set of form fields. My problem is if you change 1/2 and go to the other selection, it'll submit BOTH. not just the one you currently switched to. So if i can modify this fucntion to add the ability to either clear the divs not being used (will a clear'd div still submit data?), or reset.fields (would that do it?). I am new to javascript, thanks in advance guys Here is my code for the change div's: Quote: <script type="text/javascript"> $(document).ready(function(){ $('#3_form').hide(); $('#4_form').hide(); $('#axd_form').hide(); $('#ht_form').hide(); $("#thechoices").change(function(){ if(this.value == 'all') {$("#boxes").children().show();} else {$("#" + this.value).show().siblings().hide();} }); $("#thechoices").change(); }); </script> And here is the code to clear the div: Quote: <script type="text/javascript"> function clearDiv() { document.getElementById("4_form").innerHTML=""; } </script> So if #3_form --> clear all other div's. (4_form, axd_form, and ht_form) I just need to clear the div that isnt currently selected - idk what the best practice is for that. It must not allow other fields in other div's to be submitted in the form. So basically just clear the fields. would clearing a div do that? thanks! Hi, well i have heard alot about combining script but never did that as i always had doubts about the proper method of doing it, as these days following standards matters alot for SEO. I want to combine scripts together into one file, lets take an example i will provide 3 scripts 1- Code: <script type='text/javascript'> $(document).ready(function () { // find the elements to be eased and hook the hover event $('div.jimgMenu ul li a').hover(function() { // if the element is currently being animated if ($(this).is(':animated')) { $(this).addClass("active").stop().animate({width: "310px"}, {duration: 450, easing: "easeOutQuad", complete: "callback"}); } else { // ease in quickly $(this).addClass("active").stop().animate({width: "310px"}, {duration: 400, easing: "easeOutQuad", complete: "callback"}); } }, function () { // on hovering out, ease the element out if ($(this).is(':animated')) { $(this).removeClass("active").stop().animate({width: "83.7px"}, {duration: 400, easing: "easeInOutQuad", complete: "callback"}) } else { // ease out slowly $(this).removeClass("active").stop(':animated').animate({width: "83.7px"}, {duration: 450, easing: "easeInOutQuad", complete: "callback"}); } }); }); </script> 2- Code: <script type="text/javascript"> (function($) { $.fn.sorted = function(customOptions) { var options = { reversed: false, by: function(a) { return a.text(); } }; $.extend(options, customOptions); $data = $(this); arr = $data.get(); arr.sort(function(a, b) { var valA = options.by($(a)); var valB = options.by($(b)); if (options.reversed) { return (valA < valB) ? 1 : (valA > valB) ? -1 : 0; } else { return (valA < valB) ? -1 : (valA > valB) ? 1 : 0; } }); return $(arr); }; })(jQuery); $(function() { var read_button = function(class_names) { var r = { selected: false, type: 0 }; for (var i=0; i < class_names.length; i++) { if (class_names[i].indexOf('selected-') == 0) { r.selected = true; } if (class_names[i].indexOf('segment-') == 0) { r.segment = class_names[i].split('-')[1]; } }; return r; }; var determine_sort = function($buttons) { var $selected = $buttons.parent().filter('[class*="selected-"]'); return $selected.find('a').attr('data-value'); }; var determine_kind = function($buttons) { var $selected = $buttons.parent().filter('[class*="selected-"]'); return $selected.find('a').attr('data-value'); }; var $preferences = { duration: 800, easing: 'easeInOutQuad', adjustHeight: 'dynamic' }; var $list = $('#data'); var $data = $list.clone(); var $controls = $('ul#gamecategories ul'); $controls.each(function(i) { var $control = $(this); var $buttons = $control.find('a'); $buttons.bind('click', function(e) { var $button = $(this); var $button_container = $button.parent(); var button_properties = read_button($button_container.attr('class').split(' ')); var selected = button_properties.selected; var button_segment = button_properties.segment; if (!selected) { $buttons.parent().removeClass('selected-0').removeClass('selected-1').removeClass('selected-2'); $button_container.addClass('selected-' + button_segment); var sorting_type = determine_sort($controls.eq(1).find('a')); var sorting_kind = determine_kind($controls.eq(0).find('a')); if (sorting_kind == 'all') { var $filtered_data = $data.find('li'); } else { var $filtered_data = $data.find('li.' + sorting_kind); } if (sorting_type == 'size') { var $sorted_data = $filtered_data.sorted({ by: function(v) { return parseFloat($(v).find('span').text()); } }); } else { var $sorted_data = $filtered_data.sorted({ by: function(v) { return $(v).find('strong').text().toLowerCase(); } }); } $list.quicksand($sorted_data, $preferences, function () { $(this).tooltip (); } ); } e.preventDefault(); }); }); var high_performance = true; var $performance_container = $('#performance-toggle'); var $original_html = $performance_container.html(); $performance_container.find('a').live('click', function(e) { if (high_performance) { $preferences.useScaling = false; $performance_container.html('CSS3 scaling turned off. Try the demo again. <a href="#toggle">Reverse</a>.'); high_performance = false; } else { $preferences.useScaling = true; $performance_container.html($original_html); high_performance = true; } e.preventDefault(); }); }); </script> 3- Code: <script type='text/javascript'> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-15016456-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> I want to add them to one file and then yes i am going to make it external. Here i have a few questions: 1- Can any type of scripts be added together? 2- Is there a general rule of doing this combination of scripts (e-g remove the <script> tags from start and end of all then give spaces between each and you are done). 3- Should one use JS compressors? if yes, what are advantages and disadvantages of doing so? I asked a few question together as i don't want to spam this forum ^_^ anyway these all question are related to my topic Can anyone tell me how I can combine multiple sheets into one?
My site loads too many javascript files and it takes much time to load page. I would like to reduce the number of http requests and combine all javascript files into one file. What is the best way for it? Will it work if I just copy whole code from all files and paste into one or anything else is needed? Thanks I am new to using Javascript. Can someone help me combine these two codes? I can't get it to work. [code] body {background-color: #FFFFee;} .c { position: absolute; font-size: 1px; background:red; height: 2px; width: 2px; } .d { position: absolute; font-size: 1px; background:blue; height: 2px; width: 2px; } </style> </head> <body> <script language="javascript"> var i,y,x,y1; for (i=1; i<600; i++) { y=150-100*Math.sin(i/50); y1=150-100*Math.cos(i/50); x=i+50; document.write("<span class='c' style='left:"+x+";top:"+y+";'></span>"); document.write("<span class='d' style='left:"+x+";top:"+y1+";'></span>"); } [code] with this one. [code] .moveimage { position:absolute; left:20; top:50; z-index:2; } </style> <script language="JavaScript"> var fishLeft = 20; var imgWidth = 106; function moveFish() { var elem = document.getElementById("myDiv"); fishLeft+=4; if(fishLeft > document.body.clientWidth + (imgWidth / 2)) fishLeft = imgWidth / 2; elem.style.left = fishLeft; window.status= fishLeft ; setTimeout("moveFish()", 100); } </script> <title></title> </head> <body> <br> <div id="myDiv" class="moveImage"><img src="fish1.gif"></div> <br><br><br><br><br><br><br><br><br> <input type="button" value="Move Fish" onClick="moveFish()" ID="Button1" NAME="Button1"> [code] Hi! I'm trying to cmbine 4 .js file into one unique file. I'm getting some troubles because jquery.singlePageNav.js seems not to work. Can someone help me to combine these 4 files? Thank you js.rar Hi! What I really mean is how can you combine the effects from two plugins. Subject line only gives you so much to work with. I'm trying to use the query.corner.js plugin and the gradient (jquery.gradient.js & jquery.dimensions.js) plugins to get a rounded container that has a gradient applied to it. I've tried a few different things like putting a container withing a container and applying one plugin to one and the other to the remainder. No luck! |= Here's the code I'm playing with: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> JQuery combo plugins </title> <style type="text/css"> div.main { background:#0000FF;height:400px;width:400px;margin:auto;font-size:2em;text-align:center;} .main p {padding:20px;} </style> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="js/jquery.corner.js"></script> <script type="text/javascript" src="/js/jquery.gradient.js"></script> <script type="text/javascript" src="/js/jquery.dimensions.js"></script> <script type="text/javascript"> $(function(){ $('div.main').corner("20px"); }); </script> <script type="text/javascript"> $(function() { $('.gmain').gradient({ from: '0000FF', to: 'FFFFFF', direction: 'horizontal', position: 'verticle', }); }); </script> </head> <body> <div class="main"> <div class="gmain"> <p>Hi There!</p> </div> </div> </body> </html> I attached the js plugins and just changed the extension from js to txt so I could attach them. I did NOT attach the jquery script since I figure that is pretty common. Corner -> jquery.corner.txt Dimension -> jquery.dimensions .txt Gradient -> jquery.gradient.txt Thanks for your help! I have these two codes which both involve sockets. I can't figure out how to combine the smtp code into my first code. If you look at the first code where it prints out "you are at picture A" it is here were i want to be able to send an email. I am quite puzzled as how to combine the two codes to make it work. Any help would be greatly appreciated. First Code: Code: import java.io.*; import java.net.*; import java.util.Scanner; import java.io.File; public class Combo2 { public static void main(String[] args) throws IOException { Socket kkSocket = null; PrintWriter out = null; BufferedReader in = null; File yourFile = new File("outs.txt"); yourFile.delete(); try { kkSocket = new Socket("192.168.33.39", 12000); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: Adam."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: Adam."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { if (fromServer.equals("Bye.")) break; try{ // Create file FileWriter fstream = new FileWriter("outs.txt", true); BufferedWriter outs = new BufferedWriter(fstream); outs.write( fromServer); outs.newLine(); //Close the output stream outs.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } FileReader fin = new FileReader("outs.txt"); Scanner src = new Scanner(fin); while (src.hasNext()) { Double Tag = (src.nextDouble()); Double x = (src.nextDouble()); Double z = (src.nextDouble()); Double y = (src.nextDouble()); if ((x<=19.92) && (y<=6.1543) && (y>=4.22)) { System.out.println("You are at Picture A"); } else if ((x<=19.92) && (y<=3) && (y>=1)) { System.out.println("You are at Picture B"); } else { System.out.println("Nope"); } } } out.close(); in.close(); stdIn.close(); kkSocket.close(); } } SMTP code: Code: import java.io.*; import java.net.Socket; public class Emailer { public static void main(String[] args) throws Exception { String results = send("mailhost.computing.dcu.ie", 25, "adam.keaney2@mail.dcu.ie", "adam.keaney2@mail.dcu.ie", "Test Email", "<b>You got mail!</b>"); System.out.println(results); } /* Sends an email. * @return The full SMTP conversation as a string. */ public static String send( String host, int port, String to, String from, String subject, String message) throws Exception { // Save the SMTP conversation into this buffer (for debugging) StringBuffer buffer = new StringBuffer(); try { // Connect to the SMTP server running on the local machine. Socket smtpSocket = new Socket(host, port); // send commands TO the server with this DataOutputStream output = new DataOutputStream(smtpSocket.getOutputStream()); // recieve responses FROM the server with this BufferedReader input = new BufferedReader( new InputStreamReader( new DataInputStream(smtpSocket.getInputStream()))); try { // Read the server's hello message read(input, buffer); // Say hello to the server send(output, "HELO localhost.localdomain\r\n", buffer); read(input, buffer); // Who is sending the email send(output, "MAIL FROM: " + from + "\r\n", buffer); read(input, buffer); // Where the mail is going send(output, "RCPT to: " + to + "\r\n", buffer); read(input, buffer); // Start the message send(output, "DATA\r\n", buffer); read(input, buffer); // Set the subject send(output, "Subject: " + subject + "\r\n", buffer); // If we detect HTML in the message, set the content type so it displays // properly in the recipient's email client. if (message.indexOf("<") == -1) { send(output, "Content-type: text/plain; charset=\"us-ascii\"\r\n", buffer); } else { send(output, "Content-type: text/html; charset=\"us-ascii\"\r\n", buffer); } // Send the message send(output, message, buffer); // Finish the message send(output, "\r\n.\r\n", buffer); read(input, buffer); // Close the socket smtpSocket.close(); } catch (IOException e) { System.out.println("Cannot send email as an error occurred."); } } catch (Exception e) { System.out.println("Host unknown"); } return buffer.toString(); } /** * Sends a message to the server using the DataOutputStream's writeBytes() method. * Saves what was sent to the buffer so we can record the conversation. */ private static void send(DataOutputStream output, String data, StringBuffer buffer) throws IOException { output.writeBytes(data); buffer.append(data); } /** * Reads a line from the server and adds it onto the conversation buffer. */ private static void read(BufferedReader br, StringBuffer buffer) throws IOException { int c; while ((c = br.read()) != -1) { buffer.append((char) c); if (c == '\n') { break; } } } } Hi, I have a form where dob is generated using 3 select boxes, 1 for day, month and year. My output needs to be in the form dob=dd-mm-yyyy rather than day=dd, month=mm and year=yyyy. It has been suggested that i do the following: "On submit button click, use JS to create a hidden input (Q5) in the form and assign its value, then disable the day, month, and year fields so they are not submitted." Does anyone know how to do this? Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks |