How can I adjust the width of an Iframe with Javascript? - javascript

<div style="width: 550px;" id="zuora_payment">
<div style="display: inline;" class="z-overlay" id="z-overlay"></div>
<div class="z-container" id="z-container">
<div class="z-data" id="z-data">
<iframe style="display: block;" class="z_hppm_iframe" allowtransparency="true" scrolling="no" overflow="visible" id="z_hppm_iframe" src="https://www.zuora.com/allowtransparencypps/PublicHostedPageLite.do?..." frameborder="0" height="912" width="300">
</iframe>
</div>
</div>
</div>
I have tried: document.getElementById('z_hppm_iframe').setAttribute("style","width:500px");
I just need to adjust the width of the iFrame element, but it shows as null in the console, so I guess I'm not selecting the element correctly.
Thank you for any help you can provide.
The iFrame is added dynamically inside a
$( document ).ready(function() {}
which is is in head of the page. So I suspect it is not available at the time the .setAttribute() runs which is inside a script tag at the end of the body. I'm not doing much in this area (as you can tell), so I just need to figure out how to run this line of js after the iframe is added (I guess).

The problem is that you're trying to use the element before it was even rendered by the browser.
You should place your <script> tag just before ending the body tag.
Another solution is to use the DOMContentLoaded event, e.g:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('z_hppm_iframe').setAttribute("style", "width:500px");
});
I suggest you to change the width by doing style.width = '500px';, instead of doing by attribute, because doing the way you are, the style attribute will going to be completely replaced.

The problem is that you're trying to use the element before it was even rendered by the browser.
^ Well that only pertains to the method the OP tried. However, since the Iframe is being added dynamically and because the DOM does not need to be rendered in order to manipulate objects, he really doesn't need to move his <script> tags to the bottom of the page. Therefore, we cannot say that this is the source of the problem.
as to the OP...
The iFrame is added dynamically...
since "width" is technically one attribute and "style", another...
var iframe = document.create('iframe');
iframe.width = 500;
//or
iframe.style.width = '500px';
hopefully this helps

Related

Attach An Element When A PDF href Is Opened

Am testing something, and am not entirely sure it's possible. I have a basic href for an external pdf. I would like to attach a dynamic element to it, say a div and h1 tag for now.
View
<script>
function createElements(){
var div = $(document.createElement('div'));
div.innerHTML = '<h1 id="myTitle" class="back-button" alt="custom-title">';
$('#myTitle').css({
'position': 'absolute',
'z-index': '99',
'top': '16px',
'left': '12px',
'width': '11%',
});
}
</script>
Basically, when the external href is opened, I want to add attach an h1 tag on that document. Not sure if that's possible, however, testing the waters for now. The code above doesn't seem to work, but would appreciate feedback to see if this can be done with plain vanilla javascript/jquery.
You cannot affect a document that is not yet opened. For this to work, your javascript code would need to be inside the PDF but since browsers treat PDF content differently (as they should), it will never be executed. In short, I don't think this is possible.
Your href will always send the user to a PDF-viewer of the browser and you'll lose control over that.
If you want to have an element visible above or over the PDF file, you can maybe use a "template page" where you have your HTML element and a fullscreen iFrame with a src that points to the PDF file.
This will render the browser's PDF viewer in that iFrame winthin your template page.
Ex.
<div>
<div>
<!-- Your element here (you can make this absolute to make it lay over the pdf file etc.. -->
</div>
<iframe src=".../.pdf" style="width:100vw;height:100vh">
</div>
Maybe you don't need jQuery at all. I would do something like this (notice I leave the div empty beforehand):
View
<div id="myDiv"></div>
function createElements(){
var text = document.createElement("h1");
text.innerHTML ="MY heading";
document.getElementById("myDiv").appendChild(text);
}

Sort iframes without reloading in Angular [duplicate]

Take a look at this simple HTML:
<div id="wrap1">
<iframe id="iframe1"></iframe>
</div>
<div id="warp2">
<iframe id="iframe2"></iframe>
</div>
Let's say I wanted to move the wraps so that the #wrap2 would be before the #wrap1. The iframes are polluted by JavaScript. I am aware of jQuery's .insertAfter() and .insertBefore(). However, when I use those, the iFrame loses all of its HTML, and JavaScript variables and events.
Lets say the following was the iFrame's HTML:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// The variable below would change on click
// This represents changes on variables after the code is loaded
// These changes should remain after the iFrame is moved
variableThatChanges = false;
$(function(){
$("body").click(function(){
variableThatChanges = true;
});
});
</script>
</head>
<body>
<div id='anything'>Illustrative Example</div>
</body>
</html>
In the above code, the variable variableThatChanges would...change if the user clicked on the body. This variable, and the click event, should remain after the iFrame is moved (along with any other variables/events that have been started)
My question is the following: with JavaScript (with or without jQuery), how can I move the wrap nodes in the DOM (and their iframe childs) so that the iFrame's window stays the same, and the iFrame's events/variables/etc stay the same?
It isn't possible to move an iframe from one place in the dom to another without it reloading.
Here is an example to show that even using native JavaScript the iFrames still reload:
http://jsfiddle.net/pZ23B/
var wrap1 = document.getElementById('wrap1');
var wrap2 = document.getElementById('wrap2');
setTimeout(function(){
document.getElementsByTagName('body')[0].appendChild(wrap1);
},10000);
This answer is related to the bounty by #djechlin
A lot of search on the w3/dom specs and didn't find anything final that specifically says that iframe should be reloaded while moving in the DOM tree, however I did find lots of references and comments in the webkit's trac/bugzilla/microsoft regarding different behavior changes over the years.
I hope someone will find anything specific regarding this issue, but for now here are my findings:
According to Ryosuke Niwa - "That's the expected behavior".
There was a "magic iframe" (webkit, 2010), but it was removed in 2012.
According to MS - "iframe resources are freed when removed from the DOM". When you appendChild(node) of existing node - that node is first removed from the dom.
Interesting thing here - IE<=8 didn't reload the iframe - this behavior is (somewhat) new (since IE>=9).
According to Hallvord R. M. Steen comment, this is a quote from the iframe specs
When an iframe element is inserted into a document that has a browsing context, the user agent must create a new browsing context, set the element's nested browsing context to the newly-created browsing context, and then process the iframe attributes for the "first time".
This is the most close thing I found in the specs, however it's still require some interpretation (since when we move the iframe element in the DOM we don't really do a full remove, even if the browsers uses the node.removeChild method).
Whenever an iframe is appended and has a src attribute applied it fires a load action similarly to when creating an Image tag via JS. So when you remove and then append them they are completely new entities and they refresh. Its kind of how window.location = window.location will reload a page.
The only way I know to reposition iframes is via CSS. Here is an example I put together showing one way to handle this with flex-box:
https://jsfiddle.net/3g73sz3k/15/
The basic idea is to create a flex-box wrapper and then define an specific order for the iframes using the order attribute on each iframe wrapper.
<style>
.container{
display: flex;
flex-direction: column;
}
</style>
<div class="container">
<div id="wrap1" style="order: 0" class="iframe-wrapper">
<iframe id="iframe1" src="https://google.com"></iframe>
</div>
<div id="warp2" style="order: 1" class="iframe-wrapper">
<iframe id="iframe2" src="https://bing.com"></iframe>
</div>
</div>
As you can see in the JS fiddle these order styles are inline to simplify the flip button so rotate the iframes.
I sourced the solution from this StackOverflow question: Swap DIV position with CSS only
Hope that helps.
If you have created the iFrame on the page and simply need to move it's position later try this approach:
Append the iFrame to the body and use a high z-index and top,left,width,height to put the iFrame where you want.
Even CSS zoom works on the body without reloading which is awesome!
I maintain two states for my "widget" and it is either injected in place in the DOM or to the body using this method.
This is useful when other content or libraries will squish or squash your iFrame.
BOOM!
Unfortunately, the parentNode property of an HTML DOM element is read-only. You can adjust the positions of the iframes, of course, but you can't change their location in the DOM and preserve their states.
See this jsfiddle I created that provides a good test bed. http://jsfiddle.net/RpHTj/1/
Click on the box to toggle the value. Click on the "move" to run the javascript.
This question is pretty old... but I did find a way to move an iframe without it reloading. CSS only. I have multiple iframes with camera streams, I dont like when they reload when i swap them. So i used a combination of float, position:absolute, and some dummy blocks to move them around without reloading them and having the desired layout on demand (resizing and all).
If you are using the iframe to access pages you control, you could create some javascript to allow your parent to communicate with the iframe via postMessage
From there, you could build login inside the iframe to record state changes, and before moving dom, request that as a json object.
Once moved, the iframe will reload, you can pass the state data into the iframe and the iframe listening can parse the data back into the previous state.
PaulSCoder has the right solution. Never manipulate the DOM for this purpose. The classic approach for this is to have a relative position and "flip" the positions in the click event. It's only not wise to put the click event on the body, because it bubbles from other elements too.
$("body").click(function () {
var frame1Height = $(frame1).outerHeight(true);
var frame2Height = $(frame2).outerHeight(true);
var pos = $(frame1).css("top");
if (pos === "0px") {
$(frame1).css("top", frame2Height);
$(frame2).css("top", -frame1Height);
} else {
$(frame1).css("top", 0);
$(frame2).css("top", 0);
}
});
If you only have content that is not cross-domain you could save and restore the HTML:
var htmlContent = $(frame).contents().find("html").children();
// do something
$(frame).contents().find("html").html(htmlContent);
The advantage of the first method is, that the frame keeps on doing what it was doing. With the second method, the frame gets reloaded and starts it's code again.
At least in some circumstances a shadow dom with slotting might be an option.
<template>
<style>div {outline:1px solid black; height:45px}</style>
<div><slot name="a" /></div>
<div><slot name="b" /></div>
</template>
<div id="shadowhost">
<iframe src="data:text/html,<button onclick='this.innerText+=`!`'>!</button>"
slot="a" height=40px ></iframe>
</div>
<button onclick="ifr.slot= (ifr.slot=='a') ? 'b' : 'a';">swap</button>
<script>
document.querySelector('#shadowhost').attachShadow({mode: 'open'}).appendChild(
document.querySelector('template').content
);
ifr=document.querySelector('iframe');
</script>
In response to the bounty #djechlin placed on this question, I have forked the jsfiddle posted by #matt-h and have come to the conclusion that this is still not possible.
http://jsfiddle.net/gr3wo9u6/
//this does not work, the frames reload when appended back to the DOM
function swapFrames() {
var w1 = document.getElementById('wrap1');
var w2 = document.getElementById('wrap2');
var f1 = w1.querySelector('iframe');
var f2 = w2.querySelector('iframe');
w1.removeChild(f1);
w2.removeChild(f2);
w1.appendChild(f2);
w2.appendChild(f1);
//f1.parentNode = w2;
//f2.parentNode = w1;
//alert(f1.parentNode.id);
}

How to get parentNode ID and use it as a variable

I'm trying to run a script on images within specific blog posts. Each post div is given a unique ID by Blogger that I'm trying to get. Because I only want to run the script on posts containing the function call and not the entire page, I want the function to basically find the ID of the div that's calling it, store that ID as a variable, and then pass that variable in to my function.
<script>
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
</script>
This returns the correct element but the second I wrap it in a function(){} it doesn't work anymore. How can I assign these variables from within a function so I don'thave to clutter up every post's html with a bunch of variable declarations?
Secondly, once I have these variables assigned is there a way to use the value stored with the getElementByID method to actually select the element?
var parentDivID = parentTag.id;
var postID = document.getElementByID(parentDivID); //can't figure out how to select using this as the variable
For ease of use I'd like it if I could simply wrap the function call in script tags and stick it at the end of my post's html whenever I need to use it.
Details
The script I want to run finds images within divs with a specified class and resizes them to fit side-by-side so that the outer edges of the images completely fill the width of the div.
Here is the question covering that script:
Force dissimilar images to equal heights so combined widths fill fixed div
I would like to call this script at the end of any post body where I plan to use side-by-side formatting. The reason I want to call it at the end of a post instead of on the entire page is because the page uses "infinite scrolling" and I'm worried that as posts load after the fact the resizing script will have already been run and newly loaded posts will not be resized.
So I want the function to be able to find the unique ID of the div that contains the call, use that as a variable and ask the script to look inside that post for divs of a certain class, then look within those divs for image tags and resize those images. I hope that makes sense.
Here's an example of what I'd like the post's html to look like:
<div style="width:500px; margin:auto;">
<div class="widthVal x2">
<img class="caption" alt="Caption 01" src="sample01.jpg" />
<img class="caption" alt="Caption 02" src="sample02.jpg" />
<img class="caption"alt="Caption 03" src="sample03.jpg" />
</div>
<script> resizeMagic(); </script>
</div>
Thanks for any help!

How to Remove a iframe by jQuery

I create a iframe in a div by jQuery.Then I load another page(lets say page A.jsp) into that iframe. The page 'A.jsp' has some functionality and end of it, the parent iframe should be removed from the first page when a button in 'A.jsp' is pressed . Loading the page 'A.jsp' into the iframe is OK. but I can't remove the parent iframe. How I tried was, select the parent tag iframe then, remove it. but it didn't work. Here is how I tried.Here $(this) referes to a button in page A.jsp and &('div iframe')referes to the parent iframe
$(this).closest($('div iframe')) .animate({
opacity:0
},500,function(){$(this).remove()})
How can I remove the parent iframe ?
This should give you the info you need.
https://stackoverflow.com/a/4689154/897871
Note: the page that hosts the iframe and the page with the content will have to reside on the same host.
To which element does this refer to?
To access the iframe you should point to:
parent.document
or
parent.$("iframe")
if you want to use jQuery.
Same Origin Policy is always involved here, so pay attention to what you can actually do.
Another solution is to reload the parent page using a simple link that has target="_parent".
see also here:
How to access parent Iframe from javascript
The iframe can be fully remove from the DOM by the remove method
eg
This is my iframe
<div id="videoPlayerOP" > <iframe id="optionsPlayVideo" width="520" height="348" style="margin-left: 80px;margin-top: 7px;" src="about:blank"></iframe></div>
After loading some source in it, It can be remove by
$($("#optionsPlayVideo").parent()).empty();
If you want to reuse them them append another iframe in it
$('#videoPlayerOP').append('<iframe id="optionsPlayVideo" width="520" height="348" style="margin-left: 80px;margin-top: 7px;" src="about:blank"></iframe>');
Thanks

Jquery - Replace Specific Line in HTML

I'm having an issue with iframes and IDs.
I currently have an Iframe with no ID attached to as its generated by another websites javascript. So I quickly wrote a Jquery script to give IDs to Iframes on load of page, and it worked successfully. Problem is however, it applies the ID to ALL the Iframes on the page instead of specifically the one I want.
This is what I have.
<script>
$(document).ready(function () {
$("iframe").attr({
id: "iframeid1"
});
});</script>
Is there a method with Jquery to 'search and replace' something specific on the page? For example
Search for:
<iframe allowtransparency="true" frameborder="0" scrolling="no" width="160" height="600"
Replace with:
<iframe id="iframeid1" allowtransparency="true" frameborder="0" scrolling="no" width="160" height="600"
Any help is appreciated! Thanks in advance!
If you know it is the nth iframe on the page:
$("iframe")[n].setAttribute('id', 'iframe1');
EDIT: You could also use attribute selectors:
$("iframe[allowtransparency=true][frameborder=no][etc=etc]").attr({id: 'iframe1'});
It depends on if there is a unique way of finding the iframe you want. For example, is it the only one with width = 160 and height = 600? Or is it always the Xth iframe on the page? Is it always located in the same spot in the page?
Here are some queries as examples for all 3 scenarios:
// if the width/height combination is unique...
var iframe = $('iframe[width=160][height=600]');
// if it is always, say, the 3rd iframe on the page
var iframe = $('iframe:eq(2)'); // 0-based index
// if it is always the only iframe in a div with an id of "iframeContainer"...
var iframe = $('#iframeContainer').find('iframe');
Then you can set the attribute like you said:
iframe.attr('id', 'iframeid1');
if the iframe is wrapped inside a div, with a ID, than you can do:
<script>
$(document).ready(function () {
$("#divID iframe").attr({
id: "iframeid1"
});
});</script>
If you know where your iframe is at you can get it by index position.
If you have 4 iframes on the page and you're looking for the third (with respect to the DOM), you can do this:
$("iframe").get(3).attr({
id: "iframeid1"
});
You can use selectors to find an iframe tag with specific attributes. But you need to be able to uniquely identify the specific iframe you want from attribute values, not HTML search.
As an example:
$('iframe[width="160"][height="600"]').attr("id", "iframeid1");
This would select iframe tags with width=160 and height=600. You can add more attributes if needed to uniquely select your particular iframe.
Perhaps the best option would be to use the DOM structure around the iframe to identify which one you want. You could use parent object identifiers, ordering of the tags, etc.. whatever helps uniquely identify the one you want.

Categories

Resources