jquery wrap, append, prepend to parent div - javascript

I am trying to detect when a certain div element has a height of 0 in order to display a div element with a message.
function checkads()
{
if ($('#container').height() == 0)
{
$('.wp_bannerize').wrap($('<div id="notice">ENABLE ADS</div>'));
};
}
$(document).ready(checkads);
The above works fine, however, is there anyway to make the script wrap the parent div that is 1 or 2 levels above the child div without having to define the class name of the parent manually "wp_bannerize"

You could try something like this:
function checkads() {
var $container = $('#container');
if ($container.height() == 0) {
$container.parent().wrap($('<div id="notice">ENABLE ADS</div>'));
// OR $container.parent().parent().wrap($('<div id="notice">ENABLE ADS</div>'));
}
}
Or change your checkads() function to:
function checkads($current) {
if ($current.height() == 0) {
$current.parent().wrap($('<div id="notice">ENABLE ADS</div>'));
}
}
And call it like:
checkads($('#container');
checkads($('#container2');
//etc...

You can use $('#container').parent().parent() to find the parent of the parent, for example. You can also use $('#container').closest('div') to search through the parent list for the closest div (or whatever). You don't need to know the class name (although you can also use that with closest!)

Related

Compare Elements via jQuery

I'm in a situation where I want to check if two elements (one is clicked and another one a reference) are the same, what I'm trying to do is:
$("#process li").click(function() {
currentElement = $(this);
referenceElement = $("#process li:first-child");
if (currentElement === referenceElement) {
$(".mark").removeClass("mark");
$(this).addClass("mark");
}
});
So what I want is to check if the clicked <li> is the first child of the ul#process and if so first remove a .mark class from another element and then add it to the clicked one. I don't get any working result - ideas anyone?
UPDATE:
Thanks you very much! This is my solution:
$("#processlist li").click(function() {
currentElement = $(this);
if (currentElement.is('li:first-child')) {
$(this).addClass("mark");
}
});
Now if I click on a , if it is the first child of this list, the class .mark is added - sweet!
Comparing objects in JS is very troublesome. The simplest way is to just pick a few key properties and compare those, eg:
if (currentElement.prop('id') === referenceElement.prop('id') {
// rest of your code...
}
However, given your use case you could use is:
if (currentElement.is('#process li:first-child')) {
// rest of your code...
}
Example fiddle
You need to extract the DOM element from the jQuery object. You can use the get method of jQuery for this.
e.g. if( currentElement.get( 0 ) === referenceElement.get( 0 ) )

How to confirm if all elements are hidden

I build a UI interface that show messages and after confirming them they become :"display=none", now i want to check if all the elements are been confirm meaning all hidden. so that my interface wont start.
This is the code:
this is visible:
<li id="announcement4" class="announcement"></li>
this is not visible:
<li id="announcement4" class="announcement" style="display: none"></li>
can i check via the class or type? like
if(all elements type li are hidden)
if(all elements class announcement are hidden)
what is a good way of doing this?
Thanks
Simply use is(':visible')
var allLiHidden = !$('li').is(':visible');
var allClassHidden = !$('.announcement').is(':visible')
FIDDLE
you can do like this:
if($('ul#SomeId').children(':visible').length == 0) {
// all are hidden
}
or:
if($('li.announcement:visible').length == 0) {
// all are hidden
}
Fiddle Example
if($('.announcement:visible').length>0)
{
//something is visible
}
For such a query, you can use the jQuery :visible selector, which gives you only visible elements (everything that Consumes space in the layout) As return.
If you then compare the amount of visible elements with the invisible, you'll see whether one is not visible.
if( $('.announcement').length === $('.announcement:visible').length ){
//all visible
} else{
//not all visible
}
Or
if( $('li').length === $('li:visible').length ){
//all visible
} else{
//not all visible
}

How do I iterate through div's child elements and hide them?

I have a div that have a few elements that I want to hide, on users request. Those elements have a particular background color. The call of the function is working (it is associated to a checkbox) but it just doesnt do what i want. Actually, it does nothing. This is what I've got:
function toogleDisplay()
{
var kiddos= document.getElementById('external-events').childNodes; //my div
for(i=0; i < kiddos.length; i++)
{
var a=kiddos[i];
if (a.style.backgroundColor=="#A2B5CD")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}
What am I doing wrong?
An element's background colour is converted to rgb() (or rgba()) format internally.
But that aside, assuming $ is jQuery (you haven't tagged your question so I don't know!) then a is a jQuery object, which does not have a style property. It looks like you just wanted var a = kiddos[i];.
It is more reliable to use a specific class name instead.
You re wrapping your kiddos[i] in a jquery-object $(kiddos[i]) and then try to access the normal properties of a html-dom-objekt.
You have 2 possibilities:
remove the $()
use jquery-access to the properties
a.css('display', none); // or just a.hide();
Additionally you cant check for '#123456' since the color is transformed. Check (#Niet the Dark Absol)s answer for this
I would suggest adding a class to the elements you want to check. Then instead of trying to use background, you can do
$(kiddos[i]).hasClass('myclass')
or for a very efficient way, you can do it in one line of code.
function toogleDisplay()
{
$('.myclass').toggle(); //this will toggle hide/show
}
The divs would look like this
<div class='myclass'>Content</div>
EDIT - to do it without modifying existing html. I also think the rbg color should be rgb(162, 181, 205) if im not mistaken.
You can try something like this. Its based off the following link
Selecting elements with a certain background color
function toogleDisplay()
{
$('div#external-events').filter(function() {
var match = 'rgb(162, 181, 205)'; // should be your color
return ( $(this).css('background-color') == match );
}).toggle()
}
Your jquery selection of a is causing issues. Unwrap the $() from that and you should be fine.
Also you could end up selecting text nodes that wont have a style property. You should check that the style property exists on the node before trying to access background, display, etc.
Use a class instead of a background and check for that instead.
i think you need to see if the 'nodeType' is an element 'a.nodeType == 1' see Node.nodeType then it will work over multiple lines
var kiddos= document.getElementById('external-events').childNodes; //my div
for(i=0; i < kiddos.length; i++)
{
var a=kiddos[i];
if (a.nodeType == 1){ // Check the node type
if (a.style.backgroundColor=="red")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}
I decided to go for another aproach, using the idea of Kalel Wade. All the elements that may be (or not) hidden, already had a class name, which were the same for all elements, fortunately.
here comes the code
function toogleDisplay()
{
var kiddos = document.getElementsByClassName("external-event ui-draggable");
for (var i = 0, len = kiddos.length; i < len; i++) {
var a=kiddos[i];
if (a.style.backgroundColor==="rgb(162, 181, 205)")
{
if (a.style.display!="none")
{
a.style.display='none';
}
else
{
a.style.display='block';
}
}
}
}

Check if multiple divs are visible at once

I have been using the following code to check if a div is visible:
if ($("#monday").is(':visible')) {
document.getElementById('scheduleitem1').style.width = 540;
$("#scheduleitem1").show();
}
That code worked fine. However I want to check if one of multiple divs are visible at once.
I've tried the following codes which did not work:
if ($("#monday" || "#tuesday").is(':visible')) {
document.getElementById('scheduleitem1').style.width = 540;
$("#scheduleitem1").show();
}
and
if ($("#monday", "#tuesday").is(':visible')) {
document.getElementById('scheduleitem1').style.width = 540;
$("#scheduleitem1").show();
}
So how do I do if I want to check if one of multiple divs are visible at once?
Try this :
$("#monday,#tuesday").is(':visible')
http://api.jquery.com/is/ : "... return true if at least one of these elements matches the given arguments".
Check length of selected elements $("#monday,#tuesday").find(":visible").length == 1
Something like
if ($("#monday,#tuesday").find(":visible").length == 1) {
document.getElementById('scheduleitem1').style.width = 540;
$("#scheduleitem1").show();
}
Try this:
if ($("#monday").is(':visible') || $("#tuesday").is(':visible')) {
$("#scheduleitem1").css('width', '540px').show();
}
I would add a wrapper to all week days and do something like this:
if($("#weekDays").find('div:visible')) {
$("#scheduleitem1").css('width', '540px').show();
}
I'm aware the question states that only one element must be visible.
This answer is for future visitors who want to check if all the elements are visible.
// Assume that the elements are visible
var is_visible = true;
// Select the elements wanted and go through each of them one by one
$("#monday, #tuesday, #etc").each(function() {
// Check that the assumption is true for each element selected
if (!$(this).is(':visible')) {
is_visible = false;
}
});
if (is_visible) {
$("#scheduleitem1").width(540).show();
}
Update, for brevity:
// Check if the elements are not hidden.
if (!$("#monday, #tuesday, #etc").is(':hidden')) {
$("#scheduleitem1").width(540).show();
}

combining a method to hide or show content

I was wondering how I can combine a hide function and show function into 1 toggle Function that either fades in content or fades it out, im guessing this argument would update the fade method:
This is my current effort of JS using jQuery from my object but is totally wrong:
toggleAlertOverlay: function (state) {
var instance = this;
if (state === hide) {
instance.selector.fadeOut();
}
elseif(state === show) {
instance.selector.fadeIn();
}
},
toggleAlertOverlay(hide);
Try using .fadeToggle()
The .fadeToggle() method animates the opacity of the matched elements. When called on a visible element, the element's display style property is set to none once the opacity reaches 0, so the element no longer affects the layout of the page.
$(<element>).fadeToggle();
Where <element> is a valid selector ....
var toggleState = 'none';
toggleAllertOverlay: function()
{
if(toggleState == 'none')
{
$('#element').fadeIn();
toggleState == 'showing';
}
else
{
$('#element').fadeOut();
toggleState == 'none';
}
}
is just a concept based on what you have. Note the variable outside of the function. Its outside so it doesn't get destroyed upon function complete. But aside from that, theres various other methods you can try if this doesn't suit you. Up to and including jQuery toggle()

Categories

Resources