How to use jquery API over html string - javascript

context: I have an ajax request which return data structure with an html key.
I would like to wrap this data with a jQuery object to be able to use API like width / height and modify the data before adding it to the DOM.
> $('<div width="220" height="200"></div>').width()
0
So how could I do to get 220 and then modify it ?
I'm using jquery 1.7.2
Edit:
I'm not from the 90's because I use the wrong tag in my example. My need is to change width and height of an iframe for responsive:
> $('<iframe width="220" height="200"></iframe>').width()
0

Elements have no width before they're added to the DOM.
A solution, if you really need to not have it in the DOM, is to add it and then detach it :
var d = $('<div width="220" height="200"></div>');
d.appendTo(document.body);
var w = d.width();
d.detach();
As the screen isn't redrawn until your script ends its task, this operation won't be seen by the user.
But note that without a different style, this won't give you 220. You probably want this :
$('<div style="width:220px;height:200px;"></div>');
Demonstration

You must be from the 90's, because who uses width and height attributes on a div?
There's no width "before adding it to the DOM".
3.
$('<div width="220" height="200"></div>').attr('width')

Use css:
$('<div></div>').css({ 'width': '220px', 'height': '200px'});
This will set the width and height. Since you are setting it, there really is no need to get the width afterwards, right? But you could if needed with width().
EDIT:
Maybe I misunderstood - the question isn't too clear. If you want to get the width of an element then width works, but as mentioned, the element needs to be added to the DOM first.

Related

Calculate the size in pixels of div based on its content?

What would be the best way in Javascript/JQuery to determine the size in pixels a div would actually take to display it?
Let say I have a table with and the columns are fixed with the tag width="60px". Inside this column I add dynamically a div with a certain content, which will mostly be the following :
<div class="auto">
<img width="50px" src="/images/header-5123724.png">
<hr>
<span>Table1</span></div>
So, I know the size of the image which is 50px, but I do not know how long the text will be.
Another hint I have is that the element <span> will always be there, and the content should not be wrapped.
Is there a way to "render" the span and to get the size in pixels?
Any help is appreciated.
I found a way to accomplish what I wanted. I will post it here, maybe that can help somebody.
// add an extra span
$(this).parent().append('<span id="test" />');
//.. pick up the element to test into obj
// test the size
$('#test').html(obj.text()).css({
'font-family': obj.css('font-family'),
'font-size': obj.css('font-size'),
'font-weight': obj.css('font-weight')
});
//Width and adjustment
Width = $('#test').width() + 24;
//...If we want to check the max width, then we can loop through many columns of the table
//Finally adjust the width
obj.width(Width).css('min-width', Width);
//Cleanup
$('#test').remove();";
It is not very clean, but that worked for my case. For some reason the size of the columns were not set properly because it was resized by some plugin after the content was rendered by the browser.
Cheers.
Will the width be calculated on page load or on the fly?
If it is on page load then, #cont is the id of the content box.
$(document).ready(function() {
var dynWidth = $('#cont').width();
console.log('dynWidth: ' + dynWidth);
});
If it is on the fly then,
$(document).ready(function() {
$('#cont').bind('DOMSubtreeModified', function(){
var dynWidth = $('#cont').width();
console.log('changed dynWidth: ' + dynWidth);
});
});
Note: DOMSubtreeModified is not supported in IE8 (and below).
For any details refer this link.

How to get height in AngularJS like in JQuery?

I have this jquery snippet below:
$(document).ready(function() {
var height = Math.max($("#one").height(), $("#two").height());
$("#one").height(height);
$("#two").height(height);
});
I want to convert that to AngularJS, but I've been having an issue on actually getting the height. I've tried many different things including offsetHeight and scrollHeight and they all return 0. Is that because I'm using a table? I'm not sure how to do it / if I'm doing it right. Here's kind of an outline of what I've been trying to do so far:
$scope.height = function()
{
var height = window.Math.max(HEIGHT OF MY ELEMENT "firstTable", HEIGHT OF MY ELEMENT "secondTable");
//Now get the height and set it.
};
I'm not sure if I should make this into a directive and put it in my table (where I can access $element) or what.
Thanks in advance
What you're looking for isn't to use AngularJS to get height, but rather use native JavaScript.
Use document.getElementById() to select your element then use .offsetHeight to get the height and finally .style.height to set your height.
Your code would look a little like this:
var elementOne = document.getElementById("one"),
elementTwo = document.getElementById("two"),
height = Math.max(elementOne.offsetHeight, elementTwo.offsetHeight);
elementOne.style.height = height;
elementTwo.style.height = height;
Note that I created variables for each element to avoid repeatedly retrieving the element via document.getElementById() for getting and setting the height.
I would recommand using plain old javascript to do so.
Looks like this works well :
document.getElementById('someDiv').clientHeight;
// clientHeight includes the height and vertical padding.
document.getElementById('someDiv').offsetHeight;
// offsetHeight includes the height, vertical padding, and vertical borders.
document.getElementById('someDiv').scrollHeight;
// scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
Found solution on Stackoverflow : CSS / JavaScript - How do you get the rendered height of an element? so I do not have any merit ;).
jqLite (which is included in Angular) is limited and doesn't offer a function to calculate the height.
Your best options here is to inject the element into controller,
and get the height via:
element[0].offsetHeight;
Demo on plnkr: http://plnkr.co/edit/g45SX4unuCNwlVIUEw4j?p=preview

jquery 1.8 and higher, set the height of a div to the same as another div

As of Jquery 1.8 a change was made when getting the height() of an element. I have a CSS div height set to auto with the image inside dictating the height and width of the div by using % and auto), and when the window loads i use Jquery to get the height of the element and make another div next to it the same height. After researching this I have noticed that it is returning the height before the CSS has set the new height that is set by the image. 1.7 allowed this, but 1.8 and up does not. Is ther a work around.
this is the css
#element1{ width:80%; height:auto;}
#element1 img{width:100%; height:auto};//this allows the image to resize with the page responsively.
jQuery...
$(window).ready(
function(){
var x = $("#element").height();
alert(x); // this would return what the height was dynamically set as by the css in 1.7, but 1.8 returns a small number that i am pretty certain is just the padding added to 0px
});
Hopefully this makes sense, and someone has a work around.
Thanks
Instead of listening on $(window).load(), which might stall proper height assignment until all resources have been successfully loaded, you can listen to successful loading on each <img> instance and trigger proper height calculation.
However since in your question you only have one element you are concerned with setting height dynamically, I have reduced my script without the need to loop through all <img> instances on the page. Assuming that you have the following markup:
<div id="element1">
<img ... />
</div>
You can create a new image, check if it is loaded and then instruct jQuery to run the height calculations and set a new height when this is done:
$(function() {
var $img = $('<img />', {
'src': $('#element1 img').attr('src')
});
$img.load(function() {
$('#element2').css('height', $('#element1').height());
});
});
There's a mismatch between your css selector (#element1) and your jquery selector ('#element'). Start by making them both match whatever you have on your html element. You could also wrap this in a timeout so your image will have time to fully load.
$( document ).ready(function() {
setTimeout(function() {
$('#element2').height( $('#element1').height() );
}, 2000});
});

Variable w/ JQuery selector breaks my code

I'm having an issue with a jQuery selector in a variable.
Oh and the HTML (background-image:url('SOME-IMAGE-URL')) has an inline style, not in a stylesheet.
I can't seem to make this JS/JQuery script. It completely breaks the script.
var contentHeight = $(this).css('background-image').height();
Full code:
var sliderWidth = 0;
$(".slider li").each(function() {
var contentHeight = $(this).css('background-image').height();
sliderWidth = sliderWidth + 100;
$(".slider ul li").css("height",contentHeight);
});
var sliderContentWidth = sliderWidth/100;
$(".slider").css("width",sliderWidth + "%");
$(".slider li").css("width",100/sliderContentWidth + "%");
setInterval(function(){
$(".slider ul").css("right",100/sliderContentWidth + "%");
}, 5000);
$.css()
The above function (jQuery.css()) returns the CSS value for a given property; in your case a string. Strings don't have a .height() method though.
So on your line..
var contentHeight = $(this).css('background-image').height();
This is actually happens..
$(this) is evaluated; and returns a jQuery instance.
.css('background-image') is ran on the jQuery instance, and a string is returned (the image name)
.height() is ran on the string... but it doesn't exist.. uh oh.
In your scenario though, the height of the element itself will probably suffice.
$(this).height()
Especially considering that by default the background will just repeat if it's smaller than the element, and won't overflow if it's bigger.
Going beyond the question though, and to clarify after your comment below:
You want the size of the background image? This doesn't hold much use in reality. Take a look at the W3 documentation for background properties.
If the image is smaller than the element it's applied to, then the background-repeat property defaults to repeat. End result? The background takes on the whole element.
If the image is larger than the element it's applied to, then it's simply invisible outside the boundaries of the element. This is why sprites work. End result? The background takes on the whole element.
This behaviour can be changed using different properties, but in your scenario it doesn't appear to be. So essentially, the height of the element is the height of the background.
If you want to get the actual dimensions of the image then you're going to need to use a <img> element which, being a DOM element, DOES have height() and width() methods/properties. (Although this is going to require absolute positioning and possibly some z-indexing; and if you need to do this then it's probably best to re-think whatever you're doing)

can not get the width of the html element

I create an element using js,and I have imported the related css,however I can not get the width of the element,this is the code:
css:
#mainDiv{
position:absolute;
width:500px;
height:500px;
}
js:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
//now I want to get the width of the 'mainDiv'
var wd=mainDiv.style.width;
console.info(wd);
However the value of the 'wd' is always ''.
I wonder why?
Using the firebug,I found that the width of the 'mainDiv' is 500px.
But why I can not get the value in the js?
I do not want to set the width and height of the 'mainDiv' in the js like:
mainDiv.style.width='500px';
I want to set the size in the css.
Any idea?
try
var wd=mainDiv.clientWidth;
Use mainDiv.offsetWidth .
Hope this helps.
Listen, this is an awful answer, but just use jQuery.
If you did this would be as simple as:
var width = $('#mainDiv').width(); // width has the value 500
Docs: http://api.jquery.com/width/
In order to get the actual width of a DOM element you must use offsetWidth.
From W3Schools:
offsetWidth: Returns the width of an element, including borders and padding if any, but not margins
This example should work:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
var wd=mainDiv.offsetWidth;
console.info(wd);
It's because the element is not yet rendered. I know it's awful, but you should delay reading the width a bit:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
setTimeout(100, function() {
console.info(mainDiv.style.width);
});
You cannot get the width because you are trying to get it from the style. Sorry went into train, basically because you are not setting the style element but rather defining a class - JavaScript can't read the value from the element.

Categories