JavaScript - Modified Bubble Sort Function Javascript Help
Hi this is an assignment, ive been on it all night.
I have done the bubble sort function and have to modify it. I work out that if i could stop the amount of times it loops it would make it more efficient. To do this is would need to stop the loop when no swaps have been made on the full array.lenght-1. i have tried using booleans, false and true on the amount of swaps using a while loop instead of my first for loop, however it only loops nine times...ie only covering the array once,hence does not swap the full array. so i tried leaving in the for loop that instructs it to loop for the full array. length. I have also tried using if... else at different positions within my function please i need some guidance, im going to pull my hair out i can see what need in my head just cant get it. Plus i am very very new to this My simple objective is.... to set a flag to stop the loop when there have not been any swaps for the duration of the array. length-1, hence the array is now organised and to display the amount of loops taken. Heres the part that ive been changing and my latest attempt which is using if, however it still loops for 90 loops. Code: var temp; ;// varible to hold temporay value, var numberOfLoops = 0 swap = true if (swap = true) { for (var count = 0; count < returnArray.length; count = count +1)// sets any array lenght to be used and the number of passes as lenght of array for (var i = 0; i < returnArray.length-1; i = i + 1)// starting postion and what elements should be covered minus one pass less than the arrray { if ((returnArray[i]) > (returnArray[i+1])) { temp = returnArray[i+1]; //hold second value in temp var returnArray[i+1] = returnArray[i];// replace value second value with first value returnArray[i] = temp;//replace first value with value held in temp var swap = true } else { swap = false } numberOfLoops = numberOfLoops + 1 } } window.alert('number of loops taken is ' + numberOfLoops) return returnArray My bubble sort function als0 worked fine showing 90 loops each time...until changed it Similar TutorialsHi, OK, I know a bubble sort is very inefficient for sorting values but I have to do it as part of some coursework. I have the code working, i.e. it produces a sorted list of numeric values but the process of sorting the values is wrong. Below is my complete script. Code: <HTML> <HEAD> <TITLE> A program to sort an array using a bubble sort </TITLE> <SCRIPT> /*A function to sort an array. Function takes an array of numbers as an argument. Function returns a new array with the same elements as the argument array, sorted into ascending order*/ function bubbleSort(arrayToSort) { // declare and initialise a variable to hold the length of the argument array var length = arrayToSort.length; //declare an array to be returned by the function var returnArray = new Array(length); //copy each element of the argument array to the return array for (var i = 0; i < length; i = i + 1) { returnArray[i] = arrayToSort[i]; } // PLACE YOUR CODE FOR THE FUNCTION HERE /* */ for (var j = 0; j < returnArray.length - 1; j = j + 1) { for (var k = j + 1; k < returnArray.length; k = k + 1) if (returnArray[j] > returnArray[k]) { var temp; temp = returnArray[j]; returnArray[j] = returnArray[k]; returnArray[k] = temp; document.write('Array after each swap ' + returnArray + '<BR>') } } return returnArray; } /* a function for testing the bubbleSort() function. Function assigns an array to a variable Displays elements of unsorted array in order Invokes bubbleSort() function with the array as the argument Displays elements of sorted array in order Function takes no arguments. Function returns no value.*/ function bubbleTest() { var unsortedArray; //array to accept numbers to be sorted var sortedArray; //array to show sorted numbers // the array of values to be sorted unsortedArray = [4,3,2,1]; // TO DO TASK 3 (iv) // PLACE YOUR FUNCTION CODE HERE /*Write out the array 'unsortedArray'*/ document.write('A program to sort a series of numbers using the Bubble Sort method.' + '<BR>' + 'Unsorted array ' + unsortedArray + '<BR>'); /*Assign the results of the 'bubbleSort' function to the array 'sortedArray'*/ sortedArray = bubbleSort(unsortedArray); /*Write out the array 'sortedArray'*/ document.write('Sorted array ' + sortedArray + '<BR>'); /* The arrays below are for use in Task 4 (iii) and Task 5(iii) and can be ignored in Task 3 DATA SET 1 [8,4,6,2,10,5,3,7,1,9] DATA SET 2 [1,5,2,8,6,7,10,9,4,3] DATA SET 3 [ 6,3,8,7,2,9,10,4,5,1] DATA SET 4 [7,5,2,10,6,8,4,3,9,1] DATA SET 5 [9,4,1,10,5,2,3,8,7,6] */ } /*Test area for bubbelSort array*/ //var unsortedArray = [9,7,2,10,1,4,8,6,5,3]; //Test arguments //bubbleSort(unsortedArray); // invoke bubbleTest() to test the bubbleSort() function bubbleTest(); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> OK, the problem is that on after the first pass, the numbers should be as follows: 3,2,1,4 The biggest number always ends up in it's place after each pass. My code above outputs the numbers after the first pass: 3,4,2,1 You will notice it is probably an inefficient way of writing the code. We have to only use code we have learnt Sorry for the long post!! Basically what I have here in the following code is 15 random numbers that I am supposed to use the bubble and selection sort algorithm to sort. How can I go about getting the numbers to be sorted using selection sort I have already done the bubble. Thanks Code: <html> <body> <script language ="javaScript"> var array = new Array(15); function genNumbers(listbox){ var i; for(i= 0; i < array.length; i++) { array[i] = Math.random()*15; array[i] = Math.round(array[i]); } updateList(listbox); } function sortNumbers(listbox) { var x, y, holder; for(x=0; x < array.length; x++) { for(y=0; y< (array.length-1); y++){ if(array[y] > array[y+1]){ holder = array[y+1]; array[y+1] = array[y]; array[y] = holder; } } } updateList(listbox); } function updateList(listbox) { var i; for(i = 0; i< array.length; i++){ if(listbox.options[i] == null) { listbox.options[i] = new Option(array[i]); } else{ listbox.options[i].text = array[i]; } } } </script> <form> <center> <select name = "ranlist" size "10" style = "width: 100px"> </select> <br><br><br> <input type = "button" value = "Generate" onClick = "genNumbers(this.form.ranlist);"> <input type = "button" value = "Bubble Sort" onClick = "sortNumbers(this.form.ranlist);"> </form> </body> </html> I have an xml file: http://greenandtheblue.com/weather/parks.xml I'd like to display on an html page the time this xml document was last modified. I've done this successfully with php, but I'm wondering if I can do this with Javascript? The file will be in the same directory as the website/html page. I've googled for a while now with no success. Thanks for any help, S I have been working on the code for an alpha sort file and have become stumped. I need to incorporate both an insertion sort & selection sort method into my code before it will run. I attached the file I have been working on and it runs on Bluej with Java JDK. I would apretiate if you could take a look at it. If you would prefer not to download my file I have posted my code that I have been working on below. I am not familiar with the structure of an insertion sort or a selection sort mothod. I also am not clear on the point in which these methods would need to be placed in the file. Code: import java.io.*; import java.util.*; public class Words { ArrayList<String> words; public Words() { words = getData("wordlist.txt"); } public void displayWords() { for(int i=0; i<words.size(); i++) { System.out.println(words.get(i)); } } public ArrayList<String> getData(String filename) { ArrayList<String> list = new ArrayList<String>(); File myFile = new File(filename); if(myFile.exists() && myFile.length()>0) { try { BufferedReader in = new BufferedReader( new FileReader(myFile) ); String word = in.readLine(); while( word != null ) { list.add(word); word = in.readLine(); } } catch( Exception e ) {} } return list; } } Hi all, I have an array containing numbers. I want to order this numbers contained from major to minor in order to print them .. Here's what I have done: Code: var arr = new Array(6); arr[0] = "10"; arr[1] = "5"; arr[2] = "40"; arr[3] = "25"; arr[4] = "1000"; arr[5] = "1"; function sortNumber(a,b) { return b - a; } for(var i=0;i < 6; i++){ var myarray = arr[i]; myarray.sort(sortNumber); alert(myarray); } But I get no alert and a "myarray.sort is not a function" error. What am I doing wrong? How can I solve this? Thanks a lot in advance! Hi, Can i sort an array of objects in javascript?. I am having the value as Code: var myVarr = [{"name":"xyz","age":21}, {"name":"cde","age":25}]. The above array has two objects. I need to sort by age using javascript. Please help. Regards, anas I have the following array called 'datacontent' that have the following data: (4, RX33, ) (3, RX54, ) (102, RX44, ) (1, R100, Retail Branch 100) (2, RX12, ) (100, RX55, ) I want them to be sorted into this order: (1, R100, Retail Branch 100) (2, RX12, ) (3, RX54, ) (4, RX33, ) (100, RX55, ) (102, RX44, ) But it is always not sorted and it will give me as follows: (2, RX12, ) (3, RX54, ) (4, RX33, ) (100, RX55, ) (102, RX44, ) (1, R100, Retail Branch 100) My code is as follows: Code: function sortby(i) { return function(a,b){a = a[i];b = b[i];return a.toLowerCase() == b.toLowerCase() ? 0 : (a.toLowerCase() < b.toLowerCase() ? -1 : 1)} } datacontent.sort(sortby(1)); Appreciate any help. Hello, I am building a shopping cart website that is using a mega javascript dropdown menu. Everything was working fine until you get to the checkout page on the website. The checkout page has this accordian / spry deal where customers can checkout on one page. You can view it he http://gem-tech.com.mytempweb.com/store/pc/onepagecheckout.asp If I take the menu code out of the header.asp file, then the checkout page works just fine. But if I put the menu code back in, then the checkout page stops working. Here is the menu code (simplified it a bit for this thread): Quote: <head> <script src="Scripts/AC_RunActiveContent.js" type="text/javascript"></script> </head> Quote: <body><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript" src="jquery.hoverIntent.minified.js"></script> <script type="text/javascript"> $(document).ready(function() { function megaHoverOver(){ $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Calculate width of all ul's (function($) { jQuery.fn.calcSubWidth = function() { rowWidth = 0; //Calculate row $(this).find("ul").each(function() { rowWidth += $(this).width(); }); }; })(jQuery); if ( $(this).find(".row").length > 0 ) { //If row exists... var biggestRow = 0; //Calculate each row $(this).find(".row").each(function() { $(this).calcSubWidth(); //Find biggest row if(rowWidth > biggestRow) { biggestRow = rowWidth; } }); //Set width $(this).find(".sub").css({'width' :biggestRow}); $(this).find(".row:last").css({'margin':'0'}); } else { //If row does not exist... $(this).calcSubWidth(); //Set Width $(this).find(".sub").css({'width' : rowWidth}); } } function megaHoverOut(){ $(this).find(".sub").stop().fadeTo('fast', 0, function() { $(this).hide(); }); } var config = { sensitivity: 2, // number = sensitivity threshold (must be 1 or higher) interval: 100, // number = milliseconds for onMouseOver polling interval over: megaHoverOver, // function = onMouseOver callback (REQUIRED) timeout: 500, // number = milliseconds delay before onMouseOut out: megaHoverOut // function = onMouseOut callback (REQUIRED) }; $("ul#topnav li .sub").css({'opacity':'0'}); $("ul#topnav li").hoverIntent(config); }); </script> </body> And there are two things of script on the onepagecheckout.asp page as well. Here they a Quote: <script type="text/javascript"> $(document).ready(function() { $('#chkPayment').click(); }); </script> Quote: <script type="text/javascript"> var acc1 = new Spry.Widget.Accordion("acc1", { useFixedPanelHeights: false, enableAnimation: false }); var currentPanel = 0; <% if session("idCustomer")>"0" then session("OPCstep")=2 else session("OPCstep")=0 end if %> //* Find Current Panel <% if len(Session("CurrentPanel"))=0 AND pcv_strPayPanel="" then %> <% if session("idCustomer")>"0" then %> acc1.openPanel('opcLogin'); GoToAnchor('opcLoginAnchor'); $('#LoginOptions').hide(); $('#ShippingArea').hide(); $('#BillingArea').show(); <% else %> $('#LoginOptions').show(); $('#acc1').hide(); <% end if %> <% else %> <% If pcv_strPayPanel = "1" Then %> $(document).ready(function() { $('#LoginOptions').hide(); pcf_LoadPaymentPanel(); }); <% Else %> acc1.openPanel('opcLogin'); $('#LoginOptions').hide(); $('#ShippingArea').hide(); $('#BillingArea').show(); <% End If %> <% end if %> GoToAnchor('opcLoginAnchor'); function openme(pNumber) { acc1.openPanel(pNumber); } function toggle(pNumber) { var ele = acc1.getCurrentPanel(); var panelNumber = acc1.getPanelIndex(ele); if (panelNumber == pNumber) { acc1.closePanel(pNumber); } else { acc1.openPanel(pNumber); } } function togglediv(id) { var div = document.getElementById(id); if(div.style.display == 'block') div.style.display = 'none'; else div.style.display = 'block'; } function win(fileName) { myFloater=window.open('','myWindow','scrollbars=yes,status=no,width=300,height=250') myFloater.location.href=fileName; } </script> Any help would be GREATLY appreciated, Thank you Hello All, I always wonder that how to display any sort of data or HTML codes by just simply calling or including a Javascript file in other HTML file or a webpage. If you didn't understand what I want to say, I would like to give an example like AdSense gives a javascript code that need to be put where we want to show ads. And the ads appear, similarly how to display any HTML code with just inclusion of Javascript file. An other example is - <script type="text/javascript" src="http://example.com/scripts/javascript/source/somescript.js"> <div id="div_one"></div> <div id="div_two"></div> <div id="div_three"></div> </script> Now this script will show some HTML inside first div, some on second and so on. So How can I do that, please explain with an example... Thanks. I enclose code that should work. What to change that this code will work. I used prototype.js hi On my map, I have several markers, see my code: Code: <script language="JavaScript" type="text/javascript"> function load() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); var locationIcon = new GIcon(G_DEFAULT_ICON); //both images must be the same size locationIcon.image = "images/google-pin.png"; locationIcon.shadow = "images/google-pin-shadow.png"; locationIcon.iconSize = new GSize(90, 70); locationIcon.shadowSize = new GSize(90, 70); markerOptions = { icon:locationIcon }; map.setCenter(new GLatLng(51.3992613899243,-1.32983778443008), 8); // center point between the 2 map.addOverlay(new GMarker(new GLatLng(51.4769752333875,-2.53517458867092), markerOptions)); //BS16 3HH map.addOverlay(new GMarker(new GLatLng(50.8391656924497,-0.154312843280554), markerOptions)); // BN1 5PT map.addOverlay(new GMarker(new GLatLng(50.8340528225749,-0.259947032613667), markerOptions)); // BN43 6NZ map.addOverlay(new GMarker(new GLatLng(51.5168824045344,-2.6926718990779), markerOptions)); // BS11 9YQ map.addOverlay(new GMarker(new GLatLng(50.954582894922,-0.145016932400171), markerOptions)); // RH15 9LR } } //51.514925,-0.150118 W1U 1JQ //51.497593,-0.164806 SW3 1NQ </script> I would like to add an info bubble for each of my markers, would I add this piece of code somewhere within my code: Code: GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml("<table width='215'><tr><td><a rel="nofollow" target='_blank' href='http://www.lcls.org/'>Lewis & Clark Library System</a></td></tr><tr><td><img src='http://www.lcls.org/images/galleries/tour/01-BuildingFromLot.JPG' border='0' width='195px' height='95' /></td></tr><tr><td>425 Goshen Road<br />Edwardsville,IL 62025<br />618-656-3216</td></tr></table><br /><a rel="nofollow" target='_blank' href='http://maps.google.com/maps?q=425 Goshen Road%20Edwardsville,%20IL'>Directions</a>"); }); I found this beautiful fade-in/fade-out jQuery pop-up bubble and all I need to know is how to make the bubble animate on window.onload. If there's a better pop-up bubble than this that someone knows of offhand, that'd be great too. I haven't tested this one out and am a little wary about potential problems that the non-animated part of the bubble may or may not present. All I want to have happen is, when you visit the site, a div automatically fades in and stays near the top of the page for a minute to guide viewers to a specific area of the site, and then fades out. Thanks for any help!! Much appreciated. A dynamically-generated div pops up with absolute positioning, prompting user radio-button selection. div is selected and focused, and triggers onblur event to remove it from DOM. Clicking one of the radio buttons within the div should not remove the div from the DOM. problem: clicking radio button removes the div from the DOM even though the radio button is inside the div and even though clicking the radio button triggers onclick event to cancelBubble. I'm about to post this, and thinking that I should modify the blur event to remove the div only if the click event is outside of its coords... (...terribly sleep-deprived, lol) Since I've already prepped this post..., any thoughts / suggestions? Sample code: Code: var items = ['carrots', 'bananas', 'apples'], fragment = null, item = null; if (items.length > 0) { fragment = <div id="AddItemSelector" onblur="Cancel_AddNewItem();"><div name="title">Select Item:</div>'; do { item = items.shift(); fragment += '<div><input name="radNewItem" type="radio" value="' + item + '" onclick="Click_NewItem(event)">' + item + '</div>'; } while (items.length > 0); fragment += '<div><input type="button" value="Cancel" onclick="Cancel_AddNewItem();"><input type="button" value="Select" onclick="Select_AddNewItem();"></div></div>'; $(blahblah).after(fragment); $('#AddItemSelector').select().focus(); } items = null; fragment = null; item = null; ... function Click_NewItem(Event) { Event.cancelBubble = true; } function Cancel_AddNewItem() { $('#AddItemSelector').remove(); } I've been trying for some time now to create some code which dynamically adds markers to a google map. I've now managed this but I still have a slight problem I think with the javascript side of things. I've included a snippet of the code which shows 2 markers on the map. They should be 2 different markers but they are the same, and the contents of the popup bubble should be each individual postcode, but they both show the same postcode. Does anyone have any ideas? Thanks Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Geocoding UK Postcodes with Google APIs Demo</title> <style type="text/css"> html { height: 100%; } body { margin: 0; padding: 0; height: 100%; } #map { width: 100%; height: 100%; z-index:1; } </style> <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAQJTCOfFBzEZfb0xYTu1h_BR0_9owy9VLLEJCKI_ZedHr-0NdXxQd9Q8sR1hC7s4PNGNVmIaTUQvspA" type="text/javascript"></script> <script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAQJTCOfFBzEZfb0xYTu1h_BR0_9owy9VLLEJCKI_ZedHr-0NdXxQd9Q8sR1hC7s4PNGNVmIaTUQvspA" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ var icon2 = new GIcon(); icon2.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; icon2.shadow = "http://www.google.com/mapfiles/shadow50.png"; icon2.iconSize = new GSize(32, 32); icon2.shadowSize = new GSize(37, 34); icon2.iconAnchor = new GPoint(16, 32); icon2.infoWindowAnchor = new GPoint(16, 0); var icon3 = new GIcon(); icon3.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png"; icon3.shadow = "http://www.google.com/mapfiles/shadow50.png"; icon3.iconSize = new GSize(32, 32); icon3.shadowSize = new GSize(37, 34); icon3.iconAnchor = new GPoint(16, 32); icon3.infoWindowAnchor = new GPoint(16, 0); var localSearch = new GlocalSearch(); function initialize() { if (GBrowserIsCompatible()) { map = new GMap(document.getElementById("map")); map.setCenter(new GLatLng(55.100651, -4.664941), 6); } } function createMarker(point2,html) { var marker2 = new GMarker(point2,icon2); GEvent.addListener(marker2, "click", function() { marker2.openInfoWindowHtml(html, { noCloseOnClick: true }); }); return marker2; } function createMarker2(point3,html) { var marker3 = new GMarker(point3,icon3); GEvent.addListener(marker3, "click", function() { marker3.openInfoWindowHtml(html, { noCloseOnClick: true }); }); return marker3; } //]]> </script> </head> <body> <div id="map"><script type="text/javascript">document.write(initialize())</script></div> <script type="text/javascript"> var thetext = 'LL58 8HU' localSearch.execute("LL58 8HU, UK"); localSearch.setSearchCompleteCallback(null, function() { map.addOverlay(createMarker(new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng),thetext)); }); </script> <script type="text/javascript"> var thetext2 = 'RG4 6UT' localSearch.execute("RG4 6UT, UK"); localSearch.setSearchCompleteCallback(null, function() { map.addOverlay(createMarker2(new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng),thetext2)); }); </script> </body> </html> Hello...I need to display the last modified date of each file on my webpage. There are a variety of files including, .doc, .pdf, .ppt, .zip, etc. I am able to get the last modified date to work, however I would like to know if it is possible to format the output of the date/time? I have the following code in the head of my html file: Code: <script type="text/javascript"> function getlastmod(what) { var http=new XMLHttpRequest() http.open('HEAD',what,false) http.send(null) if (http.status!=200) return undefined return http.getResponseHeader('Last-modified') } </script> In the body section, I have the following: Code: <ul> <li><a href="documents/OMB_Memo_Conferences_Sep_2011.pdf" target="_blank"> OMB Memo Conferences</a> <script type="text/javascript">document.write(getlastmod('documents/OMB_Memo_Conferences_Sep_2011.pdf'))</script> <br /></li> <li><a href="documents/NavOceano_Crb.doc" target="_blank">Nav Oceano CRB</a> <script type="text/javascript">document.write(getlastmod('documents/NavOceano_Crb.doc'))</script><br /> </ul> The output is: OMB Memo Conferences Fri, 11 May 2012 13:00:49 GMT Nav Oceano CRB Fri, 11 May 2012 13:00:38 GMT Is there any way to format the last modified date/time to display just the following: OMB Memo Conferences May 11, 2012 Nav Oceano CRB May 11, 2012 Any help would be appreciated. Thanks, Andy I feel a little stupid to ask this question but it has always been on my mind. <html> <head> <script type="text/javascript"> { var lastMod = new Date (document.lastModified); document.write ("<p>Document last modified "); document.write ((lastMod.getMonth() +1) + "-" + lastMod.getDate() + "-" + lastMod.getFullYear()); document.write ("<p>"); } </script> </head> </html> when i open in ie or ff it renders 2/25/11 (supposed to be 2/26/11) but when i use it in chrome or an html test is renders correctly. why? Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, Hi, I am having some problems with this modified version of Lightbox. I had a programmer implement this into the site and then one day it just stopped working. I'm trying to fix it myself, with no success. To view the problem go to: http://www.uscgq.com/question/deck/2 and click the red flag icon. The lightbox opens, but only shows the "Loading" message. I have isolated the problem to somewhere in the Lightbox.js just don't know where or what it is. Any help is greatly appreciated! Code: /* Created By: Chris Campbell Website: http://particletree.com Date: 2/1/2006 Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/ */ /*-------------------------------GLOBAL VARIABLES------------------------------------*/ var detect = navigator.userAgent.toLowerCase(); var OS,browser,version,total,thestring; /*-----------------------------------------------------------------------------------------------*/ //Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/ function getBrowserInfo() { if (checkIt('konqueror')) { browser = "Konqueror"; OS = "Linux"; } else if (checkIt('safari')) browser = "Safari" else if (checkIt('omniweb')) browser = "OmniWeb" else if (checkIt('opera')) browser = "Opera" else if (checkIt('webtv')) browser = "WebTV"; else if (checkIt('icab')) browser = "iCab" else if (checkIt('msie')) browser = "Internet Explorer" else if (!checkIt('compatible')) { browser = "Netscape Navigator" version = detect.charAt(8); } else browser = "An unknown browser"; if (!version) version = detect.charAt(place + thestring.length); if (!OS) { if (checkIt('linux')) OS = "Linux"; else if (checkIt('x11')) OS = "Unix"; else if (checkIt('mac')) OS = "Mac" else if (checkIt('win')) OS = "Windows" else OS = "an unknown operating system"; } } function checkIt(string) { place = detect.indexOf(string) + 1; thestring = string; return place; } /*-----------------------------------------------------------------------------------------------*/ Event.observe(window, 'load', initialize, false); Event.observe(window, 'load', getBrowserInfo, false); Event.observe(window, 'unload', Event.unloadCache, false); var lightbox = Class.create(); lightbox.prototype = { yPos : 0, xPos : 0, initialize: function(ctrl) { this.content = ctrl.href; Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false); ctrl.onclick = function(){return false;}; }, // Turn everything on - mainly the IE fixes activate: function(){ if (browser == 'Internet Explorer'){ this.getScroll(); this.prepareIE('100%', 'hidden'); this.setScroll(0,0); this.hideSelects('hidden'); } this.displayLightbox("block"); }, // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox prepareIE: function(height, overflow){ bod = document.getElementsByTagName('body')[0]; bod.style.height = height; bod.style.overflow = overflow; htm = document.getElementsByTagName('html')[0]; htm.style.height = height; htm.style.overflow = overflow; }, // In IE, select elements hover on top of the lightbox hideSelects: function(visibility){ selects = document.getElementsByTagName('select'); for(i = 0; i < selects.length; i++) { selects[i].style.visibility = visibility; } }, // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/ getScroll: function(){ if (self.pageYOffset) { this.yPos = self.pageYOffset; } else if (document.documentElement && document.documentElement.scrollTop){ this.yPos = document.documentElement.scrollTop; } else if (document.body) { this.yPos = document.body.scrollTop; } }, setScroll: function(x, y){ window.scrollTo(x, y); }, displayLightbox: function(display){ $('overlay').style.display = display; $('lightbox').style.display = display; if(display != 'none') this.loadInfo(); }, // Begin Ajax request based off of the href of the clicked linked loadInfo: function() { var myAjax = new Ajax.Request( this.content, {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)} ); }, // Display Ajax response processInfo: function(response){ console.log('calling process info'); if($('lbHeader')) Element.remove($('lbHeader')); info = "<div id=\"lbHeader\"><a href=\"javascript: closeLightboxes();\">close</a> or hit ESC</div><div id='lbContent'>" + response.responseText + "</div>"; new Insertion.Before($('lbLoadMessage'), info) $('lightbox').className = "done"; this.actions(); }, // Search through new links within the lightbox, and attach click event actions: function(){ lbActions = document.getElementsByClassName('lbAction'); for(i = 0; i < lbActions.length; i++) { Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false); lbActions[i].onclick = function(){return false;}; } }, // Example of creating your own functionality once lightbox is initiated insert: function(e){ link = Event.element(e).parentNode; Element.remove($('lbContent')); var myAjax = new Ajax.Request( link.href, {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)} ); }, // Example of creating your own functionality once lightbox is initiated deactivate: function(){ if($('lbHeader')) Element.remove($('lbHeader')); Element.remove($('lbContent')); if (browser == "Internet Explorer"){ this.setScroll(0,this.yPos); this.prepareIE("auto", "auto"); this.hideSelects("visible"); } this.displayLightbox("none"); } } /*-----------------------------------------------------------------------------------------------*/ // Onload, make all links that need to trigger a lightbox active function initialize(){ addLightboxMarkup(); lbox = document.getElementsByClassName('lbOn'); for(i = 0; i < lbox.length; i++) { valid = new lightbox(lbox[i]); } } // Add in markup necessary to make this work. Basically two divs: // Overlay holds the shadow // Lightbox is the centered square that the content is put into. function addLightboxMarkup() { bod = document.getElementsByTagName('body')[0]; overlay = document.createElement('div'); overlay.id = 'overlay'; lb = document.createElement('div'); lb.id = 'lightbox'; lb.className = 'loading'; lb.innerHTML = '<div id="lbLoadMessage">' + '<p>Loading</p>' + '</div>'; bod.appendChild(overlay); bod.appendChild(lb); } // Send AJAX Call function sendForm(url) { new Ajax.Updater('lbContent', url, { method: 'post', parameters: Form.serialize($('content_form'),true) }); } // Function to destroy lightbox elements function closeLightboxes() { if(lightbox.prototype) lightbox.prototype.displayLightbox('none'); if($('lbHeader')) Element.remove($('lbHeader')); if($('lbContent')) Element.remove($('lbContent')); } // Close the lightbox if ESC is pressed document.onkeypress=function(e){ var KeyID = (window.event) ? event.keyCode : e.keyCode; if(KeyID == 27) { closeLightboxes(); } } Hi, I have main html page called "ana.html" which seldomly updated and another page "yeniler.html" that showing latest added articles and often updated. What I want is, whenever "yeniler.html" modified the javascript in "ana.html" shows "Latest Update Date: xx.xx.xxxx". As you can see I don't want to show file modified date of "ana" in "ana" like so many scripts offer on the web , but in page "ana" modified date of "yeniler" I also want the date format like 8.18.2008 (without hour, minute, and name of the month) What I mean is that my <body> tag currently is like this: Code: <body class="page-course"> I would like to insert a pop-up contact form which requires the body tag to be like this: Code: <body onload="javascript:fg_hideform('fg_formContainer','fg_backgroundpopup');"> Not quite sure how to merge these - indeed can I merge them? Perhaps better to make the body class (top example) execute elsewhere? THANKS!! |