Modify external CSS values - javascript

Hi I am trying to dynamicly change the height of a division using JavaScript but I can only get the JS to read the Height element of the div if it defined using style tags inside the HTML mark-up.
If its in a separate sheet it returns NaN, I'm assuming because it can't find a value and is actually returning null (I'm using ParseInt to make it work).
Here is the HTML:
<div id="dropdown_container">
<div id="dropdown" style="height:100px;">
a
</div>
</div>
(Wish the HTML stlye markup)
And here is the JS:
function clickDown() {
var el = document.getElementById('dropdown');
var maxHeight = 200;
getHeight = parseInt(el.style.height.substring(0,(el.style.height.length)-2));
console.log(getHeight);
getHeight += 2;
el.style.height = getHeight + 'px';
timeoutHeightInc = setTimeout('clickDown()',15);
if(getHeight >= maxHeight){
clearTimeout(timeoutHeightInc);
}
}
Does anyone know of a reason for this (mis?)functionaility. And a solution for it?
Here is a jsFiddle.
Try moving the height over to the CSS to see the issue i'm having.

ParseInt is missing it's radix.
You say:
I can only get the JS to read the Height element of the div if it
defined using style tags inside the HTML mark-up
Now you are only reading the div's attribute style. Which you set inline. So if you remove that, than you can not read it anymore. Make sense?
You want to get the computed height. Try: .offsetHeight
Basis of test-case to play with inc. fixed radix. this fiddle
UPDATE: tada: fixed, see this updated fiddle
function clickDown() {
var el = document.getElementById('dropdown');
var maxHeight = 200;
getHeight = parseInt(el.offsetHeight,10);
console.log(getHeight);
getHeight += 2;
el.style.height = getHeight + 'px';
timeoutHeightInc = setTimeout('clickDown()',15);
if(getHeight >= maxHeight){
clearTimeout(timeoutHeightInc);
}
}

Related

JS - check if element's declared style property is set in vh

Say we have an element
<div class="vh-100">
Content
</div>
.vh-100 { height: 100vh }
How can I get to read that exact value 100vh, because
var computedHeight = window.getComputedStyle(element).height; // will simply return the `window.clientHeight` value in pixels in this case.
var styleAttributeHeight = element.style.height // will return '', which is empty
To put it simply, I need to find a way to determine if the value is set in vh because the child elements of the example <div class="vh-100"> have the box model broken and return incorrect offsetTop and offsetLeft for some reason.
I need a simple solution excluding checking the rules in the CSS file.
Here is a link to hopefully explain why I need this.
Directly no way, but i convert pixels to vh(1vh is 1/100 browser height). Here is code snippet, i hope it will help you.
/*var z = getComputedStyle(document.getElementsByClassName('deneme')[0],null).height.replace('px','');*/
/*var b = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);*/
//deactive variables for detailed usings.
var a = document.getElementsByClassName('sample')[0].clientHeight;
var b = window.innerHeight;
var c = Math.round((a / b) * 100) + "vh";
console.log(a)
console.log(b)
console.log(c)//it's your "vh"
.sample{
width: 10vw;
height: 1vh;
background:dodgerblue;
}
<div class="sample"></div>
if what you want is the unit of the height
yourElement.style.height
Normally it will return a string of height in it unit that you settled for the element (so '100vh' in your case).

if-image-height JavaScript statement

I have a grid of several images on my website. Hovering on one of these images will display a label with a name and price. The problem is that some images have a smaller height, and then the label gets too close to the bottom. Now I'm trying to write a JS if-statement in order to decrease the margin-top of that label only if the image-height is less than 200px.
This is how my html looks like:
<div class="fw_preview_wrapper">
<img src="'.$row['imageURL'].'" alt="" class="fw_featured_image" id="product_image" width="540">
<span class="price_tag" id="price_tag"><span class="actual_price">€ '.$row['Price'].'</span>
As you can see, the image URL is variable and comes from a database via php. For the js function, I set id="product_image".
This is the CSS part:
span.price_tag {
top: 86%;
}
As you can see above, there is a margin top set to 86%. This very value needs to be changed to "80%" when an image has a height of less than 200px.
and finally, the JS part:
<script>
var img = document.getElementById('#product_image');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
if(height < 200){
$("span.price_tag").css('top','80%');
}
</script>
It doesn't work. I would appreciate some help. Thanks in advance!
Don't use hash # within param for getElementById:
var img = document.getElementById('product_image');
However you're using jQuery too, seeing your code, why not do just like this:
var img = $('#product_image');
var width = img.width();
var height = img.height();
if(height < 200){
$("span.price_tag").css('top','80%');
}
in javascript you should be using:
var img = document.getElementById('product_image');
# is used in jquery like: var img = $("#product_image")
remove # from the element getting statement , we use # to specify id in Jquery and not in js
try this..
<script type="text/javascript">
var img = document.getElementById('product_image');
var width = img.clientWidth;
var height = img.clientHeight;
if(height < 200)
$("span.price_tag").css('top','80%');
</script>

jQuery window width not equal to CSS's window width

I'm using the following two pieces of CSS and JS code:
#media (max-width: 720px) {
// a code to make arrows in a carousel disappear
}
if(jQuery(window).width() <= 720){
// a code to make arrows in the carousel stop working
}
The problem with them is that the latter executes on exactly width=738px and not 720px. I suspect that this is because of browser's vertical scrollbar that has width equal to 18px in Chrome.
Is there a way to unify this? I'd like these actions to happen at the same moment in all browsers regardless of the scrollbar's width.
Tests (when browser is # 720px and CSS has already executed):
jQuery(document).innerWidth() = 703
jQuery(window).innerWidth() = 703
jQuery(document).width() = 703
jQuery(window).width() = 703
jQuery('body').width() = 703
jQuery('html').width() = 703
I had to tackle the same problem a while ago, and so far the most correct solution I found is to use media queries to pass the actual window size to Javascript. You have to follow these steps:
Add a hidden element to your page,
Use media queries to alter the max-width property of that element,
Read back the max-width property of that element through Javascript.
For instance, add the following element to your page:
<div id="currentMedia"></div>
Then write the following CSS rules:
#currentMedia {
display: none;
}
#media (max-width: 720px) {
/* Make arrows in the carousel disappear... */
#currentMedia {
max-width: 720px;
}
}
Then, from the Javascript side, you can write:
if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
// Make arrows in the carousel stop working...
}
And it will be accurate regardless of the scrollbar size, since the value comes from the same media query that triggers the carousel's disappearance.
I tested this solution on all major recent browsers, and it gives correct results.
You will find the big summary of what properties are supported on what browsers on this page on quirksmode.org.
Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight.
innerWidth documentation
innerWidth() says this method is not applicable to window and document objects; for these, use .width()
try
How can I get the browser's scrollbar sizes?
From Alexandre Gomes Blog
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
in your code
if(jQuery(window).width()-getScrollBarWidth(); <= 720){
// a code to make arrows in the carousel stop working
}
A bit outdated thread, but i've found this solution
function getWidth(){
return ((window.innerWidth > 0) ? window.innerWidth : screen.width);
}
If you are using Bootstrap > 3 then I will suggest you something.
Bootstrap ships with .container class in its Css and predefined. And its altering with #media queries.So my working code sample for this is below.
function detectWidth(){
var width = $('.container').eq(0).outerWidth() ;
console.log(width);
if(width<750){
// do something for XS element
}else if(width>=750 && width<970){
// do something for SM element
}else if(width>=970 && width<1170){
// do something for MD element
}else{
// do something for LG element
}
}
I realize this is an old thread, but I think it can still benefit from this answer.
var width = window.outerWidth;
This will give you the width of the window including scrollbars, which is what media queries use, I believe.

Resize a dynamically generated string with javascript?

I've got an HTML page with a grid of divs containing read only text boxes, each containing a string which changes dynamically via a php script. I've been working on a javascript function to detect the string length and resize the string accordingly so that it fits cleanly in the textbox with no overflow.
This is an example of my div...
<a href='http://burstu.com'>
<div id='toprightlefthigh' class='resize'>
<input type="text" id="toprightlefthighbox" class="idea" value="" readonly>
</div>
</a>
I've tried various scripts, and my nearest fit is this one...
var div2length = div2.value.length; if(div2length <=50) {
div2.value.fontSize="10px"; }
But no such luck.
Any ideas?
div2.value.fontSize="10px";
this doesn't work; you need to access the fontSize using style:
div2.style.fontSize="10px";
Are you aware of the fact that font-size is not inherited by a form element?
By default, browsers render most form elements (textareas, text boxes, buttons, etc) using OS controls or browser controls. So most of the font properties are taken from the theme the OS is currently using.
You'll have to target the form elements themselves if you want to change their font/text styles. In stead of targeting your wrapper div (I guess you are doing by the name you gave you're variable, div2 is not beeing set in your snippet), you should target the input directly.
#andrewGibson is also right btw, you should use the style property.
Have you taken a look at http://fittextjs.com/ it does just that. I'm not a fan of the "throw jquery at it" crowd but that one does the job and its open source so you could have a poke around if you wanted to learn more if you are after a pure JS solution. In this case though why re-invent the wheel :)
Do this...
Html:
<input type="text" id="toprightlefthighbox" class="idea" value="" />
Javascript:
var MAX_FONT = 20;
var MIN_FONT = 10;
var YOUR_STRING = "Here is my long long long long string";
var textbox = document.getElementById("toprightlefthighbox");
var fontSize = MAX_FONT + 1;
var element = document.createElement("div");
element.style.visibility = "hidden";
element.style.display = "inline-block";
element.style.padding = "0px";
element.style.fontFamily = "Arial";
element.innerHTML = YOUR_STRING;
document.body.appendChild(element);
do
{
fontSize -= 1; //maybe -= 0.5 in some browsers? Just change the +1 above too
element.style.fontSize = fontSize + "px";
} while (fontSize > MIN_FONT && element.clientWidth > textbox.clientWidth);
document.body.removeChild(element);
element = null;
textbox.value = YOUR_STRING;
textbox.style.fontSize = fontSize + "px";
With CSS:
#toprightlefthighbox { width: 205px; height: 25px; font-family: arial; }
JSFiddle:
http://jsfiddle.net/hkN35/4/
Notice that when you decrease the width of the textbox to 200px it will bump the font size down.

How to get total height of 3 p tags inside a div?

here is my code
<div class="entry-content"> <p>some text...</p> <p>some text...</p> <p>some text...</p> </div>
My entry-content div has an absolute positioning, so the text inside the p tags goes under the footer. i have to fix the height of entry-content to total height of all p tags using javascript.
please help.
Use outerHeight (Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.)
var total = 0;
$('.entry-content').find('p').each(function() {
total += $(this).outerHeight(true);
});
$('.entry-content').height(total);
Try like this... Working Demo
var height = 0;
$('div.entry-content p').each(function() {
height += parseInt($(this).outerHeight(true));
});
Have you tried using $('.entry-content').height(), or similar functions like .innerHeight()? (jQuery docs).
You wouldn't need to set the height of the <div>, but you could measure the default height, and use that to position your footer.
A word of warning: because of text wrapping, the height of that div might change when the window is resized. You might want to set a callback using $(window).resize(...), to update the positioning when that happens.
I made a little jQuery plugin a while back that hopefully will come in handy for a problem such as this:
Plugin
(function ($) {
// helper 'plugin' for getting the total height
$.fn.totalHeight = function ()
{
var totalHeight = 0;
this.each(function () {
totalHeight += $(this).height();
});
return totalHeight;
}
})(jQuery);
Usage
var totalHeight = $('.entry-content p').totalHeight();
Edit: This could easily be adapted to support outerHeight() or innerHeight().
jsBin demo
Use: outerHeight(true)
var entryHeight = $('.entry-content').outerHeight(true);
$('#footer').height(entryHeight);
$(function(){
var totaltHeight;
$('.entry-content p').each(function(){
totaltHeight = totaltHeight +$(this).height();
});
});
something like that perhaps
this is depended on jQuery

Categories