Zebra stripes ignoring hidden elements - javascript

Say I have a table whose rows can be dynamically assigned .hidden classes. Rows with that class are hidden via CSS. The rows are also styled with alternating colours, like so:
tr:nth-child(even) {
background-color: $light-grey;
}
However, I want every even, unhidden row to be shaded. So hidden rows are not counted when :nth-child(even) is applied, and the pattern appears consistent. The following is my immediate attempt, but it doesn't do what I'm hoping for.
tr:not(.hidden):nth-child(even) {
background-color: $light-grey;
}
:nth-child() is simply referring to the rows' original indices, not the current selection scope from tr:not(.hidden). The two are simply 'filtered through' on top of one another.
Is there a :nth-of-scope/selection() (or simply :nth()) meta class in CSS? Are there any equivalents or alternate methods?
Or must I resort to Javascript?
(I should say that I can also use jQuery)

There is no way to do this in pure CSS as adding display:none or visibility:none doesn't remove the elements from the DOM, which is what CSS uses.
As a result, you will need to add a little JavaScript (which runs once the page has loaded) to do this, like so
var trs = document.getElementsByTagName("tr"), // Select whichever ones you need
count = 0; // Counter for the non-hidden ones
for(var i = 0; i < trs.length; i++) {
if(!trs[i].classList.contains("hidden") && (count++)%2 == 0) { // Odd ones
trs[i].style.background = "black";
} else if(!trs[i].classList.contains("hidden")) { // Even ones
trs[i].style.background = "lightgrey";
}
}

Turns out using jQuery is much simpler than any sort of CSS hack:
rows = $('table tbody tr');
rows.find('tr:visible:odd').css('background-color', '#f7f7f7');
And to specify styles for both even and odd:
rows.find('tr:visible').each(function(i) {
if (i%2) {
$(this).css('background', '#f7f7f7');
} else {
$(this).css('background', 'none');
};
});
I know, I've answered by own question—I should have made it clear that I can use jQuery!
I just wish :visible and :even would hurry up and make it into the CSS standard.

I've just managed to solve this by just adding an extra <tr> element with display: none; set (via CSS in my case but could use a style attribute) when a block of hidden rows has an odd number of elements. This won't meet every use case, but for cases where you're using multiple rows to create expanding tables it works quite well.

Not sure this is possible with pure CSS. Using display:none; and visibility:hidden; the items still exist in the DOM and so the table background color is displayed incorrectly. You can get this to work using JQuery remove() You can see my simple example on js.fiddle here

Pure CSS (no JS) solution:
The trick is to hide a row with different tag, not class. "ul/li" tags must go. In my example I use "del" tag to hide.
.list div:nth-of-type(odd) { background: ghostwhite; }
.list del { display: none; }
<div class="list">
<div>1</div>
<div>2</div>
<div>3</div>
<del>4</del>
<div>5</div>
<del>6</del>
<div>7</div>
</div>

Related

Select a css3 element by grandparent's parent's class

Im implementing multiple rangesliders into my site and because this is code generated in real time I need to select some elements by their parents parent class.
this is the code the timeline class is the last one i can set myself and i need to be able to edit the .irs-line-right without changing my other sliders
In your question you stated that you want to access an element through a parent element. I don't see why this is necessary, but it's surely possible. You can change the element style, attribute, etc. through js. However, it's best to simply use css if you only need to change the style of the span with the class 'irs-line-right'. I'll show how to do this in both css and javascript.
CSS Example
In css you can change the style of the 'irs-line-right'
by referencing the 'timeline' div (and no other ids or classes) as follows:
https://jsfiddle.net/2t3w0826/
.timeline > div:nth-of-type(2) > span > span > span > span:nth-of-type(3)
{
background-color: red;
}
Javascript Example
https://jsfiddle.net/8qceLgw8/
var array_of_all_timelines = document.getElementsByClassName("timeline");
for(var loop=0; loop < array_of_all_timelines.length; loop++)
{
var element_irs_line_right = array_of_all_timelines[loop].children[1].children[0].children[0].children[0].children[2];
element_irs_line_right.style.backgroundColor = "red";
};

How come changing background color via JavaScript overrides any CSS selectors on my object?

Just a quick question... how is it that if I have the following CSS:
li { background:red; }
li:hover { background:blue; }
With the following JS (or something similar):
document.getElementsByTagName("li")[0].style.backgroundColor="yellow";
My list elements no longer turn blue when I hover over them? I've tested this both on Chrome and FF. And example can be seen here: http://jsfiddle.net/42bQr/. Any ideas?
This is because inline styes are more specific, you can override inline styles with the following:
li:hover { background:blue !important; }
It's because the style is "inline," which takes priority.
Check out this fiddle here to see what's happening: http://jsfiddle.net/9m3qw/
The output of the fiddle is:
<div class="red-bg" style="background-color: yellow;">hello</div>
The reason is because you are setting the style as an inline style which is the most specific. So when you click on a list item, the result is effectively:
<li style="background-color: yellow;">My List Element 1</li>
The following list of selectors is by increasing specificity:
Universal selectors
Type selectors
Class selectors
Attributes selectors
Pseudo-classes
ID selectors
Inline style
To get around this, you could instead assign a class to the list item with:
var listEls = document.getElementsByTagName("li");
for (var i = 0; i <= listEls.length - 1; i++) {
listEls[i].onclick = function () {
this.className = 'yellow'
};
}
where
.yellow {
background:yellow;
}
jsFiddle example
This is happening because you have applied inline style to your selector which has more specifity.
Try this Fiddle
li:hover { background:blue; !important}
If you prefer to use Javascript, then you can use Element ClassList API. But it is only supported in major browsers. Browser Compatibility Matrix. Check out this code
Javascript
var listEls = document.getElementsByTagName("li");
function addYellowClass() {
this.classList.add('bg-yellow');
}
for (var i = 0; i <= listEls.length - 1; i++) {
listEls[i].onclick = addYellowClass;
}
JSBIN Example
As the others have said the inline style takes priority when you click it. You may want to use a hover/mouseover event to add a class ie $(this).addClass('blueBG') with the background of blue that is removed onmouseout if that is the effect you are going for.
"background-color" is more specific than "background" thus it takes priority in your final style. essentially your JavaScript code is overwriting both of CSS properties because it has more weight.
try using background-color as a property in both the CSS and in the JavaScript.

Update CSS rule property value

I have a html element which is styled (using jquery) with a background image targeted thru its class name.
When I remove the class the background image stays - which is not what I expected or want.
test.html
<div id='log' class='tile'>HELLOWORLD</div>
test.css
.tile{
background: none;
}
test.js
$('.tile').css("background-image", "url(tile.jpg)"); // We see image
$('#log').toggleClass('tile'); // We still see image
After banging my head I think I know whats happening. The css is being applied to the element - NOT to the 'class'.
How can I target a specific css rule so that its key values can be updated?
If that makes sense.
If you wan to change the css rules of the ".tile" class, then you can do it.
There is a post that explains it very well :
function changeBackgroundImage(className, value){
var ss = document.styleSheets;
for (var i=0; i<ss.length; i++) {
var ss = document.styleSheets;
var rules = ss[i].cssRules || ss[i].rules;
for (var j=0; j<rules.length; j++) {
if (rules[j].selectorText === className) {
rules[j].style.backgroundImage = value;
}
}
}
}
You can call it like this :
changeBackgroundImage(".tile","url(tile.jpg)");
The problem is that you´re setting the background-image as an inline stlye that overrides any stylesheet rules. Toggling the class won´t have any affect.
You can either have set the background through a styleheet rule and then add a class that removes it;
#log {
background-image: url(tile.jpg);
}
#log.tile {
background: none;
}
or you could just use !important as;
.tile {
background: none !important;
}
...it might be the other way around but you get the point? :)
try removing class tile and applying new class with bg: none
in effect - when needed apply class with bg, when not needed - without
No need for jQuery in this case. You can use plain old JavaScript. Check out this tutorial:
javascriptkit.com - Changing external style sheets using the DOM
You can't change the class itself without re-writing that declaration in the stylesheet, you ARE working only with the element in the selector.
Try:
$('.tile').css("background-image","none")
$('#log').toggleClass('tile',true);
I would make the background image part of the class as a css style:
.tile {background-image: url('tile.jpg')};
and then remove the class when necessary with jquery
$('#log').removeClass('tile');
you could have two classes in your css...
.tile{
background: none;
}
.tile-w-image
{
background-image: url(tile.jpg);
}
and then with jquery just toggle the classes...
$("#log").toggleClass('tile').toggleClass('tile-w-image');
I'm sure this is just one of many ways of doing this. I hope it helps.
You are very close.
It seems like you are adding inline CSS to your element and then trying to toggle the class. You should keep CSS styling separate in most cases:
HTML:
<div id='log' class='tile'>HELLOWORLD</div>
jQuery (I imagine this should be done on click or another event):
$('#log').toggleClass('tile'); // We still see image
If the "tile" class is already written to the HTML, then toggle-ing it will remove it.
CSS:
.tile{
background-image: url(tile.jpg);
}

Fastest way to do alternating background color on visible HTML table rows

I have a HTML table where I am dynamically adding and hiding rows and I want the current set of visible rows to always show with alternative backcolor for easy reading.
I have the following code that works fine functionally, but is really slow (especially on Internet Explorer browsers)
$('table.alternateRow tr:visible').removeClass('odd').filter(':odd').addClass('odd');
here is my css:
.alternateRow tr {
background-color: #FFFFFF;
}
.alternateRow tr.odd {
background-color: #DEDEDE;
}
Is there any faster solution for this code above that applies to visible rows but doesn't freeze in Internet Explorer. My table has about 150 - 200 rows visible
Also, (for certain reasons) I want to avoid paging if possible (as a last resort) as it makes the report much harder to read
The code in your question iterates over the table rows twice (once to remove the odd class, once to filter the rows), then performs a final pass over the filtered rows to add the odd class.
It might be faster to iterate over the rows only once, using each():
$("table.alternateRow tr:visible").each(function(index) {
var $this = $(this);
if (index & 1) {
$this.addClass("odd");
} else {
$this.removeClass("odd");
}
});
With CSS 3 (IE9) you can do the following
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
Although this will not take into account visibility - it does give you a useful selector (odd/even)
above: Uses CSS doesn't take into account visibility
Edit - added clarification incase someone doesn't read all the way to the end
below: Uses Jquery DOES take into account visibility
With jQuery (which effectively allows IE 8 and lower to support CSS3) you can put the odd/even part straight into your selector...
$('table.alternateRow tr:visible:even').addClass('even');
edit combined into function
function zebra(){
$('table.alternateRow tr').removeClass('even', 'odd');
$('table.alternateRow tr:visible:even').addClass('even');
$('table.alternateRow tr:visible:odd').addClass('odd');
}
This is maybe off topic but have you seen the jquery datatables plugin?
http://www.datatables.net/
It handles this sort of stuff seemlessly
Your selector seems a bit convoluted. Have a look at what I've done here, it's more concise
: http://jsfiddle.net/jomanlk/wTY3p/3/
You basically apply a default and only add the extra class for the even/odd classes.
#table tr {
background:#aa0000;
color:#fff;
}
#table tr.even {
background:#00AA00;
color:#fff;
}
$('#hide').click(function(){
var rows = [3, 4, 5];
for (row in rows) {
$('#table tr:eq(' + row + ')').hide()
}
format()
});
function format() {
$('#table tr.even').removeClass('even');
$('#table tr:even').addClass('even');
}
format()
<button id='hide'>Hide</button>
<table id='table'>
<tbody>
<tr><td>one</td><td>Two</td></tr>
<tr><td>one</td><td>Two</td></tr>
<tr><td>one</td><td>Two</td></tr>
<tr><td>one</td><td>Two</td></tr>
<tr><td>one</td><td>Two</td></tr>
<tr><td>one</td><td>Two</td></tr>
<tr><td>one</td><td>Two</td></tr>
<tr><td>one</td><td>Two</td></tr>
</tbody>
</table>
I don't know jquery so this might be redundant but...
Can't you write your own code that will loop through the rows starting one above (to find out if it is an odd or even row) the highest row made invisible? This means that you won't be looping over all the rows every time a row is hidden or displayed.
As you have shown you've defined CSS this way :
.alternateRow tr {
background-color: #FFFFFF;
}
.alternateRow tr.odd {
background-color: #DEDEDE;
}
When you are adding the rows dynamically you should check whether there are even or odd number of rows and based on that add a tr of the right class, something like this :
$('table.alternateRow').append(function(i,h){
var tr = '<tr';
if ( $(this).children('tr').size() % 2 == 0 )
tr += ' class="odd"';
tr += '></tr>';
return tr;
});
This sounds strange, but it may be much faster to change the background colors of the affected rows instead of the classes. IE8 and below are re-rendering the entire table every time any of the row's classes change, but do not if only the color or background color changes.

Change CSS of class in Javascript?

I've got a class with the display set to none I'd like to in Javascript now set it to inline I'm aware I can do this with an id with getElementById but what's the cleanest way to do it with a class?
You can do that — actually change style rules related to a class — using the styleSheets array (MDN link), but frankly you're probably better off (as changelog said) having a separate style that defines the display: none and then removing that style from elements when you want them no longer hidden.
Do you mean something like this?
var elements = document.getElementsByClassName('hidden-class');
for (var i in elements) {
if (elements.hasOwnProperty(i)) {
elements[i].className = 'show-class';
}
}
Then the CSS
.hidden-class { display: none; }
.show-class { display: inline; }
You can use getElementsByClassName in which you'll get an array of elements. However this is not implemented in older browsers. In those cases getElementsByClassName is undefined so the code has to iterate through elements and check which ones have the desired class name.
For this you should use a javascript framework such as jQuery, mootools, prototype, etc.
In jQuery it could be done with a one-liner as this:
$('.theClassName').css('display', 'inline')
you can create new style rule instead.
var cssStyle = document.createElement('style');
cssStyle.type = 'text/css';
var rules = document.createTextNode(".YOU_CLASS_NAME{display:hidden}");
cssStyle.appendChild(rules);
document.getElementsByTagName("head")[0].appendChild(cssStyle);
$("#YOUR_DOM_ID").addClass("YOUR_CLASS_NAME");
You may like to exploit/rewrite this function:
function getStyleRule(ruleClass, property, cssFile) {
for (var s = 0; s < document.styleSheets.length; s++) {
var sheet = document.styleSheets[s];
if (sheet.href.endsWith(cssFile)) {
var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
if (rules == null) return null;
for (var i = 0; i < rules.length; i++) {
if (rules[i].selectorText == ruleClass) {
return rules[i].style[property];
//or rules[i].style["border"]="2px solid red";
//or rules[i].style["boxShadow"]="4px 4px 4px -2px rgba(0,0,0,0.5)";
}
}
}
}
return null;
}
to scan all style sheets attached pass "" as third argument, otherwise something like "index.css"
ruleClass contains starting '.'
if (rules[i].selectorText && rules[i].selectorText.split(',').indexOf(property) !== -1) condition improvement found here https://stackoverflow.com/a/16966533/881375
don't forget to use javascript syntax over css properties, e.g. box-shadow vs. boxShadow
Although this is long gone, here a few remarks:
Using display: inline to make things visible again may spoil the
page flow. Some elements are displayed inline, others block etc. This
should be preserved. Hence, only define a .hidden style and remove it
to make things visible again.
How to hide: There are (at least) two ways to hide elements, one is
the above mentioned display: none which basically makes the element
behave as if it was not there, and the visibility: hidden which
renders the element invisible but keeps the space it occupies.
Depending on what you want to hide, the visibility may be a better
choice, as other elements will not move when showing/hiding an
element.
Adding/removing classes vs. manipulating CSS rules: The result is
quite different. If you manipulate the CSS rules, all elements having
a certain CSS class are affected - now and in the future, i.e. new
elements dynamically added to the DOM are also hidden, whereas when
you add/remove a class, you must make sure that newly added elements
also have the class added/removed. So, I'd say adding/removing
classes works well for static HTML, whereas manipulating CSS rules
might be a better choice for dynamically created DOM elements.
To change CLASS you need to edit document stylesheets
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.display='inline';
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.display='inline';
.box {
margin: 10px;
padding: 10px;
background: yellow;
display: none
}
<div class="box" >My box 1</div>
<div class="box" >My box 2</div>
<div class="box" >My box 3</div>
Best way to do it is to have a hidden class, like so:
.hidden { display: none; }
After that, there is a className attribute to every element in JavaScript. You can just manipulate that string to remove occurrences of the hidden class and add another one.
One piece of advice: Use jQuery. Makes it easier to deal with that kind of stuff, you can do it like:
$('#element_id').removeClass('hidden').addClass('something');

Categories