javascript - check if a div is empty - javascript

I have the following setup:
<div id="whatever">
<!-- Here some dynamic divs will be loaded -->
</div>
I need to know when the "whateverdiv" has nothing inside. The catch is that when I say nothing I mean if user sees nothing. So if inside the div something like
<div style="display: none">LOOOONG TEXT</div>
is loaded I consider it empty.
If is full of blank spaces is also empty, etc... if user doesn't see anything in it is empty.
Since there are too many cases to cover (content with height 0, content with display none, blank spaces, tabs, hidden inputs etc... almost anything may be loaded there depending on situations) I tried to use the height attribute to see if has content (the div expands depending on content). This idea worked ok but now I have another problem: I must add display: none on it sometimes. When I do that the height is always load as 0. I can't use visibility because div has 10px padding that I don't want to see when is not shown. So I'm back to square one... finding some sort of way to see if a div is empty in all that cases.
Any idea how should I do that?

var d = $('#myDiv');
var empty = d.text().trim().length === 0 || !d.is(':visible');

This one should work.
http://jsfiddle.net/fedmich/SmRnT/
I'm cleaning the html comments via Regex
$(function() {
var w = $('#whatever').clone();
w.find(':hidden').remove();
var html = w.html();
html = html.replace(/<!--.*-->/g,'')
html = $.trim(html);
alert( html );
});​
To summarize
clone the object
remove hidden elements
remove html comments
$.trim( )

If you dont count whitespace as if something is not empty:
$("selector").is(":empty")
OR
$("selector").contens().length
Does the trick.
If you dont want to count text nodes as empty:
$("selector").children().length
See:
http://api.jquery.com/empty-selector/
http://api.jquery.com/contents/
http://api.jquery.com/children/

Related

Accessibility JS Function "Role" Attribute

I'm trying to write a JS function that would give empty heading elements (h1, and h2...)a “role” attribute value of “presentation”.
This is my first time working with accessibility in my projects and would love some help!
If they're empty, do they need to be there at all? The most correct thing is just to remove them.
However, you can use document.querySelectorAll() to get all the headings, then look inside each one to see whether they are empty. If they are, you can set the role attribute. The following code is very quick and dirty, but will get you some of the way.
var headings = document.querySelectorAll("h1,h2,h3,h4,h5,h6");
// iterate through each heading
Array.prototype.forEach.call (headings, function (node) {
// remove all white space
var theTextContent = node.textContent.replace(/\s/g,'');
// see if there's anything left in the string
if (theTextContent.length < 1) {
// node contains no visible text, mark it as presentation
node.setAttribute("role", "presentation");
}
} );
BUT this is a risky heuristic. Some headings might not contain text nodes, yet still appear as text on screen (e.g. they may have a background image in CSS representing a text in bitmap form). Instead of adding role="presentation" to these, you absolutely should add an aria-label with the correct heading text, otherwise you'll be violating at least two WCAG success criteria. ("Images of Text" and "Headings and Labels").
If you were using style attributes it might look something like this:
<h1 aria-label="welcome" style="background:url(welcome.png);"></h1>

Hide Element when hover Element Javascript

I have a DIV that needs to be displayed/hide whenever i hover a menu item.
Here it is my website: Website
The Blug light section should be displayed only when I hover the Photo Booths menu on the header.
I have tried the following code on JSFiddle which it works but when i use it on my site it doesn't work
<script>
let test = document.getElementByClassName(".menu-item.menu-item-7912");
test.addEventListener("mouseover", function( event ) {
document.getElementById('test2').style.display = 'none';
});
test.addEventListener("mouseleave", function( event ) {
document.getElementById('mega-menu-customized').style.display = 'block';
});
</script>
I have tried using getElementByClassName but without success. Any ideas of how to make it work?
Are you getting DOM node in test variable, one problem I can see in your code is:
let test = document.getElementsByClassName(".menu-item.menu-item-7912");
Should be:
let test = document.getElementsByClassName("menu-item, menu-item-7912");
We do not use dot before class name and multiple classes can be separated by comma like:
let test = document.getElementsByClassName("class1, class2, class3");
Your issue is in the header element. On scroll, the style property of the document header is changing. Look:
sorry for the bad quality, upload size is maxed at 2MB
Without getting into too much detail, one thing that I see is that the height of the header is being reduced to only contain the main header. When the larger blue subheader is visible, part of that is because the style.height of the header is made to be much larger. Additionally, the first child of the header is a div with id 7905, and that seems to be what you need to target to modify the opacity of the larger blue header. You need to target that div:
const blueBannerContainer = document.getElementById('7905')
But your event handlers will also need to account for the height of the header element. display: block won't really help you here.

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

not able to append html using jQuery (JavaScript)

In this jquery plugin:
http://www.stahs.org.uk/jquery.infinitecarousel.bak
There's this line:
$(obj).append('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-imgHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
Problem is when it dumps the text node in this div, it aligns to the top of the div. I want text to align to bottom of div. So I decided to create another div within this div:
$(obj).append('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-imgHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
console.log($('#textholder'+randID));
$('#textholder'+randID).append('<div style="display:table-cell; height: 94.25px; width: 1000px; vertical-align:bottom;"></div>');
The console outputs this:
[div#textholder35196647.textholder]
[div#textholder62315889.textholder]
[div#textholder95654959.textholder]
However, my above append is not working. The nested div never shows up, so when I later do this:
if(t != null)
{
$('#textholder'+randID+' div').html(t).animate({marginBottom:'0px'},500); // Raise textholder
showminmax();
}
No text becomes visible because the nested div never gets created.
So I am extremely confused. If you look at original plugin, this line works:
$('#textholder'+randID+' div').html(t)
How is it able to target the right div here yet when I append to it right after it's created, it doesn't exist, as you guys suggest?
This doesn't work either:
var $texthold = jQuery('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-imgHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
$(obj).append($texthold);
$texthold.append('<div></div>')
Thanks for response.
It sounds as though perhaps randID has been modified between the $(obj).append... line and your added $('#textholder'+randID)... line. Are you quite sure the value of randID is the same on the two lines?
Are you sure that $(obj) really refers to the element you want to append to? Just in case, you might want to try it the other way round:
$('<div id="textholder'+randID+'" class="textholder" style="position:absolute;'
+'bottom:0px;margin-bottom:'+(-imgHeight*o.textholderHeight)
+'px;left:'+$(obj).css('paddingLeft')+'"></div>'
).appendTo(obj);
It appears this worked:
function showtext(t)
{
if(t != null)
{
if(typeof $('#textholder'+randID).find('div')[0] == 'undefined'){
$('#textholder'+randID).append('<div style="display:table-cell; height: 94.25px; vertical-align:bottom;"></div>');
}
$('#textholder'+randID+' div').html(t);
$('#textholder'+randID).animate({marginBottom:'0px'},500); // Raise textholder
showminmax();
}
}
It's just kind of crazy I had to resort to using typeof to check whether div is declared or not. Why the author of the plugin decided to randomly assign integers as ids of divs is beyond me. By doing that, it appears javascript has difficulty retaining the randomly created id. That's my only explanation for the unusual behavior I could come up with.
Try:
$(obj).after('html');
Documentation is here.

How do I auto-scroll to a specific table row?

I have an html page with a header, a table containing 100 items and a footer.
When there is a search, I highlight the row containing the data.
However, if the highlighted row is row 75, the user has to scroll down to find it.
How can I automatically scroll to that row?
I did see scrollTo() but see it only takes axis points.
Any suggestions?
Thanks.
(Using cgi in C, html, css and javascript/jquery)
You should be able to use scrollIntoView(). (It's on the DOM elements directly.)
Be aware that there are some layout situations where scrolling something on the page can cause IE6 and 7 to decide that random other stuff needs to be scrolled too.
try this:
<script>
function ScrollToElement(theElement){
var selectedPosX = 0;
var selectedPosY = 0;
while(theElement != null){
selectedPosX += theElement.offsetLeft;
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}
window.scrollTo(selectedPosX,selectedPosY);
}
</script>
<body onload="ScrollToElement(document.formName.elementName)">
I think you can do something like this:
Use this line where ever you like,
<a id="bookmark"></a>
and when you start your page, call it like this:
http://mypage.com/setting.php#bookmark
That worked for me without showing the anchor.
Check again for using bookmark in html
EDITED:
Check: JavaScript - Jump to anchor

Categories

Resources