IFrame width change with CSS and JavaScript - javascript

I'd like the width of my IFrame to be one of two sizes, depending on the width of the browser window. Unfortunately the code below doesn't give the expected results, even on refresh. What am I doing wrong?
The HTML is as follows:
<p>A frame example:<br>
<iframe src="www.google.com">
</iframe>
</p>
At the beginning, I import a stylesheet that works in all regards except the following:
iframe
{
<script>
if (window.innerWidth<800px)
{
width="200";
}
else
{
width="400";
}
</script>
height="400";
}
Any ideas on what I can improve?

You can't use javascript inside css. Just use media queries to solve the problem
#media all and (max-width:800px) {
iframe {
width: 200px;
}
}
#media all and (min-width: 801px) {
iframe {
width: 400px;
}
}

Using css media queries is preferable but if you'd like to change the width using JavaScript, you can listen to the onresize window event and change the width inside the event handler.
Note that I added an id to the iframe so you can quickly select it in the JavaScript.
HTML
<iframe id="myIframe" src="www.google.com"></iframe>
JavaScript
(function() {
var iframe = document.getElementById('myIframe');
iframe.height = 400;
window.onresize = resizeIframe;
function resizeIframe() {
if (window.innerWidth < 800) {
iframe.width = 200;
}
else {
iframe.width = 400;
}
}
}());
Check out the jsfiddle example

Related

How to call media query using jQuery

I am trying to call media queries through document.ready method. Here my aim is to call a media query after HTML content got loaded. Can anyone help? On this.
Example:
#media only screen and (min-width: 1200px){
.main_container {
width: 1200px;
}
}
You can use
$windowWidth = $(window).width();
This will give you size of the current screen. Then use conditions to add your css
if ($windowWidth >= 1200) {
$('.main_container').css('width', '1200px');
} else {
$('.main_container').css('width', 'auto');
}

Prepend and append content based on browser size

I have this function that moves a HTML element around the DOM based on whether the window size is less than 640px or more. I'm moving the image with prepend and append, but because the function fires every time the window is resized I think I'm asking for performance issues.
The code:
function moveDealsImage() {
var mobile_width = 640;
var wi = $(window).width();
if (wi < mobile_width) {
$( ".deals-header" ).prepend( $("div.htp") );
} else {
$( ".deals-header" ).append( $("div.htp") );
}
}
window.addEventListener("resize", moveDealsImage);
moveDealsImage();
I need to keep the listener in there.
Is there a way to do that, but then only prepending/appending the element once each time that the if or else statements become true? (instead of it happening on every pixel change)
There are a few things that you can do to optimize this.
A first option is to only execute your moveDealsImage function when the state changes from mobile to desktop or reverse. All the other resizes can just be ignored.
This can be accomplished by using something like following code:
var mobile_width = 640;
var is_mobile = (window.innerWidth <= mobile_width);
function moveDealsImage(e) {
// Only execute the function when then state changes from mobile to desktop or reverse
if(
! is_mobile && window.innerWidth > mobile_width ||
is_mobile && window.innerWidth <= mobile_width
)
return;
// Update state
is_mobile = (window.innerWidth <= mobile_width);
console.log('your code here');
}
window.addEventListener("resize", moveDealsImage);
moveDealsImage();
Another and better solution would be to use CSS media queries. This can be done with the following CSS and HTML.
.desktop-deals-header {
display: block;
}
.mobile-deals-header {
display: none;
}
#media only screen
and (max-width : 640px) {
.desktop-deals-header {
display: none;
}
.mobile-deals-header {
display: block
}
}
and in your HTML you add two headers, one for desktop and one for mobile.
<div class="mobile-deals-header">Mobile header</div>
<div class="desktop-deals-header">Desktop header</div>

How to change an image from the DOM in a particular browser width without using media-queries

I have an img tag in the DOM.
<div class="some-div">
<img src="https://cdn0.iconfinder.com/data/icons/social-networks-and-media-flat-icons/133/Social_Media_Socialmedia_network_share_socialnetwork_network-09-128.png">
</div>
Now when the browser width become 768px (actually for the tab,smartphone) I need to change the src of the img tag. That means simply the image will be changed to a another one. Example:-
<div class="some-div">
<img src="https://cdn0.iconfinder.com/data/icons/social-networks-and-media-flat-icons/133/Social_Media_Socialmedia_network_share_socialnetwork_network-09-128.png">
</div>
Remember I cant use the background-image property in the css for some reason here so would not be able to write media-queries like this #media only screen and (max-width: 768px)
I need to change it via JS or anyhow. Can you help? Thanks a ton.
Remember I cant use the background-image property in the css for some reason here so would not be able to write media-queries like this #media only screen and (max-width: 768px)
If it's specifically that you can't use background-image, but you can use media queries, then:
#media (min-width: 769px) {
img.small {
display: none;
}
}
#media (max-width: 768px) {
img.big {
display: none;
}
}
...and in your markup:
<img class="big" src="/path/to/big/image.png">
<img class="small" src="/path/to/small/image.png">
If you can't use media queries at all, then:
<img data-big="/path/to/big/image.png" data-small="/path/to/small/image.png">
and
(function() {
var lastSizeAttr = null;
var list = document.getElementsByTagName("img"); // the list is live
var resizeTimer = 0;
window.addEventListener("resize", maybeResize);
function maybeResize() {
if (resizeTimer) {
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(imageResize, 100); // Wait 100ms
}
function imageResize() {
var attr = favorite_width_prop_here < 769 ? "data-small" : "data-big";
var img;
var n;
resizeTimer = 0;
if (attr !== lastSizeAttr) {
lastSizeAttr = attr;
for (n = 0; n < list.length; ++n) {
img = list[n];
img.src = img.getAttribute(attr);
}
}
}
})();
...or similar at the end of your HTML (so the elements are there to be found by getElementsByTagName). Note the favorite_width_prop_here, I don't immediately recall which property to use if you're not using jQuery. :-)
You need to calculate the width of window size.
function calculateWidth(){
if(window.outerWidth <= 768){
var imgTag = document.getElementElementById('someImage');
imgTag.src = "imageForTab.jpg"; //here your small image would be for tab
}
}
//attaching the function on window resize
window.addEventListener('resize', calculateWidth);
<body onload="calculateWidth()"> //calling the function on body onload
Pleae put id on your image tag.
<img id="someImage" src="https.....
This is handeling only the image which is given with this id ('someImage').

javascript - change image width?

I am using the following code to check if the width of an image is larger than 700. If that the case then I want to set it to 700
<img src="" id="main_image">
<script>
if(document.getElementById(main_image).width > 700) {
document.getElementById(main_image).width = 700;
}
</script>
after some search I found the above code but it is not working. Tell me what I am doing wrong ?
use "main_image" instead of main_image
<script>
if(document.getElementById("main_image").width > 700) {
document.getElementById("main_image").width = 700;
}
</script>
<img src="" id="main_image">
or you can use style also
document.getElementById("main_image").style.width = "700px";
Try with style:
window.onload = function() {
if(+(document.getElementById('main_image').style.width) > 700) {
document.getElementById('main_image').style.width = '700px';
}
};
If you have set width attribute then you would use getAttribute('width') and setAttribute(700) or directly width as you were doing. But if it comes from CSS, you will need to use style like shown above.
Your issue is probably because you are running the script before the element exists on the page. Try reversing the script and the img tag.

Printing just an iFrame

I'm working on a case resolution system, and am currently using a jquery colorbox to display a list of open tasks to the user. Users want to be able to print this list, and I guess you can do it from within the page itself by adding a JavaScript link that triggers window.print from within the iframe. However, I've also got to account for users possibly selecting print from the browser's menu. In that case, if the colorbox is open, I just want to print its contents and not the overlying page.
Is it possible to hide everything except for the iframed content using a print media CSS file? If so, how can this be achieved? Failing that, I'll need to resort to JavaScript, so would achieving the effect in JavaScript be possible?
// suppose that this is how your iframe look like <iframe id='print-iframe' name='print-frame-name'></iframe>
// this is how you do it using jquery:
$("#print-iframe").get(0).contentWindow.print();
// and this is how you do it using native javascript:
document.getElementById("print-iframe").contentWindow.print();
In case the pure CSS solution will fail (didn't work for me but maybe I just missed something) you can have combined solution of CSS and JavaScript. First have this:
<style type="text/css" media="print">
.hideonprint { display:none; }
</style>
Then such JavaScript will cause all content to be hidden when printing, except your frame:
<script type="text/javascript">
window.onbeforeprint = function WindowPrint(evt) {
for (var i = 0; i < document.body.childNodes.length; i++) {
var curNode = document.body.childNodes[i];
if (typeof curNode.className != "undefined") {
var curClassName = curNode.className || "";
if (curClassName.indexOf("hideonprint") < 0) {
var newClassName = "";
if (curClassName.length > 0)
newClassName += curClassName + " ";
newClassName += "hideonprint";
curNode.setAttribute("original_class", curClassName);
curNode.className = newClassName;
}
}
}
document.getElementById("myframe").className = document.getElementById("myframe").getAttribute("original_class");
}
</script>
This also assume the iframe is direct child of the body otherwise it won't work either.
I have found a method that works to print just the IFrame's content even if the client uses the browser's print menu item, but I couldn't tell you why that is. The trick is to set the focus to the IFrame before printing. The print stylesheet is needed too, although the javascript seems to be what is happening when the user prints from the menu. You need both parts for it to work. It prints the entire document, even if it is larger than the IFrame! I have successfully tested it in IE8, Firefox 5 and 6 and Safari 3.2.
I use this script as a handler for an onclick event for a button or "print me" link:
<script type="text/javascript" language=JavaScript>
function CheckIsIE()
{
if (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER')
{ return true; }
else
{ return false; }
}
function PrintThisPage()
{
if (CheckIsIE() == true)
{
document.content.focus();
document.content.print();
}
else
{
window.frames['content'].focus();
window.frames['content'].print();
}
}
</script>
The IFrame in question is named and id'd content. My button is in a div called print_iframe The browser sniffing is essential!
Then I use a print only stylesheet linked in like this:
<link href="/styles/print.css" rel="stylesheet" type="text/css" media="print" />
#charset "utf-8";
/* CSS Document */
body { background:none; }
#left { display:none; }
#main img { display:none; }
#banner
{
display:none;
margin-top:0px;
padding:0px;
}
#main
{
margin-top:0px;
padding:0px;
}
#print_iframe
{
display:none;
}
This could work if the iframe is a direct child of body
<style type="text/css" media="print">
body *{display:none}
iframe{display:block}
</style>

Categories