Javascript style issue - javascript

I am using javascript to display the height of my current div.
This is an example of the effected area
//css
.test
{
height:1px;
}
#test1
{
margin:1px;
}
//html
<div id="test1" class="test"></div>
//javascript
var a = document.getElementById('test1');
a.style.height //how I access the style
Firebug says that the length of style is 0 and height is empty.
How can I access the correct height?

You need to look at the computed style, not the specified style. See Quirks mode's getstyle page which answers the question
Sometimes you'll want to see what styles the default document view has. For instance, you gave a paragraph an width of 50%, but how do you see how many pixels that is in your users' browser?
and it explains how to derive and use the getstyle function, though it's easier to use a library like jquery which provides a simple css function.

Try a.offsetHeight instead of a.style.height
jsfiddle demo

div height is dependent on its children. If its empty, it'll be 0.
The code you have to get height is correct, btw.

Check out the getComputedStyle method. It should do what you are looking for. Kinda lame, really, I wish this was handled better in the DOM.

Related

Javascript/AngularJS: Check if an element has the style overflow-y applied to it

I am trying to check inside my code if a has applied to its css styling the attribute overflow-y: auto. For example if my has a class "abcd", and "abcd" has for its css overflow-y: auto, then the passes. While I've already found a method for jquery, which I am not using, I want to find a method for pure javascript (or Angular JS) to find if the element has a given css attribute. How can I do this without jquery?
You can check with pure javascript by using this code : document.getElementById('myElement').style['overflow-y'].
The issue is that this code will works only for inline css style, as in <div style="overflow-y: visible">...</div>. If the css style comes from a class, you can't find it like this.
The jQuery css method will find the computed style (so it can detect the real value of overflow-y even if it comes from a class). But the css code is very huge. You can find it here : https://github.com/jquery/jquery/blob/master/src/css.js
I want to add that checking if an element has a specific css style is a very bad smell.
Instead of this, you should really consider to check if the element has a specific class. Or if you have using angularjs, a simple boolean in the model will do the trick.
If you really want to check if an element has the overflow-y: auto; style applied, according to the jQuery code, they use window.getComputedStyle(element). They also have a lot of code with a temporary div with a weird position (position:absolute;left:-11111px;width:60px;) but it is mostly to support old browsers like IE8 and IE9.
In your case, something like this could works : window.getComputedStyle(document.getElementById('myElement'))['overflow-y'] === 'auto'.
You can use the getComputedStyle method available on the window object.
var myElement = document.getElementById('myElement');
var overflowValue = getComputedStyle(MyElement).overflowY;
if (overflowValue == 'auto') {
// your code here
}
This method will get values of css properties applied in the moment.
For more info, you can refer here.
hope that helps.

Use jQuery to get css properties of a class/id that that doesn't exist in the page

As it said in the title. I want this javascript...
$("#mrNotAppearing").css("background-color");
to return "red" based on this css...
#mrNotAppearing {
background-color: red;
}
given that there are no elements in the document that actually have the id mrNotAppearing
I'm using media query checks with jQuery to get window widths as seen here and I thought it might be nice to use some "dummy" css that definitely won't get in the way of anything.
I'm also open to other suggestions that achieve the same result.
Plan B, I'll just go with actual css or add some dummy property to body?
Updating for clarity:
It can be difficult to sync javascript that requires particular window widths with media query widths in the css, which can cause layout problems.
Instead, you can query the status of the css itself. As so:
body {
background-color: blue;
}
#media (min-width: 42em) {
body {
background-color: red;
}
}
Then, in the javascript:
if($(body).css("background-color")==="red"){
// we know down to the pixel that it's safe to trigger the javascript
// because the media query went off.
}
All I'm trying to do is add a dummy entry in the css that will be used solely for triggering the javascript. I could use an existing property--and may have to--but I'd like to make it explicit what I'm doing. Or I'm at least toying with the idea.
I apologize for the confusion. I was going for brevity.
P.S. the whole point of the question is to use a style that will 100% not be appearing in the document. And will never change, even if the layout does.
EDIT: Ha, okay, final answer. em does indeed return as px. So...
I'm going to answer my own question because I'm pretty sure it isn't making sense to anyone. Also, I don't know if this is a good idea, but it seems to work for my purposes. So, my solution:
Style the <style> tag. It's in the DOM, it's not structural, and jQuery can get css properties from it. Like so...
style {
width: 672px;
}
and then...
$("style").css("width");
will return 672px
I'm probably over-thinking this. And still probably not making sense. And I have no idea if this works on any browser but Chrome or if it's a terrible idea for some reason, but I think it's kind of appealing, semantically.
Any other thoughts?
You have access to all css rules through document.styleSheets, there is no need to apply to an element.
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet
Here is another answer on how to get the style based on a class name:
How do you read CSS rule values with JavaScript?
EDIT
Although, it would be a lot easier to render the element off canvas for a brief moment:
var $dummy = $('<div>').addClass('class1 class2 class3').css({position: fixed, left: 100%}).appendTo('body');
// collect all info you need here;
$dummy.remove();

Trying to pass parameters to CSS from JavaScript

I have started working on a poetry app for the iOS platform which highlights the relevant text as the recording plays (as selected by the user). The user will see a list of options to play the audio (i.e. starting line, ending line), and as the app plays the recording, the relevant line will also be highlighted. My question is this:
My CSS code which is responsible for highlighting the relevant text looks like this:
#container {
positioon:relative;
}
#highlight {
position:absolute;
width:75px;
height:75px;
top:75px;
left:75px;
background: rgba(255, 0, 0, 0.4);
}
The values for width, height, top, left, and background are not static, they are dynamic (i.e. they will differ for each line). Is there a way for me to pass these values to the CSS from the JavaScript function that is calling it (which would in turn, be pass to the JavaScript from Objective-C)? Just wondering.
May I propose a different solution? I hope this is a little easier than your current attempt.
If you have some HTML like this:
<div class="lyrics">
<div class="line">I went down to the demonstration</div>
<div class="line">To get my fair share of abuse</div>
<div class="line">Singing, We're gonna vent our frustration</div>
<div class="line">If we don't we're gonna blow a 50-amp fuse</div>
</div>
So that each 'line' is it's own element, then it makes it very easy for your code to cycle through the lyrics line by line at an interval. This could be song lyrics, sheet music, even audio captions...
As you cycle through the lines you can target each one and add and remove classes. You don't have to use the jQuery library, but I use it pretty extensively so you could do something like:
// before transition
$(this).removeClass('highlight');
$(this).next('.line').addClass('highlight');
Then in CSS just give the ".line.highlight" or ".lyrics .highlight" some style definitions:
.lyrics .highlight {
font-weight:bold;
background:#ccc;
}
Things like the width and height would then be inherited, and you could reference them by calling:
$(this).css('width');
jQuery - css() - http://api.jquery.com/css/
jQuery - next() - http://api.jquery.com/next/
jQuery - removeClass() - http://api.jquery.com/removeclass/
jQuery - addClass() - http://api.jquery.com/addclass/
yes, what you do is in your javascript, look up the value.
$("#highlight").width()
for example, will get you the actual width.
Use jQuery to get and manipulate CSS properties of elements, as detailed here
You can add css to an element using jquery:
$("highlight").css('width','200px');
and you can replace 'width' with any valid css property, as well as pass in multiple properties.

Make div overflow its container to work with marquee.js

I have built a music player which loads songs from a database in a random order. I would like to display track info in an info panel. Because I do not know the length of artist/track names, I would like the info to scroll with a marquee effect if it's too big. I'm told browser implementations of the marquee tag are bad so I have got a jquery plugin to do that for me in a nice smooth way (I assume the auther knows why they're bad and has sorted it).
So far so good.
The trouble is the marquee doesnt work out whether it is needed, so I would like to run a check to see if it is necessary (ie if the length of the text warrants it or not) before calling it.
Now I'm sure the problem here is a simple css one but I cannot for the life of me figure it out - you know when you've been staring at something too long...
What I am attempting to do is call the marquee on an inner div if the contents of the inner div are bigger than the outer div but no matter what I do I can't seem to get my inner div to stretch horizontally beyond my outer div unless I set a fixed width (which isn't very helpful since I don't know the width of the content).
Here is my simplified HTML (wrapper contains some other stuff floated either side):
<div id="mplayerinfo_wrapper"><div id="mplayerinfo_trackinfo"><div id="ti_inner"></div></div></div>
Here is my simplified css:
#mplayerinfo_wrapper{
width:545px;
height:30px;
margin-top:32px;
display:inline-block;
float:left;
}
#mplayerinfo_trackinfo{
height:30px;
width:238px;
display:inline-block;
overflow:hidden;
float:left;
}
#ti_inner{
float:left;
height:30px;
width:auto;
}
I am then hoping to use jquery to get the width of both elements, compare them and if inner is bigger than outer, launch the marquee like so:
var owidth=$('#mplayerinfo_trackinfo').width();
var iwidth=$('#ti_inner').width();
if(iwidth>owidth){$('#ti_inner').marquee();};
If this can't be solved through css, is there away to get content width with jquery/javascript. Any ideas? Thanks in advance
Since you already know the width of the outer div, it may be easier to compare against that measurement rather that ask for that width dynamically. I've tried to re-create your simplified program and the problem I ran into was that the width() function only returned the default width of the div's, not the width as modified by css.
Your CSS looks appropriate for what you are trying to accomplish. I would try this for the comparison:
if ($('#mplayerinfo_trackinfo').innerWidth() < $('#ti_inner').outerWidth()) {
$('#ti_inner').marquee();
}
I have had better results when using JQuery's inner and outer measurements.
the ti_inner CSS needs to have
white-space: nowrap;
to prevent the div just increasing in height,
We can then check the widths to see if a marquee is required.
I prefer to check the scrollWidth and the offsetWidth of the outer mplayerinfo_trackinfo instead of comparing the width of the 2 separate divs, mainly so that and margins,borders or padding dont get in the way, but in this example it doesnt really matter.
Heres a sample on JSFiddle marquee if required
Sorry it's in mootools but I'm new to all this web stuff myself and have not used any JQuery but from what I've read it should be easy to swap.

object.style.height doesn't work

I've googled this but didn't find an answer, this is strange. In Javascript in Firefox when I do object.style.height it doesn't return anything. Would anybody know why?
In CSS I've put
#movable {
height: 100px;
....
In HTML I've put
<div id="movable"> </div>
And in JS:
alert(movable.style.height);
You're trying to get the element's CSS height. If there isn't one defined in the element's style, that's what you get.
If you want the physical height, use object.offsetHeight
element.style is just a conversion of the element's style attribute into a scriptable object. If you haven't set any inline style on the element, you won't get anything back.
If you want to query the dimensions of an element, there are a number of ways, such as object.getBoundingClientRect().

Categories

Resources