Change hard coded JS variable value - javascript

I am using a 3rd party app and they have a JS variable hard coded into their HTML that I need to change / update with Javascript OR jQuery, both are available to use.
The 3rd party app has variables hard coded into the page:
<script type="text/javascript" charset="utf-8">
var order_poNumber = "";
</script>
Which gets updated when a user selects a value from a dropdown (my dropdown, not 3rd party):
<script type="text/javascript" charset="utf-8">
var order_poNumber = "32380080-64060";
</script>
But the issue is that the value sticks for some reason. If you go to another page and come back (not using the back button, but by going to a different page then clicking a link to return to the order page where this issue is happening) the value is still set to 32380080-64060 but I need it to be blank as it originally was.
I've tried:
function resetPO(){
order_poNumber = "";
}
window.onload = resetPO();
And a few other variations of that, but it won't work.
I have to do the JS from an external JS file BTW.
Any ideas?
I am looking for a way to overwrite the value that is stored in the variable order_poNumber in the JS script block that is hard coded in the HTML. Ideally I want some kind of late or even delayed JS to come in and overwrite the value once the page has loaded. There are a lot of steps in how that number gets there once selected from the dropdown (AJAX, ActiveX, JS, jQuery, and a mix of 3rd party app and my own codes and functions) which took a lot of work to get working properly so I don't want to mess with all of that anymore.

The browser back button works differently than an initial page load. You can use jquery-address to add a listener to page changes (including ones from navigational arrows):
$.address.change(function(e) {
resetPO();
});
http://github.com/asual/jquery-address

Heres something I would try, just to see if it could work. We'll ask the browser to keep resetting the value until its actually reset. It does need to be executed after any script that sets the value in the first place, so maybe jQuery's ready() function is more useful than window.onload (which may already be in use by something else). Don't forget to put it before the ending </body> tag to make sure its the last thing being executed or loaded.
window.onload = function(){
var resetValueInterval = setInterval(function(){
order_poNumber = "";
if(order_poNumber == ""){
clearInterval(resetValueInterval);
}
},100);
}
You could also, instead of checking if it is set, stop checking when the value gets set. This could be never and use a lot more resources, but its always worth a try. Of course, if you reduce the amount of time between each iteration it becomes more reasonable. Not the most elegant way around the problem, but it might work.
window.onload = function(){
var resetValueInterval = setInterval(function(){
order_poNumber = "";
},100);
document.getElementById(/* order_poNumber-dropdown-id */).addEventListener("mousedown", function(){
clearInterval(resetValueInterval);
}, false);
}

Related

How to print an iFrame with stylesheet?

I've created this code to print data from an iFrame
function (data) {
var frame = $("<iframe>", {
name: "iFrame",
class: "printFrame"
});
frame.appendTo("body");
var head = $("<head></head>");
_.each($("head link[rel=stylesheet]"), function (link) {
var csslink = $("<link/>", { rel: "stylesheet", href: $(link).prop("href") })
head.append(csslink);
;});
frame.contents().find("head")
.replaceWith(head);
frame.contents().find("body")
.append(this.html());
window.frames["iFrame"].focus();
window.frames["iFrame"].print();
}
This creates an iFrame, adds a head to where it sets all the css links that are needed for this website. Then it creates the body.
Trouble is, the styling won't get applied to the print, unless I break at line frame.contents().find("head").replaceWith(head), which means that something in that part is running asynchronously.
Question is, can I somehow get the code to wait for a short while before running that line, or is there perhaps another way to do this? Unfortunately I'm not all that familiar with iFrames, so I have no clue what it's trying to do there.
This turned out to be a real hassle. I've always been reluctant to using iframes, but since there are many resources saying that using an iframe for printing more stuff than what's on the screen, we figured we'd give it a try.
This was instead solved by putting the data inside a hidden div which then was shown before a window.print(). At the same time, all other elements on the page were given a "hidden-print" class which is a class we're already using to hide elements for prints.
This might not be as elegant for the user (The div will show briefly before the user exits the print dialogue), but it's a way more simpler code to use and manage.
I think you could / should move the last focus() and print() calls to a onload handler for the iframe, to get it to happen after styles are loaded and applied.
I've just run into the same issue and did the following:
setTimeout(() => {
window.frames["iFrame"].focus();
window.frames["iFrame"].print();
}, 500)
This appears to have sorted it for me. I hate using timeout and the length is guess work at best but as it's not system critical it's something I can run with for now.

QuerySelectorAll not working when put in an external js file

When I put this code:
window.onload = function(){
var inputs = document.querySelectorAll("input[type=text]");
console.log(inputs.length);
for(var j=0; j<inputs.length; j++){
inputs[j].onclick = function(){
this.style.width = "500px";
}
}
}
Into an html page, it works great, but if I put it into an external .js file the for loop never starts as inputs.length is equal to 0, even if in the page that calls the script there are plenty of inputs. What could be the problem?
Update:
I found out that the code works in normal conditions, but it doesn't:
on inputs that are contained in a div that was previously hidden and
then was shown via js my bad, the hidden input was of type "email"
on every input if they're loaded via ajax I found out why: since the function is fired only when the window loads, it won't see the loaded inputs
Very often, the placement of your script tag can affect your DOM selection. So make sure that your script tag is placed at the bottom of your html file just before the end of the body tag. Perhaps this will fix the issue!
Try attaching your function with addEventListener instead of setting window.onload:
window.addEventListener(function() {
//...
});
If this solves your problem then as #adeneo said, window.onload is being assigned elsewhere in the script which overwrites any other value it can have.
Which is why in general, using addEventListener is better as you can call it as many times as you want without overwriting anything.
But the problem could also simply be that your script isn't being evaluated at all, did you try putting some top-level console.log in there?
With the help of the users who commented/answered, I found out that some of the inputs I was trying the code to were of type "email" and not "text", while in other cases the inputs were loaded via ajax, so after the DOM was loaded. To fix these problems, I've edited
var inputs = document.querySelectorAll("input[type=text]");
To
var inputs = document.querySelectorAll("input[type=text],input[type=email]");
And I called again the function when the content loaded via ajax was ready.

JavaScript function with interval doesn't work for the first time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to run the function renews() with interval but want to run first time when the html is opened. so I wrote renews(); but it doesn't work. I could run other function of the code. but only this one doesn't.
Thank you for the help!
<html>
<head>
<script>
var i=0;
var u=0; //0:redy for the next FX
var newstext;
function renews() {
if(i%2==0){
newstext = "aaa";
} else {
newstext = "bbb";
}
document.getElementById("news").innerHTML = newstext;
i++;
}
//renews(); // this doesn't work
setInterval(function(){
renews();
},3000);
</script>
</head>
<body>
<span id ="news">test</span>
</body>
</html>
Move your script to the bottom of the body. When you execute your script, the DOM has not been build yet, and thus there is no element to operate on.
When you’re dealing with the DOM it’s important to execute your code only after the page is fully loaded. If you don’t, there’s a good chance the DOM won’t be
created by the time your code executes.
Now Let’s think about what just happened when your code run. you put your js code in the header tag of the page, so it begins executing before the browser even sees the rest of the page. That’s a big problem because that span element with an id of “news” doesn’t exist, yet.
So what happened exactly? The call to getElementById returns null instead of the element you want, causing an error, and the browser, being the good sport that it is, just keeps moving and renders the page anyway, but without the change to the DOM at the first time.
How do you fix this? Well, you could move your code to the bottom of the body, but there’s actually a more foolproof way to make sure this code runs at the right time; a way to tell the browser “run my code after you’ve fully loaded in the page and created the DOM.” Besides moving the code to the bottom of the body, there’s another—and, one might argue—cleaner way to do it with code.
Here’s how it works: first create a function that has the code you’d like
executed once the page is fully loaded. After you’ve done that, you take the
window object, and assign the function to its onload property. The window object will call any function you’ve assigned to its onload property, but only after the page is fully loaded. Check This out:-
<html>
<head>
<script>
var i=0;
var u=0; //0:redy for the next FX
var newstext;
function renews() {
if(i%2==0){
newstext = "aaa";
} else {
newstext = "bbb";
}
document.getElementById("news").innerHTML = newstext;
i++;
}
//renews(); // this doesn't work
window.onload = renews; //But this will work
setInterval(function(){
renews();
},3000);
</script>
</head>
<body>
<span id ="news">test</span>
</body>
Now even if you put your JavaScript code in a separated JS file and import it in the header tag instead of moving it to the end of the body your code will work just fine.

Dynamically replace a character by another one using javascript, without returning the page back to initial state

I have a html page full of dynamically loaded content, but one of the characters everywhere needs to be replaced by another one. The reason is that I am opening this page from android, and one of the symbols does not render properly there, so I want to replace it by a similar looking one.
If I use a script like:
setInterval(function(){
document.body.innerHTML = document.body.innerHTML.replace(/\x/g, '\y');
}, 100);
it reverts the document back to initial state every 100ms, and for example all text in the input fields is lost. How can I replace the characters without reverting the document back to initial state and losing user input?
EDIT: I am using setInterval because the page changes all the time.
You can use JQuery, I'm not sure if this is that you want but try this:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function() {
var strNew = $('body').html().replace(/\x/g, '\y');
$('body').html(strNew);
},100);
});
</script>
You can use setTimeout() instead of setInterval(). Then it will run only once.
setTimeout(function() {
document.body.innerHTML = document.body.innerHTML.replace(/\x/g, '\y');
}, 100);

Trying to load an API and a JS file dynamically

I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.
I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.
Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.
Example: http://jsfiddle.net/7TWYC/
Example with loading API in head section: http://jsfiddle.net/s2HkR/
So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.
EDIT:
I've set a bounty to 250 ontop of the 50 I had previously.
Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.
I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.
Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/
-
EDIT 2 ON Gijs ANSWER:
Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.
I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/
When I used this method, I load the API successfuly but the snippets.js file is not loading at all.
Fiddle: http://jsfiddle.net/9HX7N/
I belive what you want is it:
function loadSkyscanner()
{
function loaded()
{
t.skyscanner.load('snippets', '1', {'nocss' : true});
var snippet = new t.skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
}
var t = document.getElementById('sky_loader').contentWindow;
var head = t.document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange= function() {
if(this.readyState == 'complete') loaded();
}
script.onload= loaded;
script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
head.appendChild(script);
}
$("button").click(function(e)
{
loadSkyscanner();
});
It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.
The only restriction is, you need a iframe. But you can hide it using display:none.
A working example
EDIT
Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document.
When a script is loaded in a iframe, document is the iframe document.
There is a solution, but I don't recommend, is really a workaround:
function loadSkyscanner()
{
var t;
this.skyscanner;
var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");
function realWorkaround()
{
var tbody = t.document.getElementsByTagName("body")[0];
var body = document.getElementsByTagName("body")[0];
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
}
function snippetLoaded()
{
skyscanner = t.skyscanner;
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
setTimeout( realWorkaround, 2000 );
}
var loaded = function()
{
console.log( "loaded" );
t = document.getElementById('sky_loader').contentWindow;
t.onLoadSnippets( snippetLoaded );
}
$("body").append(iframe);
iframe.load(loaded);
}
$("button").click(function(e)
{
loadSkyscanner();
});
Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.
You can see a work example here
The iframe loaded is this
EDIT
Fixed the bug you found and updated the link.
the for loop has gone and added a while, works better now.
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.
So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.
Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).
Here's an almost-working example: http://jsfiddle.net/a8q2s/1/
Here's the steps I took:
override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
Tell Skyscanner to load the module.
Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:
http://jsfiddle.net/a8q2s/3/
(note: this still seems to use a timeout loop internally)
In the skyrunner.js file they are using document.write to make the page blank on load call back... So here are some consequences in your scenario..
This is making page blank when you click on button.
So, it removes everything from page even 'jQuery.js' that is why call back is not working.. i.e main function is cannot be invoked as this is written using jQuery.
And you have missed a target 'div' tag with id = map(according to the code). Actually this is the target where map loads.
Another thing i have observed is maps is not actually a div in current context, that is maps api to load.
Here you must go with the Old school approach, That is.. You should include your skyrunner.js file at the top of the head content.
So try downloading that file and include in head tag.
Thanks

Categories