Search Results

Search found 72 results on 3 pages for 'javscript'.

Page 3/3 | < Previous Page | 1 2 3 

  • Preserve onchange for a dropdown list when setting the value with Javascript.

    - by Zac Altman
    I have a dropdown list with a piece of code that is run when the value is changed: <select name="SList" onchange="javascript:setTimeout('__doPostBack(\'SList\',\'\')', 0)" id="SList"> Everything works fine when manually done. As an option is selected, the onchange code is called. The problem begins when I try to change the selected value using a piece of Javscript. I want to be able to automatically change the selected option using JS, whilst still having the onchange code called, exactly as if done manually. I try calling this: form.SList.value = "33"; The right option is selected, but the onchange code does not get called. So then I try doing this: form.SList.value = "33"; javascript:setTimeout('__doPostBack(\'SList\',\'\')', 0); The right value is not selected and nothing happens. FYI, the code is done in ASP.NET and Javascript. What can I run to change the selected option whilst still calling the onchange code?

    Read the article

  • Calling methods within same Javwscript class [Prototype]

    - by eldeejay
    I've created a class in Javscript using the prototype Class.Create complete with the initialize function and a few other functions. However, in one of my functions I want to reference another function in the same class, but cannot seem to get the syntax correct. e.g. var sampleClass = Class.create({ initialize: function(){ //do the init work here }, functionA: function(){ //do some more stuff here } functionB: function(){ //Do some stuff functionA() } } I've tried calling functionA() , this.functionA() but nothing works I just get errors. I know how to call the functions externally when the class has been instantiated, but not reference a function from within the class itself. Thanks

    Read the article

  • How do I rotate an image in Javascript or CSS

    - by Eric
    I am creating a simple game. I want to use jQUERY to rotate the joints making it move. I am using .animate ( http://api.jquery.com/animate/ ) to animate CSS properties but if it is also possible to use Javscript, I can make my own custom code. More TO-THE-POINT How do I rotate images in CSS or Javascript? I prefer CSS but Javascript is fine too. If it is impossible (which I am pretty sure it is but I am not giving up yet) is there any other possible way to do what i am trying to do without making a bunch of seperate images, each rotated a different way. Or can anyone at least give me an example of a site that does something similar. EDIT: I need 1 CSS property (no -something: rotation(500deg);) that works with FireFox, Safari and Chrome because those are the only browsers I really work with.

    Read the article

  • scrollTo scrolls to the top of the page

    - by yanis
    Hi, I have the following Javscript code. When the page is loaded it is scrolled to the right position. When I click on the link to run the function the page scrolls to the top of the page. Has anybody any idea how to fix it? <html> <head> <script type="text/javascript"> function scroll() { window.scrollTo(0, 400) } </script> <title></title> </head> <body onload="window.scrollTo(0, 400)"> <img src="a.jpg"/> <a href="#" onclick="scroll">comments1</a> </body> </html>

    Read the article

  • Register javascript array from code behind in facebook

    - by Ahmy
    I need to set a javascript array from code behind using C# in Asp.Net2008 the problem now is that when i register the array using the following C# code: string ArrVal = ""; string Sep = ""; for (int i = 0; i < 17; i++) { ArrVal += Sep + FilesCount[i].ToString(); Sep = ","; } Page.ClientScript.RegisterArrayDeclaration("FilesArr", ArrVal); And the Client code is : var FileName = FilesArr[0]; in any web application it is working well but at my application that is released in the facebook platform the javascript code doesn't see the array but in ordinary web application the javscript code see the registered array can any one tell me why this problem occurrs ? Thanks in advance for any reply and trial.

    Read the article

  • Calling methods within same JavaScript class [Prototype]

    - by eldeejay
    I've created a class in Javscript using the prototype Class.Create complete with the initialize function and a few other functions. However, in one of my functions I want to reference another function in the same class, but cannot seem to get the syntax correct. e.g. var sampleClass = Class.create({ initialize: function(){ //do the init work here }, functionA: function(){ //do some more stuff here } functionB: function(){ //Do some stuff functionA() } } I've tried calling functionA() , this.functionA() but nothing works I just get errors. I know how to call the functions externally when the class has been instantiated, but not reference a function from within the class itself. Thanks

    Read the article

  • Convert System.DateTime to Javascript DateString

    - by SARAVAN
    I am working on an ASP .net MVC application. I have a System.DateTime? property say creationDate, which gets its value assigned from controller code. In my javascript I have access to this value, and I wanted to display this value in mm/dd/yyyy format in my grid. But I am not sure on how to convert System.Datetime? of c# to a javscript date or datestring value? Any help would be appreciated.

    Read the article

  • Javascript instanceof & typeof in GWT (JSNI)

    - by rybz
    Hi, I've encountered an curious problem while trying to use some objects through JSNI in GWT. Let's say we have javscript file with the function defined: test.js: function test(arg){ var type = typeof(arg); if (arg instanceof Array) alert('Array'); if (arg instanceof Object) alert('Object'); if (arg instanceof String) alert('String'); } And the we want to call this function user JSNI: public static native void testx()/ *-{ $wnd.test( new Array(1, 2, 3) ); $wnd.test( [ 1, 2, 3 ] ); $wnd.test( {val:1} ); $wnd.test( "Some text" ); }-*/; The questions are: why instanceof instructions will always return false? why typeof will always return "object" ? how to pass these objects so that they were recognized properly?

    Read the article

  • Programmatically Untag FB Photos with Javascript

    - by Tal
    Hello! I've spent the past hour hacking away at this: I want to write a Javscript routine to programatically untag myself from photos on Facebook. Once it works, I'll run it in the Firebug console and untag myself from all Facebook photos (there's no way to do this through the GUI). I wanted to see if you guys had some advice to get me on my journey. I have a few methods in mind but haven't come too far along quite yet. I've tried an AJAX approach by creating a new HTML request and pointing it to the remove_tag URL, which looks something like this: /ajax/photo_tagging_ajax.php?pid=(PICTURE_ID)&id=(PICTURE_OWNER_ID)&subject=(SOMETHING)&name=(YOUR+NAME)&action=remove Not surprisingly, this doesn't work (yet). I've been checking the HTTP response in Firebug and it's quite different than the one when I actually untag a picture. It's not even sending a POST request. Will this even be possible or am I dreaming? (it's almost 4AM)

    Read the article

  • javascript not loading after output of PHP file_get_contents() string

    - by mives
    I have the following structure: -uploadpage.html -index.php -resources -jquery.1.4.2.min.js On my index.php, I get the contents then output uploadpage.html through this code: $output = file_get_contents("uploadpage.html"); echo $output; My upload.html has the javascript at the bottom: <script type="text/javscript" src="./resources/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready( function() { callSomething(); } ); function callSomething() {return true;} </script> However this results in an error "$ is not defined" which means that the jquery js file is not loaded. Any ideas?

    Read the article

  • cant get ajax response (JSON) to call 'success' function?

    - by Haroldo
    for some reason the success function isnt being called? javscript: $.ajax({ type: 'POST', url: 'http://localhost/hf_latest_desktop/st_pages/user_area/acc_buttons/pass_change/pass_change_ajax.php', data: data, dataType: 'json', success: function(e){ console.log(e); if(e.status == 'success'){ alert('your password has been changed!'); } if(e.status == 'error1'){ alert('please fill in all inputs!'); } if(e.status == 'error2'){ alert('password incorrect!'); } if(e.status == 'error3'){ alert('change failed!'); } } }); php file ajax is calling to: <?php session_start(); session_cache_limiter('nocache'); header('Expires: ' . gmdate('r', 0)); header('Content-type: application/json'); $status = 'error1'; //for sake of example ?> {'status':'<?php echo $status; ?>'}

    Read the article

  • Read Cookies using Javascript

    - by Ajith
    I want to create a cookie using php,an also i need to read it using javascript.ie, by using setcookie('mycookie','hello',time()+34000) in php i am creating a cookie in my system.Now,i need to read it using javascript.Is it possible?If anybody knows please give me some idea.Please....help me.I am using javscript as follows ` function Get_Cookie( check_name ) { // first we'll split this cookie up into name/value pairs // note: document.cookie only returns name=value, not the other components var a_all_cookies = document.cookie.split( ';' ); var a_temp_cookie = ''; var cookie_name = ''; var cookie_value = ''; var b_cookie_found = false; // set boolean t/f default f for ( i = 0; i < a_all_cookies.length; i++ ) { // now we'll split apart each name=value pair a_temp_cookie = a_all_cookies[i].split( '=' ); // and trim left/right whitespace while we're at it cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, ''); // if the extracted name matches passed check_name if ( cookie_name == check_name ) { b_cookie_found = true; // we need to handle case where cookie has no value but exists (no = sign, that is): if ( a_temp_cookie.length > 1 ) { cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') ); } // note that in cases where cookie is initialized but no value, null is returned return cookie_value; break; } a_temp_cookie = null; cookie_name = ''; } if ( !b_cookie_found ) { return null; } } if (Get_Cookie('__gsb')) { alert('Found'); } `

    Read the article

  • How do you submit an authenticated HTML form using XUL (Firefox extension) Javascript?

    - by machineghost
    I am working on a Firefox extension, and in that extension I am trying to use AJAX to submit a form on a webpage. I am using: var request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest); request.onload = loadHandler; request.open("POST", url, true); request.send(values); to make the request, and it works ... mostly. The one problem is that the form has an authentication token on it, and I need to submit that token with my POST. I tried doing a GET separately to get this token, but by the time I made my second (POST) request my session had (evidently) changed, and the authenticity token was considered invalid. Does anyone know of a way to use the XUL/Chrome Javscript to maintain a constant session across multiple requests (all "behind the scenes") for something this? I'm still a XUL n00b, so there may be a totally obvious alternative that I'm missing (eg. hidden IFRAME; I tried that briefly but couldn't get it to work).

    Read the article

  • XML file does't load when HTML5 video plays

    - by DD77
    I should be able to loads the related XML file and displays the content of the XML file as the video plays back. What am I missing? DEMO JAVSCRIPT // properties var XML_PATH = "http://www.adjustyourset.tv/interview/cuepoints.xml"; var video_width; var video_height; var videos_array=new Array(); // init the application function init() { // call loadXML function loadXML(); } // XML loading function loadXML() { $.ajax({ type: "GET", url: XML_PATH, dataType: "xml", success: function onXMLloaded(xml) { // set cuepoints find("cuepoints"); find("cuepoints"); // loop for each cuepoint $(xml).find('cuepoint').each(function loopingItems(value) { // create an object var obj={timeStamp:$(this).find("timeStamp").text(), desc:$(this).find("desc").text(), thumbLink:$(this).find("thumbLink").text(), price:$(this).find("price").text()}; videos_array.push(obj); // append <ul> and timeStamp $("#mycustomscroll").append('<ul>'); $("#mycustomscroll").append('<a><li id="item">Time Stamp:'+obj.timeStamp+'</li></a>'); }); // close </ul> $("#mycustomscroll").append('</ul>'); // append li tags $("#leftcolumn").append('<li src="'+videos_array[0].desc+'"> <p src="'+videos_array[0].thumbLink+'" /></li>'); // append description $("#price").append(videos_array[0].price); // call addListeners function addListeners(); } }); }

    Read the article

  • echo php javascript alert?

    - by Anaes Arias
    How can I echo this javascript if the php error messages is called? I have an error message setting that when a user misses his username or password it triggers an error message. The php error message is called by a php code. Here is the code: <?php echo showmessage($msg) ?> I have an alert message in javascript that when called it will make a javascript css pop up alert box. IF the javascript code is present it will show the alert box right away after reload. Here is code: <script type="text/javascript"> $(document).ready(function () { jqxAlert.alert('Alert Message'); }) </script> How can I incorporate so that when the php echo message comes up it will trigger the javscript alert message. I was trying an if in php, so something like this code: if ( showmessage($msg) ) { <script type="text/javascript"> $(document).ready(function () { jqxAlert.alert('Alert Message'); }) </script> } How can I echo my javascript message on the php call?

    Read the article

  • ASP disable button during postback

    - by user667430
    I have a button which i am trying to add a css class to appear disabled once the user has clicked it. protected void Button_Continue_OnClick(object sender, EventArgs e) { Panel_Error.Visible = false; Literal_Error.Text = ""; if (RadioButton_Yes.Checked) { ...//if radio checked get text and process etc. } } My button onlick is above which simply processes a textbox filled on the page. My button looks like this: <asp:Button runat="server" ID="Button_Continue" CssClass="button dis small" Text="Continue" OnClick="Button_Continue_OnClick" ClientIDMode="Static" OnClientClick="return preventMult();" /> And my javscript is as follows: <script type="text/javascript"> var isSubmitted = false; function preventMult() { if (isSubmitted == false) { $('#Button_Continue').removeClass('ready'); $('#Button_Continue').addClass('disabled'); isSubmitted = true; return true; } else { return false; } } </script> The problem I am having is that the css class added works fine on the first postback, but after which my button onclick doesnt work and the button cant be clicked again if the user needs to resubmit the data if it is wrong Another problem I am having is that with a breakpoint in my method i notice that the method is fired twice on the click.

    Read the article

  • Hide jQuery Accordion while loading

    - by zac
    I am testing a site build with a slow connection and I noticed the jQuery Accordion stays expanded for a long time, until the rest of the site is loaded, and then finally collapses. Not very pretty. I was wondering how I could keep it collapsed through the loading process and only expand when clicked. I am working with the standalone 1.6 version of the accordion plugin. The basic structure : <div class="sidebar"> <ul id="navigation" class="ui-accordion-container"> <li><a class="head" href="#">1</a> <ul class="sub"> <li><a href="#">1a</a></li> <li><a href="#">2a</a></li> </ul> </li> </ul> </div> and the script jQuery().ready(function(){ jQuery('#navigation').accordion({ active: 'false', header: '.head', navigation: true, animated: 'easeslide', collapsible: true }); }); I tried to hide the elements in the CSS to keep them from appearing while loading but all that achieved is in having them always hidden. Maybe the problem is in the CSS I have a background image in each of the sub menus: #navigation{ margin:0px; margin-left: 10px; padding:0px; text-indent:0px; font-size: 1.1em; width:200px; text-transform: uppercase; padding-bottom: 30px; } #navigation ul{ border-width:0px; margin:0px; padding:0px; text-indent:0px; } #navigation li{ list-style:none outside none; } #navigation li ul{ height:185px; overflow:auto; } #navigation li ul.sub{ background:url('../images/sub.jpg') no-repeat; dispaly: block; } #navigation li li a{ color:#000000; display:block; text-indent:20px; text-decoration: none; padding: 6px 0; } #navigation li li a:hover{ background-color:#FFFF99; color:#FF0000; } Thanks in advance for any advice on how to have this thing run a little smoother and having the accordion always collapsed. -edit - I forgot to mention that I am also hoping for a solution that will allow the nav to still be accessible for those without javscript.

    Read the article

  • Unsure how to design JavaScript / jQuery functionality which uses XML to create HTML objects

    - by Jack Roscoe
    Hi, I'm using JavScript and jQuery to read an XML document and subsequently use the information from the XML to create HTML objects. The main 'C' nodes in the XML document all have a type attribute, and depending on the type I want to run a function which will create a new html object using the other attributes assigned to that particular 'C' node node. Currently, I have a for loop which extracts each 'C' node from the XML and also it's attributes (e.g. width, height, x, y). Also inside the for loop, I have an if statement which checks the 'type' attribute of the current 'C' node being processed, and depending on the type it will run a different function which will then create a new HTML object with the attributes which have been drawn from the XML. The problem is that there may be more than one 'C' node of the same type, so for example when I'm creating the function that will run when a 'C' node of 'type=1' is detected, I cannot use the 'var p = document.createElement('p')' because if a 'C' node of the same type comes up later in the loop it will clash and override that element with that variable that has just been created. I'm not really sure how to approach this? Here is my entire script. If you need me to elaborate on any parts please ask, I'm sure it's not written in the nicest possible way: var arrayIds = new Array(); $(document).ready(function(){ $.ajax({ type: "GET", url: "question.xml", dataType: "xml", success: function(xml) { $(xml).find("C").each(function(){ arrayIds.push($(this).attr('ID')); }); var svgTag = document.createElement('SVG'); // Create question type objects function ctyp3(x,y,width,height,baC) { alert('test'); var r = document.createElement('rect'); r.x = x; r.y = y; r.width = width; r.height = height; r.fillcolor = baC; svgTag.appendChild(r); } // Extract question data from XML var questions = []; for (j=0; j<arrayIds.length; j++) { $(xml).find("C[ID='" + arrayIds[j] + "']").each(function(){ // pass values questions[j] = { typ: $(this).attr('typ'), width: $(this).find("I").attr('wid'), height: $(this).find("I").attr('hei'), x: $(this).find("I").attr('x'), y: $(this).find("I").attr('x'), baC: $(this).find("I").attr('baC'), boC: $(this).find("I").attr('boC'), boW: $(this).find("I").attr('boW') } alert($(this).attr('typ')); if ($(this).attr('typ') == '3') { ctyp3(x,y,width,height,baC); // alert('pass'); } else { // Add here // alert('fail'); } }); } } }); });

    Read the article

  • How to replace invalid characters in XML using Javascript or PhP

    - by Raind
    Hi, Need help here for the following: Running PhP, javascript, MySQL, XML. 1) Retrieving file from MySQL and stored it onto XML file. 2) Use javascript function to load XML file (that stored those data). 3) It produces invalid characters in XML file. STEP 1 : Sample of the code in PhP - Loading MySQL DB to store data onto XML file $file= fopen("MapDeals2.xml", "w"); $_xml ="\n"; $_xml .="\n"; while($row1_ThisWeek = mysql_fetch_array($result1_ThisWeek)) { $rRName = $row1_ThisWeek['Retailer_Name']; $rRAddress = $row1_ThisWeek['Retailer_Address1']; $rRAddressPostCode = $row1_ThisWeek['Retailer_AddressPostCode1']; } $_xml .= "<DEAL>\n"; $_xml .= "<DealDescription>" . $d_Description . "</DealDescription>\n"; $_xml .= "<DealURL>" . $d_URL . "</DealURL>\n"; $_xml .= "<DealRName>" . $rRName . "</DealRName>\n"; $_xml .= "<DealRAddress>" . $rRAddress . "</DealRAddress>\n"; $_xml .= "<DealRPostCode>" . $rRAddressPostCode . "</DealRPostCode>\n"; $_xml .= "</DEAL>\n"; } } $_xml .="\n"; fwrite($file, $_xml); fclose($file); STEP 2 : Sample of the code in Javscript - Loading XML file xhttp.open("GET","Test2.xml", false); xhttp.send(""); xmlDoc=xhttp.responseXML; var x=xmlDoc.getElementsByTagName("Employee"); parser = new DOMParser(); xmlDoc = parser.parseFromString("MapDeals2.xml", "text/xml"); for (i=0;i"; . . . } Is there a solution for the above? Looking forward to hear from you soon. Cheers

    Read the article

  • UpdatePanel, JavaScript postback and changing querystring at same time in SharePoint Search Page

    - by Lee Dale
    Hi Guys, Been tearing my hear out with this one. Let me see if I can explain: I have a SharePoint results page on which I have a Search Results Core WebPart. Now I want to change the parameter in the querystring when I postback the page so that the WebPart returns different results for each parameter e.g. the querystring will be interactivemap.aspx?k=Country:Romania this will filter the results for Romania. First issue is I want to do this with javascript so I call: document.getElementById('aspnetForm').action = "interactivemap.aspx?k=Country:" + country; Nothing special here but the reason I need to call from Javascript is there is also a flash applet on this page from which the Javascript calls originate. When the javascript calls are made the page needs to PostBack but not reload the flash applet. I turned to ASP.Net AJAX for this so I wrapped the search results webpart in an update panel. Now if I use a button within the UpdatePanel to postback the UpdatePanel behaves as expected and does a partial render of the search results webpart not reloading the flash applet. Problem comes because I need postback the page from javscript. I called __doPostBack() as I have used this successully in the past. It works on it's own but fails when I first call the above Javascript before the __doPostBack() (I also tried calling click() on a hidden button) the code for the page is at the bottom. I think the problem comes with the scriptmanager not allowing a partial render when the form post action has changed. My questions are. A) Is there some other way to change the search results webpart parameter without using the querystring. or B) Is there a way around changing the querystring when doing an AJAX postback and getting a partial render. <asp:Content ContentPlaceHolderID="PlaceHolderFullContent" runat="server"> function update(country) { //__doPostBack('ContentUpdatePanel', ''); //document.getElementById('aspnetForm').action = "interactivemap.aspx?k=ArticleCountry:" + country; document.getElementById('ctl00_PlaceHolderFullContent_UpdateButton').click(); } Romania <div class="firstDataTitle"> <div class="datatabletitleOuterWrapper"> <div class="datatabletitle"> <span>Content</span></div> </div> <div class="datatableWrapper"> <div class="dataHolderWrapper"> <div class="datatable"> <div> <div class="searchMain"> <div class="searchZoneMain"> <asp:UpdatePanel runat="server" id="ContentUpdatePanel" UpdateMode="Conditional"> <ContentTemplate> <WebPartPages:webpartzone runat="server" AllowPersonalization="false" title="<%$Resources:sps,LayoutPageZone_BottomZone%>" id="BottomZone" orientation="Vertical" QuickAdd-GroupNames="Search" QuickAdd-ShowListsAndLibraries="false"><ZoneTemplate></ZoneTemplate></WebPartPages:webpartzone> <asp:Button id="UpdateButton" name="UpdateButton" runat="server" Text="Update"/> </ContentTemplate> </asp:UpdatePanel> </div> </div> </div> </div> </div> </div>

    Read the article

  • Chaining CSS classes in IE6 - Trying to find a jQuery solution?

    - by Mike Baxter
    Right, perhaps I ask the impossible? I consider myself fairly new to Javscript and jQuery, but that being said, I have written some fairly complex code recently so I am definitely getting there... however I am now possed with a rather interesting issue at my current freelance contract. The previous web coder has taken a Grid-960 approach to the HTML and as a result has used chained classes to style many of the elements. The example below is typical of what can be found in the code: <div class='blocks four-col-1 orange highlight'>Some content</div> And in the css there will be different declarations for: (not actual css... but close enough) .blocks {margin-right:10px;} .orange {background-image:url(someimage.jpg);} .highlight {font-weight:bold;} .four-col-1 {width:300px;} and to make matters worse... this is in the CSS: .blocks.orange.highlight {background-colour:#dd00ff;} Anyone not familiar with this particular bug can read more on it here: http://www.ryanbrill.com/archives/multiple-classes-in-ie/ it is very real and very annoying. Without wanting to go into the merrits of not chaining classes (I told them this, but it is no longer feasible to change their approach... 100 hand coded pages into a 150 page website, no CMS... sigh) and without the luxury of being able to change the way these blocks are styled... can anyone advise me on the complexity and benefits between any of my below proposed approaches or possible other options that would adequately solve this problem. Potential Solution 1 Using conditional comments I am considering loading a jquery script only for IE6 that: Reads the class of all divs in a certain section of the page and pushes to an array creates empty boxes off screen with only one of the classes applied at a time Reads the applied CSS values for each box Re-applies these styles to the individual box, somehow bearing in mind the order in which they are called and overwriting conflicting instructions as required Potential Solution 2 read the class of all divs in a certain section of the page and push to an array Scan the document for links to style sheets Ajax grab the stylesheets and traverse looking for matching names to those in class array Apply styles as needed Potential Solution 3 Create an IE6 only stylesheet containing the exact style to be applied as a unique name (ie: class='blocks orange highlight' becomes class='blocks-orange-highlight') Traverse the document in IE6 and convert all spaces in class declarations to hyphens and reapply classes based on new style name Summary: Solution 1 allows the people at this company to apply any styles in the future and the script will adjust as needed. However it does not allow for the chained style to be added, only the individual style... it is also processor intensive and time consuming, but also the most likely to be converted into a plugin that could be used the world over Solution 2 is a potential nightmare to code. But again will allow for an endless number of updates without breaking Solution 3 will require someone at the companty to hardcode the new styles every time they make a change, and if they don't, IE6 will break. Ironically the site, whilst needing to conform to IE6 in a limited manner, does not need to run wihtout javascript (they've made the call... have JS or go away), so consider all jQuery and JS solutions to be 'game on'. Did I mention how much i hate IE6? Anyway... any thoughts or comments would be appreciated. I will continue to develop my own solution and if I discover one that can be turned into a jQuery plugin I will post it here in the comments. Regards, Mike.

    Read the article

  • problem with google chrome

    - by user365559
    hi. i have javscript file for history management.IT is not supported by chrome when i am trying to navigate to back page with backbutton in the browser.I can see the url change but it doesnt go to preceeding page. BrowserHistoryUtils = { addEvent: function(elm, evType, fn, useCapture) { useCapture = useCapture || false; if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } } } BrowserHistory = (function() { // type of browser var browser = { ie: false, firefox: false, safari: false, opera: false, version: -1 }; // if setDefaultURL has been called, our first clue // that the SWF is ready and listening //var swfReady = false; // the URL we'll send to the SWF once it is ready //var pendingURL = ''; // Default app state URL to use when no fragment ID present var defaultHash = ''; // Last-known app state URL var currentHref = document.location.href; // Initial URL (used only by IE) var initialHref = document.location.href; // Initial URL (used only by IE) var initialHash = document.location.hash; // History frame source URL prefix (used only by IE) var historyFrameSourcePrefix = 'history/historyFrame.html?'; // History maintenance (used only by Safari) var currentHistoryLength = -1; var historyHash = []; var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash); var backStack = []; var forwardStack = []; var currentObjectId = null; //UserAgent detection var useragent = navigator.userAgent.toLowerCase(); if (useragent.indexOf("opera") != -1) { browser.opera = true; } else if (useragent.indexOf("msie") != -1) { browser.ie = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4)); } else if (useragent.indexOf("safari") != -1) { browser.safari = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7)); } else if (useragent.indexOf("gecko") != -1) { browser.firefox = true; } if (browser.ie == true && browser.version == 7) { window["_ie_firstload"] = false; } // Accessor functions for obtaining specific elements of the page. function getHistoryFrame() { return document.getElementById('ie_historyFrame'); } function getAnchorElement() { return document.getElementById('firefox_anchorDiv'); } function getFormElement() { return document.getElementById('safari_formDiv'); } function getRememberElement() { return document.getElementById("safari_remember_field"); } // Get the Flash player object for performing ExternalInterface callbacks. // Updated for changes to SWFObject2. function getPlayer(id) { if (id && document.getElementById(id)) { var r = document.getElementById(id); if (typeof r.SetVariable != "undefined") { return r; } else { var o = r.getElementsByTagName("object"); var e = r.getElementsByTagName("embed"); if (o.length > 0 && typeof o[0].SetVariable != "undefined") { return o[0]; } else if (e.length > 0 && typeof e[0].SetVariable != "undefined") { return e[0]; } } } else { var o = document.getElementsByTagName("object"); var e = document.getElementsByTagName("embed"); if (e.length > 0 && typeof e[0].SetVariable != "undefined") { return e[0]; } else if (o.length > 0 && typeof o[0].SetVariable != "undefined") { return o[0]; } else if (o.length > 1 && typeof o[1].SetVariable != "undefined") { return o[1]; } } return undefined; } function getPlayers() { var players = []; if (players.length == 0) { var tmp = document.getElementsByTagName('object'); players = tmp; } if (players.length == 0 || players[0].object == null) { var tmp = document.getElementsByTagName('embed'); players = tmp; } return players; } function getIframeHash() { var doc = getHistoryFrame().contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; } /* Get the current location hash excluding the '#' symbol. */ function getHash() { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. var idx = document.location.href.indexOf('#'); return (idx >= 0) ? document.location.href.substr(idx+1) : ''; } /* Get the current location hash excluding the '#' symbol. */ function setHash(hash) { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. if (hash == '') hash = '#' document.location.hash = hash; } function createState(baseUrl, newUrl, flexAppUrl) { return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null }; } /* Add a history entry to the browser. * baseUrl: the portion of the location prior to the '#' * newUrl: the entire new URL, including '#' and following fragment * flexAppUrl: the portion of the location following the '#' only */ function addHistoryEntry(baseUrl, newUrl, flexAppUrl) { //delete all the history entries forwardStack = []; if (browser.ie) { //Check to see if we are being asked to do a navigate for the first //history entry, and if so ignore, because it's coming from the creation //of the history iframe if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) { currentHref = initialHref; return; } if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) { newUrl = baseUrl + '#' + defaultHash; flexAppUrl = defaultHash; } else { // for IE, tell the history frame to go somewhere without a '#' // in order to get this entry into the browser history. getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl; } setHash(flexAppUrl); } else { //ADR if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) { initialState = createState(baseUrl, newUrl, flexAppUrl); } else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) { backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl); } if (browser.safari) { // for Safari, submit a form whose action points to the desired URL if (browser.version <= 419.3) { var file = window.location.pathname.toString(); file = file.substring(file.lastIndexOf("/")+1); getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>'; //get the current elements and add them to the form var qs = window.location.search.substring(1); var qs_arr = qs.split("&"); for (var i = 0; i < qs_arr.length; i++) { var tmp = qs_arr[i].split("="); var elem = document.createElement("input"); elem.type = "hidden"; elem.name = tmp[0]; elem.value = tmp[1]; document.forms.historyForm.appendChild(elem); } document.forms.historyForm.submit(); } else { top.location.hash = flexAppUrl; } // We also have to maintain the history by hand for Safari historyHash[history.length] = flexAppUrl; _storeStates(); } else { // Otherwise, write an anchor into the page and tell the browser to go there addAnchor(flexAppUrl); setHash(flexAppUrl); } } backStack.push(createState(baseUrl, newUrl, flexAppUrl)); } function _storeStates() { if (browser.safari) { getRememberElement().value = historyHash.join(","); } } function handleBackButton() { //The "current" page is always at the top of the history stack. var current = backStack.pop(); if (!current) { return; } var last = backStack[backStack.length - 1]; if (!last && backStack.length == 0){ last = initialState; } forwardStack.push(current); } function handleForwardButton() { //summary: private method. Do not call this directly. var last = forwardStack.pop(); if (!last) { return; } backStack.push(last); } function handleArbitraryUrl() { //delete all the history entries forwardStack = []; } /* Called periodically to poll to see if we need to detect navigation that has occurred */ function checkForUrlChange() { if (browser.ie) { if (currentHref != document.location.href && currentHref + '#' != document.location.href) { //This occurs when the user has navigated to a specific URL //within the app, and didn't use browser back/forward //IE seems to have a bug where it stops updating the URL it //shows the end-user at this point, but programatically it //appears to be correct. Do a full app reload to get around //this issue. if (browser.version < 7) { currentHref = document.location.href; document.location.reload(); } else { if (getHash() != getIframeHash()) { // this.iframe.src = this.blankURL + hash; var sourceToSet = historyFrameSourcePrefix + getHash(); getHistoryFrame().src = sourceToSet; } } } } if (browser.safari) { // For Safari, we have to check to see if history.length changed. if (currentHistoryLength >= 0 && history.length != currentHistoryLength) { //alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|")); // If it did change, then we have to look the old state up // in our hand-maintained array since document.location.hash // won't have changed, then call back into BrowserManager. currentHistoryLength = history.length; var flexAppUrl = historyHash[currentHistoryLength]; if (flexAppUrl == '') { //flexAppUrl = defaultHash; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } _storeStates(); } } if (browser.firefox) { if (currentHref != document.location.href) { var bsl = backStack.length; var urlActions = { back: false, forward: false, set: false } if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) { urlActions.back = true; // FIXME: could this ever be a forward button? // we can't clear it because we still need to check for forwards. Ugg. // clearInterval(this.locationTimer); handleBackButton(); } // first check to see if we could have gone forward. We always halt on // a no-hash item. if (forwardStack.length > 0) { if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) { urlActions.forward = true; handleForwardButton(); } } // ok, that didn't work, try someplace back in the history stack if ((bsl >= 2) && (backStack[bsl - 2])) { if (backStack[bsl - 2].flexAppUrl == getHash()) { urlActions.back = true; handleBackButton(); } } if (!urlActions.back && !urlActions.forward) { var foundInStacks = { back: -1, forward: -1 } for (var i = 0; i < backStack.length; i++) { if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.back = i; } } for (var i = 0; i < forwardStack.length; i++) { if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.forward = i; } } handleArbitraryUrl(); } // Firefox changed; do a callback into BrowserManager to tell it. currentHref = document.location.href; var flexAppUrl = getHash(); if (flexAppUrl == '') { //flexAppUrl = defaultHash; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } } //setTimeout(checkForUrlChange, 50); } /* Write an anchor into the page to legitimize it as a URL for Firefox et al. */ function addAnchor(flexAppUrl) { if (document.getElementsByName(flexAppUrl).length == 0) { getAnchorElement().innerHTML += "<a name='" + flexAppUrl + "'>" + flexAppUrl + "</a>"; } } var _initialize = function () { if (browser.ie) { var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html"); } } historyFrameSourcePrefix = iframe_location + "?"; var src = historyFrameSourcePrefix; var iframe = document.createElement("iframe"); iframe.id = 'ie_historyFrame'; iframe.name = 'ie_historyFrame'; //iframe.src = historyFrameSourcePrefix; try { document.body.appendChild(iframe); } catch(e) { setTimeout(function() { document.body.appendChild(iframe); }, 0); } } if (browser.safari) { var rememberDiv = document.createElement("div"); rememberDiv.id = 'safari_rememberDiv'; document.body.appendChild(rememberDiv); rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">'; var formDiv = document.createElement("div"); formDiv.id = 'safari_formDiv'; document.body.appendChild(formDiv); var reloader_content = document.createElement('div'); reloader_content.id = 'safarireloader'; var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { html = (new String(s.src)).replace(".js", ".html"); } } reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>'; document.body.appendChild(reloader_content); reloader_content.style.position = 'absolute'; reloader_content.style.left = reloader_content.style.top = '-9999px'; iframe = reloader_content.getElementsByTagName('iframe')[0]; if (document.getElementById("safari_remember_field").value != "" ) { historyHash = document.getElementById("safari_remember_field").value.split(","); } } if (browser.firefox) { var anchorDiv = document.createElement("div"); anchorDiv.id = 'firefox_anchorDiv'; document.body.appendChild(anchorDiv); } //setTimeout(checkForUrlChange, 50); } return { historyHash: historyHash, backStack: function() { return backStack; }, forwardStack: function() { return forwardStack }, getPlayer: getPlayer, initialize: function(src) { _initialize(src); }, setURL: function(url) { document.location.href = url; }, getURL: function() { return document.location.href; }, getTitle: function() { return document.title; }, setTitle: function(title) { try { backStack[backStack.length - 1].title = title; } catch(e) { } //if on safari, set the title to be the empty string. if (browser.safari) { if (title == "") { try { var tmp = window.location.href.toString(); title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#")); } catch(e) { title = ""; } } } document.title = title; }, setDefaultURL: function(def) { defaultHash = def; def = getHash(); //trailing ? is important else an extra frame gets added to the history //when navigating back to the first page. Alternatively could check //in history frame navigation to compare # and ?. if (browser.ie) { window['_ie_firstload'] = true; var sourceToSet = historyFrameSourcePrefix + def; var func = function() { getHistoryFrame().src = sourceToSet; window.location.replace("#" + def); setInterval(checkForUrlChange, 50); } try { func(); } catch(e) { window.setTimeout(function() { func(); }, 0); } } if (browser.safari) { currentHistoryLength = history.length; if (historyHash.length == 0) { historyHash[currentHistoryLength] = def; var newloc = "#" + def; window.location.replace(newloc); } else { //alert(historyHash[historyHash.length-1]); } //setHash(def); setInterval(checkForUrlChange, 50); } if (browser.firefox || browser.opera) { var reg = new RegExp("#" + def + "$"); if (window.location.toString().match(reg)) { } else { var newloc ="#" + def; window.location.replace(newloc); } setInterval(checkForUrlChange, 50); //setHash(def); } }, /* Set the current browser URL; called from inside BrowserManager to propagate * the application state out to the container. */ setBrowserURL: function(flexAppUrl, objectId) { if (browser.ie && typeof objectId != "undefined") { currentObjectId = objectId; } //fromIframe = fromIframe || false; //fromFlex = fromFlex || false; //alert("setBrowserURL: " + flexAppUrl); //flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ; var pos = document.location.href.indexOf('#'); var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href; var newUrl = baseUrl + '#' + flexAppUrl; if (document.location.href != newUrl && document.location.href + '#' != newUrl) { currentHref = newUrl; addHistoryEntry(baseUrl, newUrl, flexAppUrl); currentHistoryLength = history.length; } return false; }, browserURLChange: function(flexAppUrl) { var objectId = null; if (browser.ie && currentObjectId != null) { objectId = currentObjectId; } pendingURL = ''; if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { try { pl[i].browserURLChange(flexAppUrl); } catch(e) { } } } else { try { getPlayer(objectId).browserURLChange(flexAppUrl); } catch(e) { } } currentObjectId = null; } } })(); // Initialization // Automated unit testing and other diagnostics function setURL(url) { document.location.href = url; } function backButton() { history.back(); } function forwardButton() { history.forward(); } function goForwardOrBackInHistory(step) { history.go(step); } //BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); }); (function(i) { var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st = setTimeout; if(/webkit/i.test(u)){ st(function(){ var dr=document.readyState; if(dr=="loaded"||dr=="complete"){i()} else{st(arguments.callee,10);}},10); } else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){ document.addEventListener("DOMContentLoaded",i,false); } else if(e){ (function(){ var t=document.createElement('doc:rdy'); try{t.doScroll('left'); i();t=null; }catch(e){st(arguments.callee,0);}})(); } else{ window.onload=i; } })( function() {BrowserHistory.initialize();} );

    Read the article

< Previous Page | 1 2 3