Overwrite Javascript SetTimeout time but keep the inside function - javascript

I'm trying to make a tampermonkey script to reduce the time of a javascript function (SetTimeout) in order to get faster redirect of a page. The page code is this one:
<script type="text/javascript">
window.setTimeout(function() {
window.location.replace("http://linkhere.com/R4NDoM1CODEHeRE" + window.location.hash);
}, 3000);
</script>
I always end up in the same page after being redirected by this one (just like those ADs that forces you to fill reCaptcha and then they transfer you back again to the same page, ask you to wait some seconds and then transfer to another reCaptcha page).
Could someone help me in this task?

It's possible to use a regex to find http://mylinkhere.link and immediately redirect to it (or display the button if you prefer).
Something like this should work:
var target = /document\.getElementById\('show'\)\.innerHTML = '<a href="([^"]*)|replace\("([^"]*)" \+ window/.exec(document.documentElement.innerHTML);
window.location = target[1] || target[2];
Edit: Corrected answer. Changed contents to document.documentElement.innerHTML.
Edit 2: Corrected answer again.
Edit 3: Updated the answer so it works on both pages from original question.

To be more general, overwrite the window.setTimeout function.
window.setTimeout = ((original) =>
(codeOrFunc, delay, ...args) =>
original(codeOrFunc, 0, ...args)
)(window.setTimeout);

#Originato solution in chat:
(function() {
'use strict';
window.seconds = -1;
var target = /document\.getElementById\('show'\)\.innerHTML = '<a href="([^"]*)|replace\("([^"]*)" \+ window/.exec(document.documentElement.innerHTML);
window.location = target[1] || target[2];
})();

Related

Change content in iframe without reloading page with AJAX and Jquery [duplicate]

I would like to reload an <iframe> using JavaScript. The best way I found until now was set the iframe’s src attribute to itself, but this isn’t very clean. Any ideas?
document.getElementById('some_frame_id').contentWindow.location.reload();
be careful, in Firefox, window.frames[] cannot be indexed by id, but by name or index
document.getElementById('iframeid').src = document.getElementById('iframeid').src
It will reload the iframe, even across domains!
Tested with IE7/8, Firefox and Chrome.
Note: As mentioned by #user85461, this approach doesn't work if the iframe src URL has a hash in it (e.g. http://example.com/#something).
If using jQuery, this seems to work:
$('#your_iframe').attr('src', $('#your_iframe').attr('src'));
Appending an empty string to the src attribute of the iFrame also reloads it automatically.
document.getElementById('id').src += '';
window.frames['frameNameOrIndex'].location.reload();
Because of the same origin policy, this won't work when modifying an iframe pointing to a different domain. If you can target newer browsers, consider using HTML5's Cross-document messaging. You view the browsers that support this feature here: http://caniuse.com/#feat=x-doc-messaging.
If you can't use HTML5 functionality, then you can follow the tricks outlined here: http://softwareas.com/cross-domain-communication-with-iframes. That blog entry also does a good job of defining the problem.
I've just come up against this in chrome and the only thing that worked was removing and replacing the iframe. Example:
$(".iframe_wrapper").find("iframe").remove();
var iframe = $('<iframe src="' + src + '" frameborder="0"></iframe>');
$.find(".iframe_wrapper").append(iframe);
Pretty simple, not covered in the other answers.
Simply replacing the src attribute of the iframe element was not satisfactory in my case because one would see the old content until the new page is loaded. This works better if you want to give instant visual feedback:
var url = iframeEl.src;
iframeEl.src = 'about:blank';
setTimeout(function() {
iframeEl.src = url;
}, 10);
A refinement on yajra's post ... I like the thought, but hate the idea of browser detection.
I rather take ppk's view of using object detection instead of browser detection,
(http://www.quirksmode.org/js/support.html),
because then you're actually testing the capabilities of the browser and acting accordingly, rather than what you think the browser is capable of at that time. Also doesn't require so much ugly browser ID string parsing, and doesn't exclude perfectly capable browsers of which you know nothing about.
So, instead of looking at navigator.AppName, why not do something like this, actually testing for the elements you use? (You could use try {} blocks if you want to get even fancier, but this worked for me.)
function reload_message_frame() {
var frame_id = 'live_message_frame';
if(window.document.getElementById(frame_id).location ) {
window.document.getElementById(frame_id).location.reload(true);
} else if (window.document.getElementById(frame_id).contentWindow.location ) {
window.document.getElementById(frame_id).contentWindow.location.reload(true);
} else if (window.document.getElementById(frame_id).src){
window.document.getElementById(frame_id).src = window.document.getElementById(frame_id).src;
} else {
// fail condition, respond as appropriate, or do nothing
alert("Sorry, unable to reload that frame!");
}
}
This way, you can go try as many different permutations as you like or is necessary, without causing javascript errors, and do something sensible if all else fails. It's a little more work to test for your objects before using them, but, IMO, makes for better and more failsafe code.
Worked for me in IE8, Firefox (15.0.1), Chrome (21.0.1180.89 m), and Opera (12.0.2) on Windows.
Maybe I could do even better by actually testing for the reload function, but that's enough for me right now. :)
for new url
location.assign("http:google.com");
The assign() method loads a new document.
reload
location.reload();
The reload() method is used to reload the current document.
Another solution.
const frame = document.getElementById("my-iframe");
frame.parentNode.replaceChild(frame.cloneNode(), frame);
Now to make this work on chrome 66, try this:
const reloadIframe = (iframeId) => {
const el = document.getElementById(iframeId)
const src = el.src
el.src = ''
setTimeout(() => {
el.src = src
})
}
In IE8 using .Net, setting the iframe.src for the first time is ok,
but setting the iframe.src for the second time is not raising the page_load of the iframed page.
To solve it i used iframe.contentDocument.location.href = "NewUrl.htm".
Discover it when used jQuery thickBox and tried to reopen same page in the thickbox iframe.
Then it just showed the earlier page that was opened.
Use reload for IE and set src for other browsers. (reload does not work on FF)
tested on IE 7,8,9 and Firefox
if(navigator.appName == "Microsoft Internet Explorer"){
window.document.getElementById('iframeId').contentWindow.location.reload(true);
}else {
window.document.getElementById('iframeId').src = window.document.getElementById('iframeId').src;
}
If you using Jquery then there is one line code.
$('#iframeID',window.parent.document).attr('src',$('#iframeID',window.parent.document).attr('src'));
and if you are working with same parent then
$('#iframeID',parent.document).attr('src',$('#iframeID',parent.document).attr('src'));
Using self.location.reload() will reload the iframe.
<iframe src="https://vivekkumar11432.wordpress.com/" width="300" height="300"></iframe>
<br><br>
<input type='button' value="Reload" onclick="self.location.reload();" />
<script type="text/javascript">
top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script>
If all of the above doesn't work for you:
window.location.reload();
This for some reason refreshed my iframe instead of the whole script. Maybe because it is placed in the frame itself, while all those getElemntById solutions work when you try to refresh a frame from another frame?
Or I don't understand this fully and talk gibberish, anyways this worked for me like a charm :)
Have you considered appending to the url a meaningless query string parameter?
<iframe src="myBaseURL.com/something/" />
<script>
var i = document.getElementsById("iframe")[0],
src = i.src,
number = 1;
//For an update
i.src = src + "?ignoreMe=" + number;
number++;
</script>
It won't be seen & if you are aware of the parameter being safe then it should be fine.
Reload from inside Iframe
If your app is inside an Iframe you can refresh it with replacing the location href:
document.location.href = document.location.href
If you tried all of the other suggestions, and couldn't get any of them to work (like I couldn't), here's something you can try that may be useful.
HTML
<a class="refresh-this-frame" rel="#iframe-id-0">Refresh</a>
<iframe src="" id="iframe-id-0"></iframe>
JS
$('.refresh-this-frame').click(function() {
var thisIframe = $(this).attr('rel');
var currentState = $(thisIframe).attr('src');
function removeSrc() {
$(thisIframe).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(thisIframe).attr('src', currentState);
}
setTimeout (replaceSrc, 200);
});
I initially set out to try and save some time with RWD and cross-browser testing. I wanted to create a quick page that housed a bunch of iframes, organized into groups that I would show/hide at will. Logically you'd want to be able to easily and quickly refresh any given frame.
I should note that the project I am working on currently, the one in use in this test-bed, is a one-page site with indexed locations (e.g. index.html#home). That may have had something to do with why I couldn't get any of the other solutions to refresh my particular frame.
Having said that, I know it's not the cleanest thing in the world, but it works for my purposes. Hope this helps someone. Now if only I could figure out how to keep the iframe from scrolling the parent page each time there's animation inside iframe...
EDIT:
I realized that this doesn't "refresh" the iframe like I'd hoped it would. It will reload the iframe's initial source though. Still can't figure out why I couldn't get any of the other options to work..
UPDATE:
The reason I couldn't get any of the other methods to work is because I was testing them in Chrome, and Chrome won't allow you to access an iframe's content (Explanation: Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file?) if it doesn't originate from the same location (so far as I understand it). Upon further testing, I can't access contentWindow in FF either.
AMENDED JS
$('.refresh-this-frame').click(function() {
var targetID = $(this).attr('rel');
var targetSrc = $(targetID).attr('src');
var cleanID = targetID.replace("#","");
var chromeTest = ( navigator.userAgent.match(/Chrome/g) ? true : false );
var FFTest = ( navigator.userAgent.match(/Firefox/g) ? true : false );
if (chromeTest == true) {
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(targetID).attr('src', targetSrc);
}
setTimeout (replaceSrc, 200);
}
if (FFTest == true) {
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(targetID).attr('src', targetSrc);
}
setTimeout (replaceSrc, 200);
}
if (chromeTest == false && FFTest == false) {
var targetLoc = (document.getElementById(cleanID).contentWindow.location).toString();
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc2() {
$(targetID).attr('src', targetLoc);
}
setTimeout (replaceSrc2, 200);
}
});
For debugging purposes one could open the console, change the execution context to the frame that he wants refreshed, and do document.location.reload()
I had a problem with this because I didnt use a timeout to give the page time to update, I set the src to '', and then set it back to the original url, but nothing happened:
function reload() {
document.getElementById('iframe').src = '';
document.getElementById('iframe').src = url;
}
but it didnt reload the site, because it is single threaded, the first change doesnt do anything, because that function is still taking up the thread, and then it sets it back to the original url, and I guess chrome doesnt reload because preformance or whatever, so you need to do:
function setBack() {
document.getElementById('iframe').src = url;
}
function reload() {
document.getElementById('iframe').src = '';
setTimeout(setBack,100);
}
if the setTimeout time is too short, it doesnt work, so if its not working, try set it to 500 or something and see if it works then.
this was in the latest version of chrome at the time of writing this.
This way avoids adding history to some browsers (an unneeded overhead). In the body section put:
<div id='IF'>
<iframe src='https://www.wolframalpha.com/input?i=Memphis%20TN%20Temperature'
style="width:5in; height:6in" // or whatever you want in your Iframe
title'Temperature'></iframe>
</div>
Then in some JAVASCRIPT you may have a function like:
function UPdate() { // Iframe
T1=document.getElementById('IF')
T2=T1.innerHTML
T1.innerHTML=T2
}

How to reload an iframe in Javascript? [duplicate]

I would like to reload an <iframe> using JavaScript. The best way I found until now was set the iframe’s src attribute to itself, but this isn’t very clean. Any ideas?
document.getElementById('some_frame_id').contentWindow.location.reload();
be careful, in Firefox, window.frames[] cannot be indexed by id, but by name or index
document.getElementById('iframeid').src = document.getElementById('iframeid').src
It will reload the iframe, even across domains!
Tested with IE7/8, Firefox and Chrome.
Note: As mentioned by #user85461, this approach doesn't work if the iframe src URL has a hash in it (e.g. http://example.com/#something).
If using jQuery, this seems to work:
$('#your_iframe').attr('src', $('#your_iframe').attr('src'));
Appending an empty string to the src attribute of the iFrame also reloads it automatically.
document.getElementById('id').src += '';
window.frames['frameNameOrIndex'].location.reload();
Because of the same origin policy, this won't work when modifying an iframe pointing to a different domain. If you can target newer browsers, consider using HTML5's Cross-document messaging. You view the browsers that support this feature here: http://caniuse.com/#feat=x-doc-messaging.
If you can't use HTML5 functionality, then you can follow the tricks outlined here: http://softwareas.com/cross-domain-communication-with-iframes. That blog entry also does a good job of defining the problem.
I've just come up against this in chrome and the only thing that worked was removing and replacing the iframe. Example:
$(".iframe_wrapper").find("iframe").remove();
var iframe = $('<iframe src="' + src + '" frameborder="0"></iframe>');
$.find(".iframe_wrapper").append(iframe);
Pretty simple, not covered in the other answers.
Simply replacing the src attribute of the iframe element was not satisfactory in my case because one would see the old content until the new page is loaded. This works better if you want to give instant visual feedback:
var url = iframeEl.src;
iframeEl.src = 'about:blank';
setTimeout(function() {
iframeEl.src = url;
}, 10);
A refinement on yajra's post ... I like the thought, but hate the idea of browser detection.
I rather take ppk's view of using object detection instead of browser detection,
(http://www.quirksmode.org/js/support.html),
because then you're actually testing the capabilities of the browser and acting accordingly, rather than what you think the browser is capable of at that time. Also doesn't require so much ugly browser ID string parsing, and doesn't exclude perfectly capable browsers of which you know nothing about.
So, instead of looking at navigator.AppName, why not do something like this, actually testing for the elements you use? (You could use try {} blocks if you want to get even fancier, but this worked for me.)
function reload_message_frame() {
var frame_id = 'live_message_frame';
if(window.document.getElementById(frame_id).location ) {
window.document.getElementById(frame_id).location.reload(true);
} else if (window.document.getElementById(frame_id).contentWindow.location ) {
window.document.getElementById(frame_id).contentWindow.location.reload(true);
} else if (window.document.getElementById(frame_id).src){
window.document.getElementById(frame_id).src = window.document.getElementById(frame_id).src;
} else {
// fail condition, respond as appropriate, or do nothing
alert("Sorry, unable to reload that frame!");
}
}
This way, you can go try as many different permutations as you like or is necessary, without causing javascript errors, and do something sensible if all else fails. It's a little more work to test for your objects before using them, but, IMO, makes for better and more failsafe code.
Worked for me in IE8, Firefox (15.0.1), Chrome (21.0.1180.89 m), and Opera (12.0.2) on Windows.
Maybe I could do even better by actually testing for the reload function, but that's enough for me right now. :)
for new url
location.assign("http:google.com");
The assign() method loads a new document.
reload
location.reload();
The reload() method is used to reload the current document.
Another solution.
const frame = document.getElementById("my-iframe");
frame.parentNode.replaceChild(frame.cloneNode(), frame);
Now to make this work on chrome 66, try this:
const reloadIframe = (iframeId) => {
const el = document.getElementById(iframeId)
const src = el.src
el.src = ''
setTimeout(() => {
el.src = src
})
}
In IE8 using .Net, setting the iframe.src for the first time is ok,
but setting the iframe.src for the second time is not raising the page_load of the iframed page.
To solve it i used iframe.contentDocument.location.href = "NewUrl.htm".
Discover it when used jQuery thickBox and tried to reopen same page in the thickbox iframe.
Then it just showed the earlier page that was opened.
Use reload for IE and set src for other browsers. (reload does not work on FF)
tested on IE 7,8,9 and Firefox
if(navigator.appName == "Microsoft Internet Explorer"){
window.document.getElementById('iframeId').contentWindow.location.reload(true);
}else {
window.document.getElementById('iframeId').src = window.document.getElementById('iframeId').src;
}
If you using Jquery then there is one line code.
$('#iframeID',window.parent.document).attr('src',$('#iframeID',window.parent.document).attr('src'));
and if you are working with same parent then
$('#iframeID',parent.document).attr('src',$('#iframeID',parent.document).attr('src'));
Using self.location.reload() will reload the iframe.
<iframe src="https://vivekkumar11432.wordpress.com/" width="300" height="300"></iframe>
<br><br>
<input type='button' value="Reload" onclick="self.location.reload();" />
<script type="text/javascript">
top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script>
If all of the above doesn't work for you:
window.location.reload();
This for some reason refreshed my iframe instead of the whole script. Maybe because it is placed in the frame itself, while all those getElemntById solutions work when you try to refresh a frame from another frame?
Or I don't understand this fully and talk gibberish, anyways this worked for me like a charm :)
Have you considered appending to the url a meaningless query string parameter?
<iframe src="myBaseURL.com/something/" />
<script>
var i = document.getElementsById("iframe")[0],
src = i.src,
number = 1;
//For an update
i.src = src + "?ignoreMe=" + number;
number++;
</script>
It won't be seen & if you are aware of the parameter being safe then it should be fine.
Reload from inside Iframe
If your app is inside an Iframe you can refresh it with replacing the location href:
document.location.href = document.location.href
If you tried all of the other suggestions, and couldn't get any of them to work (like I couldn't), here's something you can try that may be useful.
HTML
<a class="refresh-this-frame" rel="#iframe-id-0">Refresh</a>
<iframe src="" id="iframe-id-0"></iframe>
JS
$('.refresh-this-frame').click(function() {
var thisIframe = $(this).attr('rel');
var currentState = $(thisIframe).attr('src');
function removeSrc() {
$(thisIframe).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(thisIframe).attr('src', currentState);
}
setTimeout (replaceSrc, 200);
});
I initially set out to try and save some time with RWD and cross-browser testing. I wanted to create a quick page that housed a bunch of iframes, organized into groups that I would show/hide at will. Logically you'd want to be able to easily and quickly refresh any given frame.
I should note that the project I am working on currently, the one in use in this test-bed, is a one-page site with indexed locations (e.g. index.html#home). That may have had something to do with why I couldn't get any of the other solutions to refresh my particular frame.
Having said that, I know it's not the cleanest thing in the world, but it works for my purposes. Hope this helps someone. Now if only I could figure out how to keep the iframe from scrolling the parent page each time there's animation inside iframe...
EDIT:
I realized that this doesn't "refresh" the iframe like I'd hoped it would. It will reload the iframe's initial source though. Still can't figure out why I couldn't get any of the other options to work..
UPDATE:
The reason I couldn't get any of the other methods to work is because I was testing them in Chrome, and Chrome won't allow you to access an iframe's content (Explanation: Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file?) if it doesn't originate from the same location (so far as I understand it). Upon further testing, I can't access contentWindow in FF either.
AMENDED JS
$('.refresh-this-frame').click(function() {
var targetID = $(this).attr('rel');
var targetSrc = $(targetID).attr('src');
var cleanID = targetID.replace("#","");
var chromeTest = ( navigator.userAgent.match(/Chrome/g) ? true : false );
var FFTest = ( navigator.userAgent.match(/Firefox/g) ? true : false );
if (chromeTest == true) {
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(targetID).attr('src', targetSrc);
}
setTimeout (replaceSrc, 200);
}
if (FFTest == true) {
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(targetID).attr('src', targetSrc);
}
setTimeout (replaceSrc, 200);
}
if (chromeTest == false && FFTest == false) {
var targetLoc = (document.getElementById(cleanID).contentWindow.location).toString();
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc2() {
$(targetID).attr('src', targetLoc);
}
setTimeout (replaceSrc2, 200);
}
});
For debugging purposes one could open the console, change the execution context to the frame that he wants refreshed, and do document.location.reload()
I had a problem with this because I didnt use a timeout to give the page time to update, I set the src to '', and then set it back to the original url, but nothing happened:
function reload() {
document.getElementById('iframe').src = '';
document.getElementById('iframe').src = url;
}
but it didnt reload the site, because it is single threaded, the first change doesnt do anything, because that function is still taking up the thread, and then it sets it back to the original url, and I guess chrome doesnt reload because preformance or whatever, so you need to do:
function setBack() {
document.getElementById('iframe').src = url;
}
function reload() {
document.getElementById('iframe').src = '';
setTimeout(setBack,100);
}
if the setTimeout time is too short, it doesnt work, so if its not working, try set it to 500 or something and see if it works then.
this was in the latest version of chrome at the time of writing this.
This way avoids adding history to some browsers (an unneeded overhead). In the body section put:
<div id='IF'>
<iframe src='https://www.wolframalpha.com/input?i=Memphis%20TN%20Temperature'
style="width:5in; height:6in" // or whatever you want in your Iframe
title'Temperature'></iframe>
</div>
Then in some JAVASCRIPT you may have a function like:
function UPdate() { // Iframe
T1=document.getElementById('IF')
T2=T1.innerHTML
T1.innerHTML=T2
}

Best way to execute js only on specific page

I was wondering what would be the best way to execute a java-script code only on specific pages.
Let's imagine we have a template-based web-site, rewrite rule for the content ist set, jquery available and it basically looks like this:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
...
include $content;
..
</body>
</html>
content 'info' contains a button, we want something to happen on click, content 'alert' should give us a message when you hover a text field.
What is the best way to trigger these actions, without running into an error, because the object is not found?
Option one: using window.location.pathname
$(document).ready(function() {
if (window.location.pathname == '/info.php') {
$("#button1").click(function(){
//do something
})
}else if(window.location.pathname == '/alert.php'){
$("#mytextfield").hover(){
alert('message');
}
}
Option two: checking if elements exist
$(document).ready(function() {
if ($("#button1").length > 0) {
$("#button1").click(function(){
//do something
})
}else if ($("#mytextfield").length > 0){
$("#mytextfield").hover(){
alert('message');
}
}
Option three: include the script in the loaded template
//stands for itself
Is there a better solution? Or do I have to get along with one of these solutions?
Your experience, usage, or any links related to this topic are appreciated.
//EDIT:
I might have choosen a bad example, the actual code would be somethin like:
mCanvas = $("#jsonCanvas");
mMyPicture = new myPicture (mCanvas);
where the myPicture constructor get's the context of the canvas element, and throws an error, if mCanvas is undefined.
Set a class attribute to your body tag.
<body class="PageType">
And then in your script..
$(function(){
if($('body').is('.PageType')){
//add dynamic script tag using createElement()
OR
//call specific functions
}
});
I would use the switch statement and a variable. (I'm using jQuery!)
var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch(windowLoc){
case "/info.php":
//code here
break;
case "/alert.php":
//code here
break;
}
//use windowLoc as necessary elsewhere
This will allow you to change what "button" does based on the page that you're on. If I understood your question correctly; this is what I would do. Also, if I had were serving large amounts of javascript, I would simply add a new JS file completely.
var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch(windowLoc){
case "/info.php":
var infoJS = document.createElement('script');
infoJS.type = 'text/javascript';
infoJS.src = 'location/to/my/info_file.js';
$('body').append(infoJs);
break;
case "/alert.php":
var alertJS = document.createElement('script');
alertJS.type = 'text/javascript';
alertJS.src = 'location/to/my/alert_file.js';
$('body').append(alertJs);
break;
}
Hope this helps -
Cheers.
A little different approach than checking the URL path : You can group page specific event handlers in a single function and then in each include, have a domready which will call these functions.
Eg: in script.js you have two functions (outside domready) viz. onPage1Load() and onPage2Load().
While in your page1.php you have a $(document).ready(onPage1Load)
and so on for other pages. This will make sure that unintended event handlers are not registered.
You can also use vanilla javascript to do the same
console.log(window.location.href);
const host = "http://127.0.0.1:5500/";
// JAVASCRIPT FOR INDEX PAGE
if (window.location.href == host + 'index.html') {
console.log("this is index page");
}
// JAVASCRIPT FOR ORDER PAGE
if (window.location.href == host + 'order.html') {
console.log("this is order page");
}
You can use Require js (RequireJS is a JavaScript file and module loader) and load script if they only needed. Link is http://requirejs.org/, I know using require js not so much easy.

How to make my function to be page specific or div id specific?

I am writing javascript to my web pages, but there is a number of functions and loops, that i think are running in all pages, so the first one is running and failing on the second page. Because of this, the javascript function on the second page is not running.
Can anyone give me an idea of how to create page-specific functions or check the availability of an id? I don't use any frameworks.
thanks in advance.
my javascript code is :
window.onload = function(){
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
function animeYellowBar(num){
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num * 250);
}
}, num * 500);
}
for (var i = 0; i < yellows.length; i++){
animeYellowBar(i);
}
alert("alert second page");
}
in this code, the alert message not working on second page. any idea?
If I understand you correctly, you have a javascript function, that you want to attach to an event from a specific div element in your page.
a) Include an event directly to you HTML page, something like this:
<div id="element" onclick="some_function();">Text is here</div>
b) Use a javascript function (add this code between <script> tag):
window.onload = function() {
document.getElementById("element").setAttribute("onclick", "some_function()")
}
The best way would be to only include those scripts on the pages which need them. Why waste time loading and parsing scripts you don't need?
If you must keep them on every page, put your functions in an if statement and check for something unique to the page that needs them (such as a form element or field ID).
Update
In response to your comment:
You have to code more defensively. You are attempting to make use of the magazine-brief and signup-link elements before you have made certain that they exist. Never trust that the proper element was returned - always check that it was before attempting to use that element.
I suggest checking your vars like so:
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
if (yellows != 'undefined' && signUp != undefined)
{
function animeYellowBar(num)
{
//...
}
}

How to run a javascript function using the # in the url?

hi this all started when i ran a function (lets call it loadround) that altered the innerHTML of an iframe. now once loadframe was loaded there were links in the iframe that once clicked would change the iframe page. the only problem is when i click the back button the loadround page was gone. i've thought about this numerous times to no avail. so i tried this code.
loadround
then
function loadround(a,b){
window.location.hash = "#loadround('"+a+"','"+b+"')";
var code = "<(h2)>"+a+"</(h2)><(h2)>"+b+"</(h2)>"
var iFrame = document.getElementById('iframe');
var iFrameBody;
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0]
iFrameBody.innerHTML = code;
}
(the brackets in the h2 are intentional)
then i would try to reload the function by possibly an onload function but for now i was testing with a simple href as followed.
function check(){
var func = location.hash.replace(/#/, '')
void(func);
}
check
unfortunately the check code doesn't work and im almost certain there is an easier way of doing this. i tried changing the src of the iframe instead of the innerhtml and there was the same problem. thanks in advance
The modern browsers are starting to support the event window.onhashchange
In the meantime you can use the workaround proposed by Lekensteyn or maybe you can find something useful here: JavaScript/jQuery - onhashchange event workaround
You are misunderstanding the function void, which just make sure the return value is undefined. That prevents the browser from navigating away when you put it in a link. You can test that yourself by pasting the next addresses in your browser:
javascript:1 // note: return value 1, browser will print "1" on screen
javascript:void(1) // note: undefined return value, browser won't navigate away
It's strongly discouraged to execute the hash part as Javascript, as it's vulnerable to XSS without proper validating it. You should watch the hash part, and on modification, do something.
An example; watch every 50 milliseconds for modifications in the hash part, and insert in a element with ID targetElement an heading with the hash part. If the hash part is not valid, replace the current entry with home.
var oldHash = '';
function watchHash(){
// strip the first character (#) from location.hash
var newHash = location.hash.substr(1);
if (oldHash != newHash) {
// assume that the parameter are alphanumeric characters or digits
var validated = newHash.match(/^(\w+)$/);
// make sure the hash is valid
if (validated) {
// usually, you would do a HTTP request and use the parameter
var code = "<h1>" + validated[1] + "</h1>";
var element = document.getElementById("targetElement");
element.innerHTML = code;
} else {
// invalid hash, redirect to #home, without creating a new history entry
location.replace("#home");
}
// and set the new state
oldHash = newHash;
}
}
// periodically (every 50 ms) watch for modification in the hash part
setInterval(watchHash, 50);
HTML code:
Home
About Me
Contact
<div id="targetElement">
<!-- HTML will be inserted here -->
</div>

Categories