Hide a whole div with CSS with part of it is empty - css

Is there a way to hide a whole div if part of it is empty? For example if "dd" is empty as shown below can I hide the whole class "test" so the keyword Restrictions does not show either. I tried .test dd:empty { display: none; } but this does not work. thanks!
<div class="test"><dt>Restrictions:</dt>
<dd></dd></div>

I don't think there's any easy way to do what you're talking about with just CSS. Better to test it server-side if you can. But if you can't here's some JS that will do the job.
<script type="text/javascript">
// handles multiple dt/dd pairs per div and hides them each conditionally
function hideIfEmpty() {
// get all the elements with class test
var els = document.getElementsByTagName('dl');
// for every 'test' div we find, go through and hide the appropriate elements
Array.prototype.map.call(els, function(el) {
var children = el.childNodes;
var ddEmpty = false;
for(var i = children.length - 1; i >= 0; i--) {
if(children[i].tagName === 'DD' && !children[i].innerHTML.trim()) {
ddEmpty = true;
} else if(children[i].tagName === 'DT') {
if(ddEmpty) {
children[i].style.display = 'none';
}
// reset the flag
ddEmpty = false;
}
}
});
}
window.addEventListener('load', hideIfEmpty);
</script>
<div class="test">
<div style="clear: both;"></div>
<dl>
<dt>Restrictions:</dt>
<dd></dd>
<dt>Other Restrictions:</dt>
<dd>Since I have content, I won't be hidden.</dd>
</dl>
</div>
Just a fair warning: the code uses some functions that may not exist in older IE, such as Array.prototype.map, String.prototype.trim, and addEventListener. There are polyfills available for these and you could also write your own pretty easily (or just do it with a for loop instead).

CSS alone can't do that. Either, you need a javascript to retrieve empty elements and hide their parents, or your CMS applies special CSS classes if there's no content.
Put as an answer as requested by #Barett.

You could update your CSS to be
.test{
display: none;
color: transparent;
}
This would make the text transparent too, but display:none should hide it anyway.
To make the div with the id test ONLY show when the dd tag is EMPTY, and you can use jQuery, try the following JavaScript along with the CSS:
if($("dd").html().length ==0)
{show();
}
Note: this solution requires jQuery, which is a JavaScript library.

Related

Anyone have solutions for table>th with position:sticky not working on FF & IE?

I have an idea to make sticky header of table and I have tried with position:sticky. It's
working fine on Chrome but on Firefox and IE not working as I think. Below is my CSS
.myTable--mof thead th {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index:100;
}
position:sticky is not supported for child table elements in some browsers. The 'why' I don't know.. Will it be supported in the future? I sure hope so!
I recently wrote this jQuery solution. It'll work for simple tables with simple headers. Does not look for colspans or multiple rows in thead!
I tried some plugins before, but they all listened for the scroll event which throws alerts in some browsers. They caused flickering/jumping in some cases, and a delay was noticable when hitting the position to stick at.
Using position:sticky for other elements and liking those transitions more, I came up with the following piece of code.
jQuery.fn.stickTableHeaders = function() {
return this.each(function()
{
var table = $(this),
header = table.find('thead'),
sticked = $('<table></table>').addClass('table').append(header.clone()); // Needs to be wrapped in new table since table child elements can't be sticky? (FF)
sticked.find('th').css({ // You'll have to copy the original thead (th's) CSS manualy
'backgroundColor': '#DEE5EA',
'color': '#606060',
'padding':'8px',
'color':'#606060'
}).removeAttr('width'); // And remove the width attr from the clone th's since we'll be setting them again later
sticked.find('th:not(:last-child)').css({ // More CSS
'borderRight': '1px solid #ddd'
});
sticked.find('a').css({ // More CSS
'color':'#606060'
});
// I tried different things, most of the original th's should have a width attribute set (not in CSS and avoid percent) for best results
$(window).resize(function() {
sticked.width(table.width());
sticked.find('th').each(function() {
var headerTH = header.find('th').eq($(this).index());
if(headerTH.is('[width]') || headerTH.is(':first-child') || headerTH.is(':last-child')) { // First and last th are allready calculated by another function in my app. See what suits for you here...
$(this).width(header.find('th').eq($(this).index()).width());
}
else {
var cellWidth = header.find('th').eq($(this).index()).width(true),
tableWidth = table.width(true),
percent = 100*(cellWidth/tableWidth);
$(this).css({'width':percent+'%'});
}
});
// We keep the original thead to avoid table collapsing, we just slide the whole table up.
table.css({
'marginTop':-header.height()
});
}).trigger('resize');
// Apply stickyness
sticked.css({
'display':'table',
'position':'sticky',
'top':$('#header-menu').height(), // My sticky nav is my top position, adjust this to your needs
'zIndex':'10'
});
// Insert clone before original table
$(this).before(sticked);
});
};
Now I just use this on each page load:
$("table").stickTableHeaders();
You might want to filter out nested tables from the above selector...
Hope this helps someone.

Using adjacent sibling CSS combinator (+) with HgClass and dynamic value

I'm just trying to figure out if this is possible or if I need to rethink the way I'm going about things.
Here's a very simple idea of where I'm at
My main list will be constantly having items added and removed by other processes. I use NgFor to generate my items and I'm using the adjacent sibling combinator in my style sheet (+) to add margin-top to all but the first item, then ngClass to apply the class itself.All god so far...
Now I want the value of margin-top to also be dynamic and linked to value coming in from another service.
So my question is just, can anyone give me a way of using the adjacent sibling selector and a dynamic value for the style it applies?
Since rendered CSS won't do variables cross browser yet, one option would be a small script adding a style like this
window.addEventListener('load', function() {
loadStyle(20);
setTimeout(function() { loadStyle(40); }, 1000);
setTimeout(function() { loadStyle(60); }, 2000);
})
function loadStyle(margin) {
var node = document.querySelector('my-app style') || document.createElement("style");
var css = ".my-item+.my-item{margin-top: "+margin+"px;}"
node.type = 'text/css';
if (node.styleSheet){
node.styleSheet.cssText = css;
} else {
node.appendChild(document.createTextNode(css));
}
document.querySelector('my-app').appendChild(node);
}
.my-item{
background-color: red;
}
.my-item+.my-item{
margin-top: 20px;
}
<my-app>
<div class='my-item'>A</div>
<div class='my-item'>B</div>
<div class='my-item'>C</div>
</my-app>
You can use style:
<div *ngFor="let user of userList" [ngClass]="'my-item'" [style.margin]="marginValue">{{user}}</div>
marginValue = '0 0 0 9px';

dynamic stylesheet with angularjs

I have and angularjs application that fetches data via api, and builds a webpage with it.
Usually I use ng-style to create dynamic styling, but now I have to use the nth-of-type attribute that can only be used in a css stylesheet (I cannot use individual styling since the number and order of elements always change).
I have tried this naive code (in the html page):
<style ng-if="styles.sc && styles.sc.length==3">
a.mosection:nth-of-type(3n) > div {
background-color: {{styles.sc[0]}} !important;
}
a.mosection:nth-of-type(3n+1) > div {
background-color: {{styles.sc[1]}} !important;
}
a.mosection:nth-of-type(3n+2) > div {
background-color: {{styles.sc[2]}} !important;
}
</style>
But it didn't work... Apparently angular doesn't bind the data inside the style tag (the ng-if attribute does get digested properly)
Does anyone have any idea how this can be done?
Thanks!
You should checkout those three ng-*
https://docs.angularjs.org/api/ng/directive/ngClass
https://docs.angularjs.org/api/ng/directive/ngClassOdd
https://docs.angularjs.org/api/ng/directive/ngClassEven
all of them can accept functions as attributes, you can also checkout
https://docs.angularjs.org/api/ng/directive/ngStyle
which might be actually the best in your case
Thanks!
I indeed solved it by using ng-style with a function
The HTML
<div class="widget widget-people" ng-style="{backgroundColor: staggerBgColors('widget', 'widget-people', '#333333')}"></div>
<div class="widget widget-property" ng-style="{backgroundColor: staggerBgColors('widget', 'widget-property', '#24d10f')}"></div>
The scope function
$scope.staggerBgColors = function(elesClass, eleClass, defaultColor){
if (!$scope.styles || !$scope.styles.sc || $scope.styles.sc.length!=3){
return defaultColor;
}else{
var listItem = $('.'+eleClass);
var n = $('.'+elesClass).index( listItem ) % 3;
return '#' + $scope.preview.moment.sc[n];
}
}
I had to implement the same functionality of the css property "nth-of-type" using jQuery, but it works prefectly!

Is there a CSS "haschildren" selector? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a CSS parent selector?
Is there a css selector I can use only if a child element exists?
Consider:
<div> <ul> <li></li> </ul> </div>
I would like to apply display:none to div only if it doesn't have at least one child <li> element.
Any selector I can use do this?
Sort of, with :empty but it's limited.
Example: http://jsfiddle.net/Ky4dA/3/
Even text nodes will cause the parent to not be deemed empty, so a UL inside the DIV would keep the DIV from being matched.
<h1>Original</h1>
<div><ul><li>An item</li></ul></div>
<h1>No Children - Match</h1>
<div></div>
<h1>Has a Child - No Match</h1>
<div><ul></ul></div>
<h1>Has Text - No Match</h1>
<div>text</div>
DIV {
background-color: red;
height: 20px;
}
DIV:empty {
background-color: green;
}
Reference: http://www.w3.org/TR/selectors/#empty-pseudo
If you go the script route:
// pure JS solution
​var divs = document.getElementsByTagName("div");
for( var i = 0; i < divs.length; i++ ){
if( divs[i].childNodes.length == 0 ){ // or whatever condition makes sense
divs[i].style.display = "none";
}
}​
Of course, jQuery makes a task like this easier, but this one task isn't sufficient justification to include a whole libary.
Nope, unfortunately that's not possible with CSS selectors.
CSS does not (yet) have any parent rules unfortunately, the only way around it if you must apply it only parents that contain a specific child is with the Javascript, or more easily with a library of javascript called jQuery.
Javascript can be written in a similair way to CSS in someways, for your example we would do something like this at the bottom of our HTML page:
<script type="text/javascript">
$('div:has(ul li)').css("color","red");
</script>
(For this you would need to include the jQuery library in your document, simply by putting the following in your <head></head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
If you use jquery, you can try out this function
jQuery.fn.not_exists = function(){
return this.length <= 0;
}
if ($("div#ID > li").not_exists()) {
// Do something
}
There is another option
$('div ul').each(function(x,r) {
if ($(r).find('li').length < 1){
$(r).css('display','block'); // set display none
}
})

Applying Events Handler to Child Elements (Event Propogation in jQuery)

Edit : Problem wasn't related Event Propagation, if you want to know how to stop propagation in jQuery, then use event.stopPropagation();
When user moves his/her mouse over <span> element my jQuery code appends an <img>into this <span> element and when he moves out his mouse off <span> than the element appended is removed. It helps people to edit the field when clicking on the appended <img> element.
The reason I used append() method to add <img> into <span> is because I want to keep <img> element visible when user moves his mouse over to appended <img> element (<img> is becoming <span>'s child element) But it didn't happen and when user moves his mouse over it <img> is being deleted. I am thinking it is because event propagation but I couldn't find how to activate it in jQuery as we do with addEventListener in Firefox based browsers.
Here is the code :
JQuery Code :
$(document).ready(function() {
$('.EditEnabled').bind("mouseover", ShowEditFields);
$(".EditEnabled").bind("mouseout", HideEditFields);
});
function ShowEditFields(event) {
$(event.target).append(" <img id='editImg' src='images/edit.png' style='margin-bottom:-3px'/>");
}
function HideEditFields(event) {
$(event.target).children("#editImg").remove();
}
Simple HTML :
<span id="something" class="EditEnabled">Something Here</span>
Can you explain my how to solve it.
Thank you.
You want to use the jQuery mouseenter and mouseleave events, not mousover and mouseout. The reason is that mouseout will fire when you move the mouse over the img.
Thankfully, jQuery combines this into a hover method:
$(document).ready(function() {
$('.EditEnabled').hover(ShowEditFields, HideEditFields);
});
However I agree with the other answer that you should use CSS to do this vs. manipulating the DOM. I would just use the :hover pseudo selector, and then add special support for IE6.
CSS
span.EditEnabled img { display: none }
span.EditEnabled:hover img,
span.EditEnabled.hover img { display: block }
Make sure you have the img in the span in your HTML to begin with, and that is all you need for most browsers and IE7+
To support IE6 add:
<!--[if lte IE 6]>
<script type="text/javascript">
$(function(){
$(".EditEnabled").hover(
function(){ $(this).addClass('hover') },
function(){ $(this).removeClass('hover')}
);
});
</script>
<![endif]-->
Firstly, I would avoid as much DOM manipulation as you can. The ideal scenario is to construct your markup like this:
<span class="editEnabled">Some data<img ...></span>
with CSS:
span.editEnabled img { display: none; }
span.editEnabled img.visible { display: inline; }
and Javascript:
$(function() {
$("span.editEnabled").hover(function() {
$(this).children("img").addClass("visible");
}, function() {
$(this).children("img").removeClass("visible");
});
});
That should pretty much do it.
I would avoid the jQuery effects as making things visible will make them block level elements rather than inline like you want.
I've found another answer actually, the way I am looking for. It might not be a best practice but at least I've found out how to solve that.
$(document).ready(function() {
// $('.EditEnabled').bind("mouseenter", ShowEditFields);
// $(".EditEnabled").bind("mouseleave", HideEditFields);
$(".EditEnabled").hover(ShowEditFields, HideEditFields);
});
function ShowEditFields(event) {
var target = $(event.target);
if (target.is(":has(#editImg)") == false)
target.append(" <img id='editImg' src='images/edit.png' style='margin-bottom:-3px;display:inline'></img>");
}
function HideEditFields(event) {
// event.stopPropagation();
// if ($(event.relatedTarget).is("#editImg") == false)
$(event.target).children("#editImg").remove();
}

Resources