JavaScript - Combine Javascript Files
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 Similar TutorialsHi! 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 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] Right now this javascript shopping cart works to 1. charge shipping based on the item, 2. the destination country, 3. it combines shipping for a quantity over 1 of the SAME item. Each item has 2 different possible shipping charges. I am trying to get the javascript to check the shopping cart to see what item in the cart has the highest possible shipping charge, charge that amount to that item, and charge the lowest possible shipping charge on all other items in the cart. If item A is purchased alone shipping is $5.00. If purchased with item B, which costs $10.00 to ship alone, the $10.00 is charged for item B and only $3.00 for item A. Because item B had the higher shipping charge at a quantity of one. I have tried adding various things like me.items[current], item.shipping, me.shipping, this.shipping, shipping_Cost, and other things next to the second && in the part of the script that shows the country. I have also tried adding && if (me.whatever) and && if (item.whatever) and similar things at the beginning of the script next to if (this.country). I have found the parts of the script that pertain to cart items and to updating the shopping cart. Now I am stuck. The javascript is in 2 parts. One part goes in the item page, which I will post first. The second part goes in an external javascript file which I will post at the bottom. In between there is the part that shows the shopping cart. It isn't part of the javascript. Code: <script type="text/javascript" src="simpleCart.js"></script> <script type="text/javascript"> <!-- simpleCart.checkoutTo = PayPal; simpleCart.email = "my Paypal email address"; simpleCart.cartHeaders = ["Name" , "Price" , "Quantity" , "remove" ]; CartItem.prototype.shipping=function(){ // we are using a 'country' field to calculate the shipping, // so we first make sure the item has a country if(this.country){ if( this.country == 'United States' && this.quantity == '1'){ return this.quantity*5.00; } else if( this.country == 'United States' && this.quantity >= '2') { return this.quantity*3.00; } else if( this.country == 'Belgium' && this.quantity == '1') { return this.quantity*12.00; } else if( this.country == 'Belgium' && this.quantity >= '2') { return this.quantity*9.00; else { return this.quantity*0.00; } } else { // use a default of $0.00 per item if there is no 'country' field return this.quantity*0.00; } } // --></script> Code: <div style="display:block;"></div> <div>SHOPPING CART</div> <div class="cartHeaders"></div><br><br><br> <div class="simpleCart_items"></div> <div id="totals"> Item Total: <span class="simpleCart_total"></span><br>Shipping Total: <span class="simpleCart_shippingCost"></span><br>Tax: <span class="simpleCart_taxCost"></span><br>Final Total: <span class="simpleCart_finalTotal"></span> </div> <br><br><br><br> <br><br> <a href="javascript:;" class="simpleCart_empty">Empty Shopping Cart</a><br><br> <a href="javascript:;" class="simpleCart_checkout">Checkout Through Paypal</a> </div></div> separate javascript file is here http://simplecartjs.com/documentation.html So, I have a dynamic PHP file on my server. I want to make it so browsers can take the code I provide and paste it in an .html, .php, or .asp file, and it'll display across the board. The file would need to be included, unless someone thinks there's a better way of doing this? The only example I could think of would be Google Adsense's code? But I'm not sure. I am doing a program to teach pre-schoolers on how to use the keyboard. If there any possible if I press the arrow up key, It will then show a excellent swf, that I have make. if wrong if will come out try again swf using javascript. please help me. im stuck. hi all, i'm a relatively new user to javascript. i'm supposed to use javascript to search through a folder that contains many excel files. the search term is obtained from a front end html form, javascript gets that value, search every single excel file in the folder and see which file has a cell that matches the search terms. I currently know (sort of) how to search through 1 file. but how do I search through many files? and from what i see from the searching of 1 file, it takes a few seconds to open and close the excel file (located on a network drive). which means it will take a fair bit of time to cycle through 97 excel files. Is there like any searching algorithm to speed up the process? Howdy all. I have Win 7, IE9. I have a HTML file on my hard drive, with Javascript within. When I load the page, it keeps popping up Do u want to allow this content, I have to click to allow. I want to stop this, and after doing some searching I found the setting in Internet Options, Advanced - "Allow active content to run in files on my computer". Perfect. Doesnt work. When i check this box, the page loads without the warning, but then the Javascript just doesnt work. Getting quite annoying, because this file is my home page. Any help would be great! I have an external Javascript file that only works when I put: Code: <script type="text/javascript" src="external.js"></script> at the end of the HTML page. Does anyone know why it won't work in the head of the page? Thanks I want to use HTML5's audio coding similar to the one below: Code: var audioElement = document.createElement('audio'); audioElement.setAttribute('src', 'horse.ogg'); audioElement.play(); In order to play sound files depending on the input. What I'm working on is a text-to-speech webapplication. What I'd need to happen is for there to be an input and then allow the user to type anything into the input, so if they type in: Hello, how are you doing? Javascript or PHP will recognize each character and translate it into an audio sequence. In example: It'd detect the "H" in hello and play sound file "H.ogg" It'd then detect the "E" in hello and play sound file "E.ogg" I know there must be an easy way to do this. Could somebody help me please to explain what I'm doing wrong.... a have this html file with references to some javascripts (datagrid from http://www.datatables.net) and this html file work ok..I mean javascripts a css styling works with table... but when I call this page by ajax and callback (this html page) is forward back into another div , table doesn't work ....just data from page but now functionality from javascript and css styling... how should I force callback result to use javascript and css? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/media/images/favicon.ico"> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml"> <style type="text/css" media="screen"> @import "media/css/demo_page.css"; @import "media/css/demo_table.css"; @import "http://www.datatables.net/media/css/site_jui.ccss"; @import "media/css/demo_table_jui.css"; @import "media/css/themes/base/jquery-ui.css"; @import "media/css/themes/smoothness/jquery-ui-1.7.2.custom.css"; /* * Override styles needed due to the mix of three different CSS sources! For proper examples * please see the themes example in the 'Examples' section of this site */ .dataTables_info { padding-top: 0; } .dataTables_paginate { padding-top: 0; } .css_right { float: right; } #example_wrapper .fg-toolbar { font-size: 0.8em } #theme_links span { float: left; padding: 2px 10px; } </style> <script type="text/javascript" src="media/js/complete.js"></script> <script src="media/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="media/js/jquery.dataTables.min.js" type="text/javascript"></script> <script type="text/javascript" src="media/js/jquery.dataTables.editable.js"></script> <script src="media/js/jquery.jeditable.js" type="text/javascript"></script> <script src="media/js/jquery-ui.js" type="text/javascript"></script> <script src="media/js/jquery.validate.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready( function () { $('#example').dataTable().makeEditable({ sUpdateURL: "update.php", sDeleteURL: "delete.php" }); } ); </script> </head> <body id="index" class="grid_2_3"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> <thead> <tr> <th> ID</th> <th> user</th> <th> password</th> <th> first</th> <th> last</th> <th> company</th> </tr> </thead> <tbody> <tr class="even_gradeA" id="1"> <td> 1 </td> <td> XY </td> <td> passwoed </td> <td> Ja </td> <td> jajovic </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="2"> <td> 2 </td> <td> jojo </td> <td> fa25af5301e2dda1fddea740200aa10ab6c70d86 </td> <td> jojo </td> <td> jojovicko </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="3"> <td> 3 </td> <td> kuk </td> <td> d588aebb93e3adf70eac1fb479d6d53f9dc21816 </td> <td> kuk </td> <td> kukovic </td> <td> 3 </td> </tr> <tr class="even_gradeA" id="10"> <td> 10 </td> <td> admin </td> <td> f865b53623b121fd34ee5426c792e5c33af8c227 </td> <td> admin </td> <td> adminovic </td> <td> 3 </td> </tr> </tbody> </table><button id="btnDeleteRow">Delete</button> </body> </html> Hi all- I currently use a javascript seacrh string on my website that searchs all folders (directories) and gives results on a html page. My problem is that some folders (or sub directories) are not being found when I type into the form search box. Does anyone know why this might be happening? here is the script im using <script language="JavaScript" type="text/javascript">function OnSearchSubmit(){var b_return=true;if (document.form_search.sw){for(var i=0;i<document.form_search.sw.value.length;i++){if (document.form_search.sw.value.charAt(i)!=" ") {lh="searchresult.html?sw="+encodeURIComponent(document.form_search.sw.value);b_return=false;break;} }}if (b_return) return;window.open(lh,"_self");}</script> thanks! I have been working on a few budget scripts that I can access from the web in using HTML. My problem is that when variable values change I need to change these values in all of the HTML files on the server. I know that there is a way to declare global variables in a single file and use those values in another file but I have not been able to find any information that tells me exactly how to do this. I have tried to put it together on my own using what little informaiton I have been able to find but have not been able to get this to work. Is there a more detailed referance that I can find somewhere or does anyone know what steps I need to take to make this happen?
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 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> 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? 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! Can anyone tell me how I can combine multiple sheets into one?
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; } } } } |