Why does innerWidth() give different result than get(0).width? - javascript

Testing in Chrome. If I create dynamically a canvas object, put it into a div like this:
$('<div />').css({
width: '95%',
margin: '0px auto',
border: '1px solid red'
})
.append(
$('<canvas />')
.attr({ id: 'myCanvas' })
.css({ width: '100%' })
)
.appendTo('body');
And then in all the resize events, i try to show size:
function updateCanvas() {
console.log($('#mycanvas').get(0).width);
console.log($('#mycanvas').innerWidth());
}
/* listening to whatever change it can be on the device */
var eventListen = function() {
window.addEventListener("orientationchange", eventResize, false);
window.addEventListener("resize", eventResize, false);
};
var eventResize = function() {
window.removeEventListener("orientationchange", eventResize, false);
window.removeEventListener("resize", eventResize);
window.setTimeout(function(){
/* small timeout in case of lot of resize (dragging) */
var w=innerWidth;
var h=innerHeight;
window.setTimeout(function(){
if ((innerWidth!=w) || (innerHeight!=h)) {
eventResize();
} else {
updateCanvas();
eventListen();
}
}, 100);
}, 100);
}
eventListen();
The results are differents! Pure DOM gives me actual size of the canvas, whereas $('#mycanvas').innerWidth() gives me bigger result...

I think this scheme should answer your question (found on google images)
(source: stacktrace.jp)
The difference between the width and the innerWidth is made by the padding.
EDIT: Correction
As PE pointed out, this difference is due to the fact that the width() method you are using is in fact the object property, which is different from the css property.
If you don't set your canvas property the width attribute defaults to 300, and the height attribute defaults to 150. The width and height CSS properties control the size that the element displays on screen.
More info:
http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting.html#attr-canvas-width

The difference is because you are checking two different things
get(0).width is the canvas' object's width property, which is not affected/changed by css styling, and is set either by the element's width attribute or the .width property in js. And defaults to 300x150 as per the spec.
jQuery's width(),innerWidth() etc methods are calculating the layout size of the canvas element, which is affected by the css styling.

Related

How do I set a responsive proportional image that is relative to its own height – NOT its width

How do I set a responsive proportional image that is relative to its own height – NOT its width?
simply setting...
img{
width: auto;
height: 100%;
}
doesn't give me proportional dimensions for my image.
How can I do that?
I've found the only consistent solution was a javascript one.
Introducing naturalWidth and naturalHeight.. supported on all browsers except IE8.
There is also a work around for IE8. ( http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/ )
If you don't mind using jquery and underscore you could set each width like so.
$(window).load( function() {
function imgWidth(){
$("img").each( function(){
nWidth = $(this)[0].naturalWidth;
nHeight = $(this)[0].naturalHeight;
nRatio = nWidth/nHeight;
curHeight = $(this).height();
$(this).css("width", curHeight*nRatio);
});
}
imgWidth();
var updateLayout = _.debounce( function(e) {
imgWidth();
}, 500);
window.addEventListener("resize", updateLayout, false);
}
Image manipulation becomes stupidly convoluted in HTML/CSS. The height tags directly on the img get ignored in a lot of scenarios, depending on div properties. I think the simplest way is to create a div with the image in question set as the background.
.img-div {
height:x; width:x;
background:url(file/path/here.svg);
background-position:center;
background-size:auto 100%;
Here's a demonstration: https://jsfiddle.net/JTBennett/nukLf5m3/

Toggle class and change size on an element using jQuery

I am trying to have a div change its properties on a click function. Some of the properties I am changing with a call to toggleClass() which is fine and works great. However I also want to resize the div based on the size of the viewport. In order to have access to those numbers I am changing the width and height with jQuery. This command looks like this:
$('.box').click( function() {
$(this).toggleClass('box--grow', 0);
$(this).css('width', w * .9);
$(this).css('height', h * .9);
});
EDIT I want the height and width to go back to 100%.
I tried using the toggle class but that caused the entire div to disappear, and this solution doesn't work because when I click the div again the class is removed but the height is the same.
I am looking for a way to toggle this or to get the viewport width within the css. I tried both approaches but couldn't get anything to what I am looking for.
why not using CSS VH and VW values?
CSS:
.my90Class{
width: 90vw;
height: 90vh;
}
JS:
$('.box').click( function() {
$(this).toggleClass("my90Class");
});
You need to get the window size first, and then put everything into combined .ready() and .resize() functions, to make it responsive.
function myfunction() {
var w = $(window).width();
var h = $(window).height();
$('.box').click(function () {
if ($(this).hasClass('box--grow')) {
$(this).removeClass('box--grow');
$(this).css({
'width': '',
'height': ''
});
} else {
$(this).addClass('box--grow');
$(this).css({
'width': w * .9,
'height': h * .9
});
}
});
}
$(document).ready(myfunction);
$(window).on('resize', myfunction);
jsfiddle
You can check for the class with:
$(this).hasClass('box--grow')
Then to remove the class:
$(this).removeClass('box--grow');
And to add it back again:
$(this).addClass('box--grow');
The end would look like this save the original width and height before the event so you can add it back again:
var oldwidth = $('.box').css('width');
var oldheight = $('.box').css('height');
$('.box').click( function() {
if($(this).hasClass('box--grow')) {
$(this).removeClass('box--grow');
$('.box').css('width', oldwidth);
$('.box').css('height', oldheight);
} else {
$(this).addClass('box--grow');
}
});
untested but it would probably work

Changing image widths after page had loaded if width is declared already? If width is undeclared, width will change but not if declared as I have

The trouble is that I need these images with generated IDs "cam_snap_XXX" to become a different width if they are dragged and dropped into this area. I can make the height change but NOT THE WIDTH because the width is designated to 20px if x==1. Never is the image height specified therefore I believe that is the reason it is changeable? Q: How can I make these image widths change from 20px to 100px if "dragged"?
while (cnt <= 100) {
cam_icon=document.getElementById('cam_snap_' + cnt);
cam_icon.style.visibility = 'hidden';
if (x==1) {
cam_icon.style.width = '20px';
cam_icon.style.visibility = 'visible';
}
cnt++;
}
The height changes from the following javascript...
//js for adding class "dragged" which gives new height and width image parameters
$('.droparea td.drop').droppable({
onDrag: function (e, source) {
$(this).addClass('dragged'); //Changes height correctly not width though.
}
}
And the css..
//css for attempting to change image width and height on drop
.dragged{
height: 100px; //Works because height stretches image height from ~20px to 100px.
width: 100px; //**Doesn't work and is useless because width remains 20px.**
}
Should I try removing the class before adding class 'dragged' to these images? Using removeClass()? Any ideas are welcome even if not the solution.
This part of javascript modifies your HTML
cam_icon.style.width = '20px';
cam_icon.style.visibility = 'visible';
to
<someTag id="cam_snap_x" style="width:20px;visibility:visible">
According to css rules inline style (inside an HTML element) has the highest priority. so you'll have to change attribute value to see changes in UI.
Solution 1: change your onDrag function like below.
$('.droparea td.drop').droppable({
onDrag: function (e, source) {
$(this).width(100).height(100); //This will change the style property
}
}
Solution 2: Use !important to prioritize value specified in class over inline style attribute
.dragged{
height: 100px;
width: 100px !important;
}

Dynamically resize iframe

Situation:
I'm working on a responsive design that involves the typical HTML/CSS combo. Everything is working nicely except in one case where there is an iframe inside of a div. The iframe should adjust automatically to the size of the parent div. A purely css solution has not presented itself so I'm going with a JQuery approach. It works nicely except in one scenario, when resizing from a smaller width to a larger width screen.
HTML:
<div class="container">
<iframe class="iframe-class" src="http://www.cnn.com/"></iframe>
</div>
CSS:
.container {
width: 100%;
height: 250px;
}
.iframe-class {
width: 100%;
height: 100%;
border: 1px solid red;
overflow: auto;
}
Javascript:
$(function () {
setIFrameSize();
$(window).resize(function () {
setIFrameSize();
});
});
function setIFrameSize() {
var ogWidth = 700;
var ogHeight = 600;
var ogRatio = ogWidth / ogHeight;
var windowWidth = $(window).width();
if (windowWidth < 480) {
var parentDivWidth = $(".iframe-class").parent().width();
var newHeight = (parentDivWidth / ogRatio);
$(".iframe-class").addClass("iframe-class-resize");
$(".iframe-class-resize").css("width", parentDivWidth);
$(".iframe-class-resize").css("height", newHeight);
} else {
// $(".iframe-class-resize").removeAttr("width");
// $(".iframe-class-resize").removeAttr("height");
$(".iframe-class").removeClass("iframe-class-resize");
}
}
http://jsfiddle.net/TBJ83/
Problem:
As the window is resized smaller, it continually checks the window width and once it hits < 480 px, the code adds a class called iframe-class-resize and sets the width and height to that class. As the window is resized larger, it removes the class once the size hits 480 px. The problem is that setting the width and height attributes adds them directly to the element and not the class itself. Therefore, removing the class does not remove the new width and heights. I tried to force removing the attributes using removeAttr() (commented out above) but that didn't work.
Anyone see where the code above went wrong? Or any suggestions on how to accomplish having a responsive iframe more effectively? The main things that are required are that the iframe has to be inside the <div></div> and the div may not necessarily have a width or height defined. Ideally, the parent div should have the width and height explicitly defined but the way this site is currently setup, that won't always be possible.
Additional:
In case the above wasn't clear enough, try the following to reproduce the issue:
Open up a browser on a desktop machine. I'm using Chrome on a Windows machine. Don't maximize the browser.
Open up the jsfiddle above (http://jsfiddle.net/TBJ83/). You'll notice that the iframe content spans the entire width of the Preview panel.
Manually resize the width down until the entire window is < 480px. At this point, the iframe content will be pretty tiny.
Manually resize the width back up until the entire window is >> 480px. The goal is to have that iframe content to regain the entire width of the Preview panel. Instead, the content is retaining the resized width and height since the .css() function applies css changes directly to elements rather than to the classes.
Thanks in advance!
You can do this in about 30 characters. Change:
$(".iframe-class").removeClass("iframe-class-resize")
to:
$(".iframe-class").removeClass("iframe-class-resize").css({ width : '', height : '' })
This will reset the width/height you applied to the element. When you use .css() you add whatever you pass-in to the style attribute of the element. When you pass a blank value, jQuery removes that property from the style attribute of the element.
Here is an updated fiddle: http://jsfiddle.net/TBJ83/3/
EDIT
OK, here's something tweaked for performance (and just some other ways to do things):
$(function () {
//setup these vars only once since they are static
var $myIFRAME = $(".iframe-class"),//unless this collection of elements changes over time, you only need to select them once
ogWidth = 700,
ogHeight = 600,
ogRatio = ogWidth / ogHeight,
windowWidth = 0,//store windowWidth here, this is just a different way to store this data
resizeTimer = null;
function setIFrameSize() {
if (windowWidth < 480) {
var parentDivWidth = $myIFRAME.parent().width(),//be aware this will still only get the height of the first element in this set of elements, you'll have to loop over them if you want to support more than one iframe on a page
newHeight = (parentDivWidth / ogRatio);
$myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
} else {
$myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
}
}
$(window).resize(function () {
//only run this once per resize event, if a user drags the window to a different size, this will wait until they finish, then run the resize function
//this way you don't blow up someone's browser with your resize function running hundreds of times a second
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
//make sure to update windowWidth before calling resize function
windowWidth = $(window).width();
setIFrameSize();
}, 75);
}).trigger("click");//run this once initially, just a different way to initialize
});
This can be done using pure CSS as below:
iframe {
height: 300px;
width: 300px;
resize: both;
overflow: auto;
}
Set the height and width to the minimum size you want, it only seems to grow, not shrink.
This is how I would do it, code is much shorter: http://jsfiddle.net/TBJ83/2/
<div class="container">
<iframe id="myframe" src="http://www.cnn.com/"></iframe>
</div>
<script>
$(function () {
setIFrameSize();
$(window).resize(function () {
setIFrameSize();
});
});
function setIFrameSize() {
var parentDivWidth = $("#myframe").parent().width();
var parentDivHeight = $("#myframe").parent().height();
$("#myframe")[0].setAttribute("width", parentDivWidth);
$("#myframe")[0].setAttribute("height", parentDivHeight);
}
</script>
I did it that way for read-ability, but you could make it even shorter and faster...
function setIFrameSize() {
f = $("#myframe");
f[0].setAttribute("width", f.parent().width());
f[0].setAttribute("height", f.parent().height());
}
One selector, so you only look through the DOM once instead of multiple times.
For those using Prestashop, this is how I used the code.
In the cms.tpl file I added the below code:
{if $cms->id==2}
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type="text/javascript" src='../themes/myheme/js/formj.js'></script>
<div style="width: 100%; height: 800px;">
<iframe style=" width: 100%; height: 100%; border: overflow: auto;" src="https://cnn.com"></iframe>
</div>
{/if}
Then created a new js file: formj.js and added the below code:
$(function () {
//setup these vars only once since they are static
var $myIFRAME = $(".iframe-class"),//unless this collection of elements changes over time, you only need to select them once
ogWidth = 970,
ogHeight = 800,
ogRatio = ogWidth / ogHeight,
windowWidth = 0,//store windowWidth here, this is just a different way to store this data
resizeTimer = null;
function setIFrameSize() {
if (windowWidth < 480) {
var parentDivWidth = $myIFRAME.parent().width(),//be aware this will still only get the height of the first element in this set of elements, you'll have to loop over them if you want to support more than one iframe on a page
newHeight = (parentDivWidth / ogRatio);
$myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
} else {
$myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
}
}
$(window).resize(function () {
//only run this once per resize event, if a user drags the window to a different size, this will wait until they finish, then run the resize function
//this way you don't blow up someone's browser with your resize function running hundreds of times a second
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
//make sure to update windowWidth before calling resize function
windowWidth = $(window).width();
setIFrameSize();
}, 75);
}).trigger("click");//run this once initially, just a different way to initialize
});

Insert image to DOM resized to 50% of its width/height

So I am trying to insert an image to a page with JavaScript with 50% of its width and 50% of its height.
I do this:
someElement.html('<img src="/path/to/img.jpg" alt="" class="sImg" />');
The sImg class is defined in stylesheet like this:
.sImg{
border: 0;
width: 50%;
height: 50%;
}
Yet the image appears fullsize.
I have also checked via Firebug and the image has width and height both at 50%.
First of all, if you're setting a width and height, you should also include display: block; since inline elements don't generally enjoy being given a set height.
But more importantly, when you express a width (or height) as a percentage, that's a percentage of the parent element, so if the parent is 1000px wide, the image will be 500px wide (regardless of what size the actual image file is).
If you're using JavaScript to determine the current image size and change it, just express the new size in px instead of %.
The CSS you've got means that the width and height should be computed as half the size of the parent container, not the image itself.
What you can do is something like this: create an Image object and give it an "onload" handler. The handler can get reliable size information (because the image will have been loaded), and can then add the image element with the proper size.
var img = new Image();
img.onload = function() {
$(someElement).empty().append($('<img/>', {
src: img.src,
alt: '',
'class': 'sImg',
css: { width: Math.floor(img.width / 2) + 'px', height: Math.floor(img.height / 2) + 'px', display: 'inline-block' } // display should be set as you need it
});
};
img.src = yourUrl;
edit — the eerily knowledgeable Šime Vidas points out that setting the "width" or "height" attribute should make the right thing happen, with the size being reduced appropriately to maintain the aspect ratio.
Does the parent container have a height/width? it maybe that the browser does not know what 50% of x is and what 50% of y is. but if it knew what x and y were then it could apply it. Try
var myWidth = $('.sImg').width(),
myHeight = $('.sImg').height();
myWidth = myWidth / 2;
myHeight = myHeight / 2;
$('.sImg').attr('width', myWidth + 'px').attr('height', myHeight + 'px');
http://api.jquery.com/width/
http://api.jquery.com/height/

Categories