How to clear form behind modal window with javascript? - javascript

Just like the question says, I'm trying to clear a form from a modal window while the modal stays up. I've tried:
if (myDocument.title == "Modal Window") {
parent.document.getElementById("textbox")
}
(I need it to do more than 1 tb, but used that just to try to get there. No luck.
It is contained within an iFrame, so I tried:
if (myDocument.title == "Modal Window") {
var ifr = document.getElementById("iFrame")
var form = ifr.document.getElementById("form")
ClearForm(form)
}
The ClearForm(form) function I stole from another Stack Overflow answer:
function ClearForm(form) {
$(':input', form).each(function () {
var type = this.type;
var id = this.id;
if (type == 'text' && id != 'text2')
this.value = "";
});
}
That 'text2' is one specific tb that we need to remain populated.
Any idea what I'm missing? I've been plagued with this bug for weeks.

I expect your issue is that the form is within an iFrame - most browsers won't allow you to modify elements within an iFrame, from the parent page, if they aren't from the same origin (or if the server is set up to deny it, or if you're looking at the page locally... see here for more details)
To double-check, try moving the form markup into the same page as the modal is in and run your function ClearFormfrom there. I expect that you'll then find it works.
Your only way around this would be to include the ClearForm function within the iFrame'd page, and then trigger it from the parent.

Related

Function to hide form fields from external script

I'm using a web page which contains a form loaded with an external script using the command 'script src'.
I created a function to populate some fields from url parameters and also hide some of them.
Here is the code.
<script type="text/javascript">
<!-- Hide Form Field -->
function hideFormField(name) {
var list = document.getElementsByName(name);
for (i = 0; i < list.length; i++) {
list[i].style.display = 'none';
list[i].style.visible = 'false';
list[i].type = 'hidden';
}
}
<!-- Customize form -->
function CustomizeForm()
{
// Set Field Value
hideFormField('custom_11');
hideFormField('custom_12');
hideFormField('custom_13');
hideFormField('custom_14');
hideFormField('custom_15');
}
// call it
CustomizeForm();
</script>
The fields are populated but not hidden.
When I debug, the form fields appear to disappear briefly but then they reappear.
It looks like the form is being refreshed afterwards.
To hide fields, which specific command is best and should I use out of those three? I'm tried them separately but it didn't seem to solve my problem.
field.style.display = 'none';
field.style.visible = 'false';
field.type = 'hidden';
Where should I put the call to the function to hide fields?
Assuming I don't control where the code is being added exactly in my designer (only in which section: header, body or footer), is there another alternative that would work every time? For example, can I attach to an event (which one) that might get called after all the loading and refresh is done.
Can I somehow debug or trace what is happening and why the fields do reappear?
Thank you in advance!
it's visibility not visible, try:
list[i].style.visibility = "hidden";

Getting a href source within the iframe [duplicate]

I got a warning by my ad system provider about click fraud. No further info, all they are recommending is "hide the ads for users who click on ads too quickly'". I wrote a piece of JS script that hides all DIVs with ads for N seconds (using cookie) when clicked on, but this solution does not work as the "inner" content (with ads) is generated by an JS script that calls and renders the content from external server (as you would expect from an ad system). So, when one takes the cross-domain security into account it is kinda Catch 22. How can I detect a click inside a DIV (locally defined) of which content is rendered by an external JS and in iframe?
Example:
<div class="ad-class"> <!-- locally defined div -->
<div id="my-id"> </div> <!-- identifies my ad in the provider's system -->
<script>
var foo = blah // declares the ad dimensions and stuff
// and renders the contextual ad in #my-id DIV
</script>
</div>
Were it all local, solution would be easy as the internal div would inherit the parent class ("ad-class"). In case of cross-domain, this is not valid. Any tips, dudes?
You cannot detect click events in cross-domain iframe.
That put, you might have one bad option:
One of the nearest things you can do is detect that the focus moved from your window to the iframe:
window.focus(); //force focus on the currenct window;
window.addEventListener('blur', function(e){
if(document.activeElement == document.querySelector('iframe'))
{
alert('Focus Left Current Window and Moved to Iframe / Possible click!');
}
});
http://jsfiddle.net/wk1yv6q3/
However it's not reliable, loose focus does not mean a click, it could be user moving across the website using TAB.
Another problem is that, you only detect the first time focus is moved to the iframe, you do not know what user does in there, he can click a million times and you will never know.
Luizgrs inspired me this solution :
var clickIframe = window.setInterval(checkFocus, 100);
var i = 0;
function checkFocus() {
if(document.activeElement == document.getElementById("ifr")) {
console.log("clicked "+(i++));
window.focus();
}
}
<!DOCTYPE html>
<h2>Onclick event on iframe</h2>
<iframe src="https://www.brokenbrowser.com/" id="ifr"></iframe>
The function detect if the iframe has the focus, if yes, the user clicked into the iframe. We then give back the focus to our main windows, which allow us to find if the user click another time.
This trick has been usefull to me for a POC on a 2 step iframe click-jacking. Getting to know when the user clicked for the first time on the iframe allowed me to reorganize my different layers to keep the illusion perfect.
The approach #Luizgrs pointed out is very accurate, however I managed to indeed detect the click event using a variation of the method:
var iframeMouseOver = false;
$("YOUR_CONTAINER_ID")
.off("mouseover.iframe").on("mouseover.iframe", function() {
iframeMouseOver = true;
})
.off("mouseout.iframe").on("mouseout.iframe", function() {
iframeMouseOver = false;
});
$(window).off("blur.iframe").on("blur.iframe", function() {
if(iframeMouseOver){
$j("#os_top").click();
}
});
The above code works like a charm on desktop if you want to add mobile support you just need to use touch events touchstartand touchendevents to simulate the mouseover on mobile.
Source
Well, a while ago I found this plugin for WordPress. Obviously it does what I need -- just wondering how this guy made it to work, it does count clicks on Adsense iframe. I must have a closer look though I am not a PHP programmer. I program mainly in Python and need some solution of this kind for Django. If anyone can read the code easily, I would appreciate any help.
The plugin is searching first for any iframe wrapped by a previous specified class name.
The iframe id´s will be collected in a array and for everyone of these id´s an mouseover event will be created which fires the script which hides the class 'cfmonitor'. As a result the iframe containing ad is not visible anymore.
// IFRAME ACTION
function iframeAction () {
jq.each(jq.cfmonitor.iframes, function(index,element) {
frameID = jq(element).attr('id') || false;
if (frameID) initiateIframe(frameID);
//alert (frameID);
});
}
// INIT IFRAME
function initiateIframe(elementID) {
var element = document.getElementById(elementID);
// MOUSE IN && OUT
if (element) {
element.onmouseover = processMouseOver;
element.onmouseout = processMouseOut;
//console.log("mouse on out");
}
// CLICKS
if (typeof window.attachEvent !== 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener !== 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
// IFRAME CLICKS
function processIFrameClick() {
// ADD A CLICK
if(isOverIFrame) {
//addClick();
// Some logic here to hide the class 'cfmonitor'
//console.log("Go");
top.focus();
}
}
Check this it might help. You can not detect the click event when its cross browser.
window.focus();
window.addEventListener('blur', function(e){
if(document.activeElement == document.getElementById('Your iframe id'))
{
console.log('iframe click!');
}
});

Method if P Id is true

I am trying to trigger an window open event such as "window.open" whenever the within the body of the document, the elements "P id" becomes true.
So when, within the body of the page, this ID happens to load:
<p id=newPlayListText>
"There is a new playlist that was sent to you, check it out here."
I can triggered the event of "window.open".
This is what i have and after inspecting it, its not flagging anything to debug and nothing happens...
//#test: check to see if the new playlist banner text pops up during ep.
window.onload = function () {
if(element.id = "nextPlaylistText") {
window.open("http://www.w3schools.com");
}
Please help
The window.onload hook is called when the page loads, but element is never defined. You'll need to assign the variable to element before using it:
var element = document.getElementById("newPlayListText");
There are two issues with your code. First as Litty correctly pointed out that element is never declared. Second you aren't comparing values within if block.
if(element.id = "nextPlaylistText") // required `===` or at-least `==`
P.S. some browsers may block this line window.open
window.onload = function() {
var p = document.getElementById('newPlayListText');
if (!p) {
alert('New playlist not found');
return;
}
var popup = window.open("http://www.w3schools.com");
if (!popup) {
alert('Kindly un-block/disable pop-up blocker');
return;
}
};
<p id="newPlayListText">There is a new playlist that was sent to you, check it out here.</p>

Calling a function or focusing a programmatically generated Iframe from an HTML5 canvas

I have an HTML5 canvas controlled and generated by a library of JavaScript files (Craftyjs library mostly).
The canvas generates 2 regular html iframes (same domain) which are stacked on top of each other.
The canvas switches between the two iframes based on calls from the iframes to the parent so I know the code controlling the canvas is easily accessed by their common parent.
I want the parent canvas to either call a function in the iframes to have them focus on a specific element in them or to somehow just have the iframes get focus in general.
I would also prefer to not have to constantly reload/recreate the iframes to get focus.
---- In the Iframe ----
//The head has a function "focusThis()" to focus on an element in the iframe
//body also has onfocus="focusThis();"
//Call the parent to change to the other iframe
parent.changeIframe();
---- In the parent's canvas JS code ----
// I know the function and will hide/show the iframe, but it won't focus
function changeIframe(){
//For now, just switch randomly
MODE = Math.floor(Math.random()*2);
//I am hiding the iframes here, then showing the one that should be seen
Crafty("Game1").each(function () {this.visible = false});
Crafty("Game2").each(function () {this.visible = false});
//Switch the iframes
if(MODE){
//Show this iframe
Crafty("iframe1").each(function () {this.visible = true});
These are things I have tried to get to work
When it doesn't throw an error it doesn't do anything in chrome or FireFox.
(Object [object global] has no method 'focusThis') is a common error
//document.getElementById('iframe1').focus();
//document.getElementById("iframe1").contentWindow.focusThis();
//document.getElementById('iframe1').contentWindow.focusThis();
//var iframe_window = window.frames["iframe1"];
//iframe_window.focus();
//iframe_window.contentDocument.body.focus();
//window.parent.document.getElementById('iframe1').contentWindow.focusThis;
//window.parent.document.getElementById('iframe1').contentWindow.focusThis();
//window.frames["iframe1"].focus();
//window.frames["iframe1"].contentWindow.focus();
//window.frames["iframe1"].contentDocument.focus();
var frame = document.getElementById("iframe1");
if(frame){
alert("yep");
frame.contentWindow.focusThis();
}
}
else{
//....Same thing but for iframe2
}
}
Any help would be greatly appreciated.
I solved my problem after some more fiddling.
This also solved my problem without having to reload the iframe.
I set a timer in the onload function of each iframe that tries to focus itself onto an element in itself based on a parent flag variable (MODE) that tells the iframe if it is supposed to have focus and an internal variable (focused) that tells it to stop trying to focus once it finally has focus again.
Somewhere in the head...
var focused = false;
function focusThis(){
if(parent.MODE && !focused){
document.getElementById("SOME_ELEMENT_I_WANT_FOCUSED").focus();
focused = true;
}
}
Somewhere in onLoad...
var autoFocus =
setInterval(function(){if(parent.MODE && !focused) focusThis()},500);
Somewhere in script below the body...
parent.changeIframe();
changeImage();
if(!parent.MODE){
//This element is just to have a place for focus to go when out of focus
document.getElementById("NA").focus();
focused = false;
}
else
focused = true;

windows onload not firing from external script

Okay i know this has been asked a lot but it seems that none of the solutions actually work for me. Here's the situation. I have a webpage that i need to add to an existing site, this site uses a master page which i can not touch. This limits me to using javascripts window.onload because i do not have access to the body tag.
On my page i have linked my external .js file in the head beneath every other external file. Here is an example of what my .js file looks like.
var myobj = null;
(5 or so functions that work properly. Mainly just toggles that show and hide divs. none touch the onload)
function load(){
myobj = document.getElementById("my_element");
alert("test");
}
window.onload = load;
Tried this and the load function never fires as i never get the alert. I've tried commenting out the first line in the load function and only haven't the alert and still nothing. Looking around i also found another way to do it that i tried without success. Everything else is the same except i removed the window.load and added this.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(load);
addLoadEvent(function () {
/* more code to run on page load */
alert("hello2");
});
In this function, neither of the alerts fire. I have also tried placing an alert outside of a function, that one does work.
The browsers i am using are IE 8.0.7600.16385 and Chrome 21.0.1180.60
Let me know if you need more information.
Oh and as a side note, i cannot use jquery or any other javascript library as we are trying to keep this as light as possible. This page also must work in IE8, that is the businesses only supported browser at the moment. It would be nice if it worked in Chrome as well.
EDIT
In case i'm going about this completely the wrong way, what i am trying to do is keep track of the last element i have. I essentially have a page with 2 columns, left side is a menu and right is content. The content is all placed in div's with only one category showing at a time. The way it is supposed to work is when clicking on the menu category it hides the previous content and shows the new content.
I have set my content class to display: none; and have the start_content ID set to display: block;. What the Javascript is supposed to do is initialize my global with the start_content object. When clicking in the menu it calls a function that does an obj.style.display = 'none' and then sets the new obj to display = 'block'. It then takes the new obj and places it in my global variable to be changed on the next menu click.
here's an example without any of the onload functions
var prevContent = document.getElementById("start_content");
function toggle(id) {
prevContent.style.display = "none";
var content = document.getElementById(id);
content.style.display = "block";
prevContent = content;
}
The problem with this is that prevContent is unidentified when it enters the toggle function. I had assumed this was because i am linking this .js file in the head and so the page hasn't loaded my start_content yet which is why i had changed it to declaring the global as a null and then setting up a window.onload to set the appropriate value after it is created.
Adding "Defer" to the script tag in the head ended up doing the trick.

Categories

Resources