How to apply the offset .top to the height of a div? - javascript

On this blog I want to edit the height of the #content div and make it height: x.top px (of the article:last-child) so that the background which is repeating itself vertically.
http://manutdstream.tumblr.com/
I tried to do this:
$(document).ready(function(){
x=$("article:last-child").offset();
$('#content').css('height' : 'x.top px');
});
I think the problem is in the .css() as when I ran it to alert the x.top it went fine.

Your variable is being treated as a string, place it outside the quotes and add it to the string with a +:
$(document).ready(function(){
var x = $("article:last-child").offset();
$('#content').css('height' : x.top + 'px');
});

If you're just setting the height, no need to bother with css. Pixels is the default unit for the height function:
$(document).ready(function(){
var lastArticle = $("article:last-child");
$('#content').height(lastArticle.offset().top);
});
Not to nit-pick, but I'd recommend against using variables named something like x even for simple things -- unless you actually mean x (for example, coordinate spaces). Code is already hard to read, but good names can make it easier.

The syntax for .css() is incorrect, should be
$('#content').css('height', x.top + 'px');
Fiddle example:
http://jsfiddle.net/jessikwa/5vnbLr91/

Related

How to change comma separated css values with Jquery.css Method?

I am trying to stack background images using only one div container and making sure their position is related to the screen height. The issue is I can't seem to alter comma separated CSS values. Here is how I logically thought it would work.
jQuery(document).ready(function() {
windowHeight = window.innerHeight;
jQuery("#home-bg.bg-1").css('background-position-y', '0, ' + windowHeight);
});
You should add px at the end:
jQuery("#home-bg.bg-1").css('background-position', '0, ' + windowHeight+'px');
background-position-y only takes one value. It should not be comma separated. You may be confused with background-position which takes two values, x and y position.
Try this:
jQuery(document).ready(function($) {
windowHeight = window.innerHeight;
$("#home-bg.bg-1").css('background-position-y', windowHeight);
});
You should use background-position and set both values. Don't use background-position-y. See here why.
If you still want to use it, then you have to remove 0,, because background-position-y only takes 1 argument and don't forget to add px to the value.

JavaScript get size of content box

I was using padding to restrict the size of the content-box. I need a way to get the size of the content box width and hight in pixels.
I'm open to work around's like nesting elements, pseudo-elements, trying out something like flex box setups.
However, a vanilla JavaScript way to get these values is the subject of the question.
Example: http://codepen.io/anon/pen/lbzJi
Taken from the answer to a similar question; you can use window.getComputedStyle(element, null).getPropertyValue('css-property'); to obtain the value of a computed CSS property. In your case, you can use this for the properties padding-left, padding-right, padding-top and padding-bottom.
For example, to compute the height of the content box of your "box" div you can do something similar to the following where I assume the padding is specified as an integer (hence the parseInt);
function property(e, p) {
return parseInt(window.getComputedStyle(e, null).getPropertyValue(p));
}
var box = document.getElementById('box');
var paddingTop = property(box, 'padding-top');
var paddingBottom = property(box, 'padding-bottom');
var contentHeight = box.clientHeight - paddingTop - paddingBottom;
Try this using jquery: http://codepen.io/anon/pen/shoun
$(document).ready(function(){
$("pre").append("Total Height = " + ($("#box").height() - parseInt($("#box").css("padding-top"))));
});
Well, you could try:
element.clientHeight
element.clientWidth
-or-
element.offsetWidth
element.offsetHeight
depending on what you want, but we'd need some code to really help you out.

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)

Fit text to a div

I have a div with fixed height and width and inside I have text that is changing. Sometimes it can be a word or two and sometimes it can be a sentence. What I need is to shrink the font size so the text fits to that div.
i had an idea and it worked :) here is my code
$('li').each(function () {
while ($(this).outerHeight() > 25) {
var currentFontSize = $(this).css("font-size");
$(this).css("font-size", (parseFloat(currentFontSize) - 1) + "px");
}
});
I had a similar issue, which made me write my own plugin for this. One solution is to use the shrink-to-fit-approach, as described by user54316.
However if you have to fit multiple items or are concerned with performance, e.g., on window resize, have a look at jquery-quickfit.
It meassures and calculates a size invariant meassure for each letter of the text to fit and uses this to calculate the next best font-size which fits the text into the container.
The calculations are cached, which makes it very fast (there is virtually no performance hit from the 2nd resize on forward) when dealing with multiple texts or having to fit a text multiple times, like e.g., on window resize. I think it would work perfect in your case.
You'd just have to call
$('#yourid').quickfit()
after you changed the text.
Production example, fitting 14x16x2 texts
Try giving the font-size in em:
http://clagnut.com/blog/348/
http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/
There is a jQuery plugin for that: FitText.js
Here the URL: https://github.com/davatron5000/FitText.js
Here's an example: http://jsfiddle.net/martinschaer/sRvB9/
The function fitText() receives a parameter, with which you need to "play" in order to get the results you want. Also, it resized the text when the window is resized; if you need to have the text resized when (for example) a div is resized, you should add a pair of JS lines for that ;)
$text.css('font-size', "100px");
$text.css('line-height', "100px");
var foo= $div.width() / $text.width();
var bar= $div.height() / $text.height();
if(foo < bar) {
foo=Math.floor(foo*100) +"px";
$text.css('font-size', foo);
$text.css('line-height', foo);
} else {
bar=Math.floor(bar*100) +"px";
$text.css('font-size', bar);
$text.css('line-height', bar);
}
//centralizing text, top and left are defined as 50% on the CSS, optional
$text.css('margin-left', -$text.width() /2 + "px");
$text.css('margin-top', -$text.height() /2 + "px");
One small note is that you need to call this function if the div itself changes size. You can bind this code to the resize eventof the div.
you can do it by defining the font size like......
.small {font-size: 0.8em}
you can see effect here working demo

Convert css width string to regular number

While trying to compute the width of an hidden element I found that jquery.width() returns 0 for that elements' width.
I found out that using jquery.css('width') would return the correct width by using the declared style width (even if that value is different from the initial stylesheet). The problem is that the css('width') method returns a string, generally in a "100px" fashion. My question resolves into: how to retrieve the number from the "100px" string?
Is there an easy way?
If it always returns in px format, "100px", "50px" etc (i.e. not "em" or percent), you could just...
var width = parseInt($("#myelem").css("width"),10); // always use a radix
or
var width = parseInt(element.style.width,10); // always use a radix
It ignores the "px" suffix so you should be good to go.
Although deep down I'm thinking that something isn't right if $("#myelem").width() isn't working.
Note on hidden elements.
If you are adding jQuery to progressively enhance you page, the element you are calculating should be visible when the page first loads. So you should get the width before you initially hide the element. By doing this, $("#myelem").width() will work.
var myWidth = 0;
$(document).ready( function () {
myWidth = $("#myelem").width();
$("#myelem").hide();
});
In plain JavaScript:
parseInt('100px', 10)
Works with "100em", "100%", and even with: "100". No need for any Regular Expression patterns.
You could remove non-numericals with a regular expression and then just convert to a number. This works no matter how you define the width (px, em, %, pt). Preserves decimal points too.
vanilla javascript
Number(elem.style.width.replace(/[^\d\.\-]/g, ''));
jQuery
Number($elem.css('width').replace(/[^\d\.\-]/g, ''));
Oh, I came up with:
new Number($elem.css('width').slice(0, -2));
//to extract the 'px' and return a regular number
Now I only hope that jquery allways returns the same string fashion: "100px"
I would stick to .width() because it actually gets the computed width instead of css width. Instead of hiding it with .hide() (display: none) you could hide it with .css('visible', 'hidden') then .width() should work.
from my comment
If you don't want to change your .hide()´s then you could apply visible: hidden and thereafter .show() and then measure the height. After you have measured it, reverse that. Objects still affects the page layout when they are hidden by visible: hidden - beware of that.
To avoid tags which mess with the layout, you could set the position to absolute, move it to the body tag and then measure.

Categories