Is there a race condition to remove the elements? - javascript

I'm very new to JS and HTML. I would like to remove an element from the page as soon as the page is loaded. This is my simple HTML code:
<html>
<head>
</head>
<body>
<div id="trapParent"><a id="trap" href='/trap/removeByJS'> Javascript removal </a></div>
<script>
function timeout() {
setTimeout(function () {
timeout();
}, 1000);
}
timeout();
var parent = document.getElementById('trapParent');
var child = document.getElementById('trap');
while (child & parent){
parent.removeChild(child);
parent = undefined;
child = undefined;
}
</script>
</body>
</html>
But when I open the page I can still get a reference to the link on the page; when I get the value of document.getElementById('trap');, it returns the link which means that it is still in the DOM and I can see that the link is still there. Am I missing something here?
I added the timeout function to make sure that the script will run after the page is loaded.

Thanks to above answers, the following worked for me:
<html>
<head>
</head>
<body onload = "removelink();">
<div id="trapParent"><a id="trap" href='/trap/removeByJS'> disables Javascript </a></div>
Hey!
<script>
function removelink( ){
var parent = document.getElementById('trapParent');
var child = document.getElementById('trap');
while (child && parent){
parent.removeChild(child);
parent = undefined;
child = undefined;
}
}
</script>
</body>
</html>

Related

Run javascript function on loaded page

Very new to Javascript, so working on my first project. Attempting to run a script that gathers listing numbers, opens them in a URL and clicks an element on the loaded page. I can't get .click() to run on the resulting loaded page.
I've tried to set the logIn function to only run once the resulting page has loaded, but it doesn't seem to be doing the trick. AM I missing something basic?
var listingNum = prompt("Listing numbers").split(" ");
logIn = function(){
if(document.readyState === "complete"){
document.getElementById('SignInAsMemberLinkHeader').click();
}
};
for(i = 0; i < listingNum.length; i++){
window.open("http://www.website.com" + listingNum[i],"_self");
setInterval(logIn(), 4000);
};
Okay, the following test harness worked for me. I had to change your _self reference to _blank, so that each page loads separately and doesn't overwrite the operation of the parent page. You then just handle the load event of each window that is instantiated using window.open(). This was the part you were missing. You weren't handling the load events of the loaded windows.
You may wish to check that the SignInAsMemberLinkHeader element exists prior to calling click() on it, but I'll leave that up to you to implement.
NB this will not work if cross site scripting restrictions apply.
Hope this helps :)
<!DOCTYPE HTML>
<html>
<head>
<title>External Page Opener Test</title>
<meta charset="UTF-8">
<style>
body {
background-color:cornflowerblue;
color:white;
font-family:Tahoma,Arial,sans-serif;
}
</style>
<script>
window.addEventListener('load', init, false);
function init(event) {
var listings = prompt("Listing numbers:");
if (listings) {
var listingNum = listings.split(" ");
for (i = 0; i < listingNum.length; i++) {
// I used my local desktop and 3 test HTML files,
//each with a button click and handler on them.
var url = "file:///C:/Users/******/Desktop/" + listingNum[i];
var handle = window.open(url, "_blank");
handle.addEventListener('load', extPageLoaded, false);
}
} else {
console.log('No listings were entered.');
}
}
function extPageLoaded(event) {
const TIME_TO_WAIT_IN_MILLISECONDS = 4000;
setTimeout(
function() {
event.target.getElementById('SignInAsMemberLinkHeader').click();
},
TIME_TO_WAIT_IN_MILLISECONDS
);
}
</script>
</head>
<body>
</body>
</html>

Trigger a script

I've a script (an ads one) and I'd like to to trigger him out only when a button on my site has been clicked for X times.
<script type="text/javascript" src="ADS_URL"></script>
Let's assume this is my script. This is what I've done to find when the button has been clicked 5 times, but after it I'm blocked. I don't know how to trigger the script out.
Where should I paste the script? Thank you for the help!
$("#button").click(function() {
nclick++;
if (nclick == 7) {
nclick = 0;
// Make something
};
});
The following code works fine for me:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
"use strict";
var nclick = 0;
$(document).ready(function() {
// ===== START OF QUESTION CODE =====
$("#button").click(function() {
nclick++;
if (nclick == 7) {
nclick = 0;
alert("Pretend that this is an ad.");
}
});
// ===== END OF QUESTION CODE =====
});
</script>
</head>
<body>
<a id="button" href="#">Click me!</a>
</body>
</html>
If your code is not running:
Check the browser console. Are there any errors?
Is jQuery included on your page?
Are you attaching the #button function when the page is ready? You might be attempting to add an event before the button is created.
Have you declared an nclick variable and initialised it to zero?
EDIT
Okay, the question has now been clarified - the ad script appears as soon as the page is loaded, but you want to delay it until a button has been clicked 7 times. The solution is basically the same as the above, though:
ads.js
alert("hello, world!");
example.htm
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
"use strict";
var nclick = 0;
var ad_script = null;
$(document).ready(function() {
// ===== START OF QUESTION CODE =====
$("#button").click(function() {
nclick++;
if (nclick == 7) {
nclick = 0;
ad_script = document.body.appendChild(document.createElement("script"));
ad_script.src = "ads.js"
}
else if (ad_script)
{
document.body.removeChild(ad_script);
ad_script = null;
}
});
// ===== END OF QUESTION CODE =====
});
</script>
</head>
<body>
<a id="button" href="#">Click me!</a>
</body>
</html>
Simply add the script into the page once the counter reaches 7.
create script tag & remove script tag
cScript();
var nclick=0;
$("#button").click(function() {
nclick++;
if (nclick == 7) {
rScript();
nclick = 0;
// Make something
};
});
function cScript(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'ADS_URL';
$("#someElement").append( script );
}
function rScript(){
var html = $("#someElement");
html.find('script').remove();
}
If i understood you correctly your JQuery event is not getting executed?
You need to add the JQuery's source first:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js? ver=1.4.2"></script>
<script type="text/javascript" src="ADS_URL"></script>
</head>
If you don't have the source for JQuery included it won't know what you mean. with $("#button").click

HashChange events stop firing when an Angular ng-include exists on the page

I have the following HTML+Angular app shell that does everything I need it to do:
If the URL hash is empty when the page loads, it gets initialized to #/.
Whenever the URL hash changes, the view variable is updated.
This much works perfectly:
<!DOCTYPE html>
<html ng-app>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
<script>
function Router($scope) {
if (location.hash === "") location.hash = "#/";
$scope.view = createView(location);
window.addEventListener("hashchange", function (event) {
$scope.view = createView(event.newURL);
$scope.$apply();
});
}
function createView(url) {
var parser = document.createElement("a");
parser.href = url.toString();
var hash = parser.hash;
return (hash.replace("#/", "/views/") + "/index.html").replace("//", "/");
}
</script>
</head>
<body ng-controller="Router">
Navigation:
one
two
Partial: {{view}}
<!--<div ng-include="view"></div>-->
</body>
</html>
Then only problem is that as soon as I uncomment the div[ng-include], everything stops working. Specifically, the hashchange events stop firing. Am I doing something wrong or is this a bug? Any workarounds?

Redirect from iFrame using javascript or Jquery

If a website is loaded into an iframe, what code do I need to put on the child page of that iFrame to break out of the iFrame and load that page as the top document or reidrect to that page
Just found the code
<script>
if(window.top !== window.self){
window.top.location.href = "http://www.blah.com";
}
</script>
Even better code:
<style> html{display : none ; } </style>
<script>
if( self == top ) {
document.documentElement.style.display = 'block' ;
} else {
top.location = self.location ;
}
</script>
Code Example below:
<!DOCTYPE html>
<html lang="en">
<head>
blah
</head>
<body>
<iframe src="www.blah.com"></iframe>
</body>
</html>
What JQuery or javascript do I need to put on (in this example) www.blah.com so it breaks out of the iframe and www.blah.com is directly shown to the user?
What you're looking for is called a Framekiller
Here's the suggested implementation from that article:
<style> html{display : none ; } </style>
<script>
if( self == top ) {
document.documentElement.style.display = 'block' ;
} else {
top.location = self.location ;
}
</script>
This should work:-
<script type="text/javascript">
if (window!=top){top.location.href=location.href;}
</script>
window.top.location.href = "http://blah.com/";
As mentioned here (with a fuller explanation):
Redirect parent window from an iframe action
If you are using a link setting target="_top" attribute probably would do the job.

Can one set an iframe's src and manipulate its contents afterwards?

My goal is to have a parent page change the src of an iframe from blank to its proper url (as to utilize an onload handler in the iframe at a given point, but that's beside the point) and then manipulate the iframe's contents. However, javascript seems oblivious to any elements of an iframe that aren't on its src when the DOM loads. Is there any way around this?
The setTimeouts are intended to allow the DOM and iframe to load.
edit:fixed some stuff.
Here's the containing page:
<html><head>
<script type="text/javascript">
var done = false;
var theIframe;
window.onload = function () {
setTimeout('stuff()', 2000);
clearTimeout('stuff()');
}
function stuff() {
if (!done) {
theIframe = window.myiframe;
theIframe.src = 'http://localhost/TestStuff/redirectIframe.jsp';
done = true;
stuff();
} else {
theIframe.setMe = true;
}
}
</script>
</head>
<body>
<iframe src="" width="500" height="500" id="myiframe" name="myiframe">
</iframe>
</body>
And here's the iframe:
<html>
<head>
<script type="text/javascript">
var setMe = false;
window.onload = setInterval('checker()', 1000);
function checker() {
alert('hi');
if (setMe) {
window.onload = null;
top.location = 'http://www.google.com';
alert('foundit');
} else alert('a');
}
</script>
</head>
<body></body>
</html>
Any ideas?
In this piece of code:
theIframe.src = ...;
stuff();
you're calling stuff() immediately, contrary to what you have described, so in fact you're not allowing any time for the page to load. Maybe you're confused about how setTimeout works: it just schedules a single execution after the specified time, it doesn't automatically delay all calls to a function.
Also, you can use clearTimeout only with a previous ID returned by setTimeout, not with code as you have now.
Try something like this:
window.onload = function() {
loadFrame();
}
function loadFrame() {
theIframe = ...;
theIframe.src = ...;
setTimeout(setSomething, 2000);
}
function setSomething() {
theIframe.setMe = true;
}

Categories