Check if contents of a DIV is only an Image - javascript

I have a div containing initially a loader image tag.
<img src="/images/indicator_big.gif" style="display:block;margin:auto">
I want to check if the DIV contains only the loader image then the function should trigger an Ajax Request.
If i do some thing like div.innerHTML I get it as a string.
What will be the best way to test if the innerHTML is only a loader image?

This method will do what you ask, although I'm not sure the general approach is the best to be honest.
function hasOnlyImg(div) {
if (div.children.length != 1)
return false;
return div.children[0].tagName == "IMG";
}

You can check how many elements are inside your element
var children = document.querySelector("#yourDiv > *");
if (children.length == 1 && children[0].tagName.toLowerCase() == "img") {
//you only have one child in here, and that's an image
}
This will be 1 if it only contains your initial image.
Be wary of the browser support, though: http://www.quirksmode.org/dom/w3c_core.html#t13

I'm assuming your 'style.display' of that loader image will change? You could just check for that?
function checkDiv(div,func) {
var thisDiv = div;
var imgLink = thisDiv.getElementsByTagName("img");
if (imgLink.length == 1 && imgLink[0].style.display !== "block") {
func();
}
}
checkDiv(document.getElementById("mydiv"),function() {
//call ajax code
});
Or if you still would like to check the number of HTML tags within your div, just do something like:
var allDivTags = mydiv.getElementsByTagName("*");
if (allDivTags.length == 1 && allDivTags.nodeName.toLowerCase() == "img") {
//only 1 html element exists in the div, and it's an image.
//run code
}
Hope this helps.

Related

How to convert links to text using JQuery?

I try to think up function which can replace links to text. Image inside a tag should be moved to the wrapper, the original a should be removed.
JS:
var selectors = 'a.mark-video;a.sp5;a>img[alt!=""]'
selectors = selectors.split(";").join(", ");
$(selectors).each(function() {
var current = this;
if (this.nodeName == "IMG") {
current = this.parentNode;
if (current.nodeName != "A")
current = this.parentNode;
if (current.nodeName != "A")
return false;
current = $(current);
}
var wrapper = current.parent();
var new_context = $().append(current.html());
current.remove();
wrapper.append(new_context);
}
);
The problem is
1) that the image is not inserted into the wrapper
2) if it would be inserted it would not have correct position.
I am experimenting using webextensions API (Firefox addon) and I injected the code to site:
http://zpravy.idnes.cz/zahranicni.aspx
In the debugger you can see two wrappers with class="art ". I have removed the first link but image is not inserted. The second one has not been removed yet when debugger was paused after first iteraction.
I hope you can find out why the image is not appended and how to append it to the original position of the element a. I need to find out position of the element a first, and then to move the image into to correct position - that is before div.art-info.
Note: please do not change the selectors string. This is the users input from form field.
Edit:
Almost there:
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).html().replaceWith($(this)); // error: html() result does not have replaceWith...
}
Is this what you're looking for?
https://jsfiddle.net/4tmz92to/
var images = $('a > img');
$.each(images, function(key, image) {
$(this).parent().replaceWith(image);
});
First select all the images that you want to remove the link from, then loop through them and simply replace the parent() with the image.
I have finally solved the problem:
$(selectors).each(
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).replaceWith(
$(this).html()
);
}
);
This works similar. Novocaine suggested not to use $(this).html() but this would skip some images so I prefer to use it.

finding if a particular div is invisible (visible = false) using javascript

using the below code i am finding if a div is invisible.
if(document.getelementbyid("header").style.visible){
alert("Yes");
}
else{
alert("No");
}
checking the visible property because in the code behind header.visible = false is defined depending upon the condition. But it always returning "No". Please tell the correct way.
There isn't a visible property, but visibility, and it can have the following values:
visible
hidden
collapse
See the MDN article.
You can use display and visibility to check if element is visible or not
var elem = document.getelementbyid("header");
if(elem .style.visibility == "hidden" || elem.style.display == 'none'){
alert("No"); // element is visible
}
else{
alert("Yes");
}
Remember that there is not style.visible in javascript. Depending on how do you hide a div, you need to check
if(document.getelementbyid("header").style.visibility != "hidden") {
//visible
} else {
//not visible
}
or
if(document.getelementbyid("header").style.display != "none") {
//visible
} else {
//not visible
}
At the same time, above code will only check if exact element has display none or visibility hidden. But at the same time, it will return visible when parent element is not visible. Because of that, you may do next:
var element = document.getelementbyid("header");
if(element.offsetWidth > 0 || element.offsetHeight > 0) {
//visible
} else {
//not visible
}
Browser always returns 0 width and height of an element if it is not visible
If you're using jQuery:
var isVisible = $("#header").is(":visible");
The CSS property is visibility. Bear in mind that the property may not contain the value you expect if it has been set using CSS, rather than by the style attribute.

How to set preload images to its corresponding place?

I met such a problem recently and do not how to figure it out. I have an HTML image table:
The number of table rows will change dynamically without page refresh according to user input
Each row in the table contains one special image in the database
I want to load image for rows that're displayer (many other rows are hidden so I don't want to load image for them)
I found a snippet like the following:
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img);
}
});
but the problem is that, on the .load method, the image itself will forget where it should be placed (because I use for loop to load the image row by row in the table)
Is there anybody know how to resolve this issue?
You will need to correlate the image with its row. If you have the row at hand when creating the image, you can use it in the callback to .load. For example, if at some point you have a list of new rows, you can do something like this:
var loadImageForRow = function(row) {
var img = $("<img/>").attr('src', 'my-image-source.png')
.load(function() {
if (!this.complete || typeof this.naturalWidth == 'undefined' || this.naturalWidth == 0) {
// handle broken image
} else {
row.find('.image-cell').append(img);
}
});
});
newRows.each(function() { loadImageForRow($(this)); }
This uses the row parameter from the enclosing closure inside the callback. Alternatively, you can correlate the two using data attributes on the image or on the row (e.g. put something like data-row-index='17' on the img element) or any equivalent mechanism.

testing for element tag name

When a user enters a bookmark using form['f3'] (a url and a title) it is immediately entered in via the dom - visually the title and the favicon are seen by the user. Each bookmark is a link and and image under div Bb1c. The insert is done alphabetically. Basically, I need to insert the new image and link after the previous one.
The loop portion was created before I had added in favicons so it loops through all the child elements, but it only needs to loop through the tags. How do I check to make sure that it is an element of type a before doing a compare? My for loop needs an && added to it.
This is rough draft code so if there anything else - contstructive criticism
var a=document.getElementById('Bb1c'),
b=document.createElement('a'),
e=document.createElement('img');
c=document.forms['f3'].elements,
d=a.firstChild,
b.innerHTML=c[1].value;
b.href=c[2].value;
b.name="a1";
b.className="b";
e.src=b.hostname + '/favicon.ico';
e.onerror=function()
{
e.src = 'http://www.archemarks.com/favicon.ico';
}
while(d=d.nextSibling)
{
if(b.innerHTML<d.innerHTML)
{
break;
}
}
a.insertBefore(b,d);
return 1;
}
You want the tagName (or nodeName) property.:
if(ele.id === "foo" && ele.tagName.toLowerCase() === "span") {
// do something
}

How are they doing the accordion style dropdown on the following website?

I was taking a look at http://www.zenfolio.com/zf/features.aspx and I can't figure out how they are doing the accordion style expand and collapse when you click on the orange links. I have been using the Web Developer Toolbar add-on for firefox, but I have not been able to find anything in the source of the page like JavaScript that would be doing the following. If anyone knows how they are doing it, that would be very helpful.
This is actually unrelated, but if all you answers are good, who do I give the answer too?
They're setting the .display CSS property on an internal DIV from 'none' to '', which renders it.
It's a bit tricky, as the JS seems to be in here that's doing it:
http://www.zenfolio.com/zf/script/en-US/mozilla5/windows/5AN2EHZJSZSGS/sitehome.js
But that's basically how everyone does this. It's in there, somewhere.
EDIT: Here it is, it looks like:
//... (bunch of junk)
zf_Features.prototype._entry_onclick = function(e, index)
{
var cellNode = this.dom().getElementsByTagName("H3")[index].parentNode;
while (cellNode.tagName != "TD") cellNode = cellNode.parentNode;
if (this._current != null) this.dom(this._current).className = "desc";
if ("i" + index != this._current)
{
cellNode.className = "desc open";
cellNode.id = this.id + "-i" + index;
this._current = "i" + index;
}
else this._current = null;
zf_frame.recalcLayout();
return false;
};
Basically, what they're doing is a really roundabout and confusing way of making the div inside of TD's with a class "desc" change to the class "desc open", which reveals its contents. So it's a really obtuse roundabout way to do the same thing everyone does (that is, handling onclick to change the display property of a hidden div to non-hidden).
EDIT 2:
lol, while I was trying to format it, others found it too. =) You're faster than I ;)
Using jQuery, this effect can be built very easily:
$('.titleToggle').click(function() {
$(this).next().toggle();
});
If you execute this code on loading the page then it will work with any markup that looks like the following:
<span class="titleToggle">Show me</span>
<div style="display:none">This is hidden</div>
Notice that this code will work for any number of elements, so even for a whole table/list full of those items, the JavaScript code does not have to be repeated or adapted in any way. The tag names (here span and div) don't matter either. Use what best suits you.
It is being done with JavaScript.
When you click a link, the parent td's class changes from 'desc' to 'desc open'. Basically, the expanded text is always there but hidden (display: none;). When it gets the css class of 'open' the text is no longer being hidden (display: block;).
If you look in the sitehome.js and sitehome.css file you can get an idea about how they are doing that.
btw I used FireBug to get that info. Even though there is some feature duplication with Web Developer Toolbar it's worth the install.
They're using javascript. You can do it too:
<div id="feature">
Feature Name
<div id="desc" style=="display:none;">
description here...
</div>
</div>
<script type="text/javascript">
function toggle()
{
var el=document.getElementById('desc');
if (el.style.display=='none')
el.style.display='block'; //show if currently hidden
else
el.style.display='none'; //Hide if currently displayed
}
</script>
The function above can be written using Jquery for smooth fade in/fade out animations when showing/expanding the descriptions. It has also got a SlideUp and Slidedown effect.
There is a lot of obfuscated/minified JS in their master JS include. It looks like they are scraping the DOM looking for H3's and checking for table cells with class desc and then processing the A tags. ( or some other order, possibly ) and then adding the onclick handlers dynamically.
if (this._current != null) this.dom(this._current).className
= "desc"; if ("i" + index != this._current) { cellNode.className = "desc open"; cellNode.id = this.id
+ "-i" + index; this._current = "i" + index; }
http://www.zenfolio.com/zf/script/en-US/safari3/windows/5AN2EHZJSZSGS/sitehome.js
The script is here.
The relevant section seems to be (re-layed out):
// This script seems over-complicated... I wouldn't recommend it!
zf_Features.prototype._init = function()
{
// Get a list of the H3 elements
var nodeList = this.dom().getElementsByTagName("H3");
// For each one...
for (var i = 0; i < nodeList.length; i++)
{
// ... set the onclick to be the function below
var onclick = this.eventHandler(this._entry_onclick, i);
// Get the first <a> within the H3 and do the same
var node = nodeList[i].getElementsByTagName("A")[0];
node.href = "#";
node.onclick = onclick;
// And again for the first <span>
node = nodeList[i].getElementsByTagName("SPAN")[0];
node.onclick = onclick;
}
};
zf_Features.prototype._entry_onclick = function(e, index)
{
// Get the parent node of the cell that was clicked on
var cellNode = this.dom().getElementsByTagName("H3")[index].parentNode;
// Keep going up the DOM tree until we find a <td>
while (cellNode.tagName != "TD")
cellNode = cellNode.parentNode;
// Collapse the currently open section if there is one
if (this._current != null)
this.dom(this._current).className = "desc";
if ("i" + index != this._current)
{
// Open the section we clicked on by changing its class
cellNode.className = "desc open";
cellNode.id = this.id + "-i" + index;
// Record this as the current one so we can close it later
this._current = "i" + index;
}
else
this._current = null;
// ???
zf_frame.recalcLayout();
return false;
};
Edit: added some comments
Unfortunately their code is in-lined and hard to read (http://www.zenfolio.com/zf/script/en-US/mozilla5/windows/5AN2EHZJSZSGS/sitehome.js), but this looks quite simple to implement... something along these lines (using prototypejs):
<script>
var showHide = {
cachedExpandable: null
,init: function() {
var containers = $$(".container");
for(var i=0, clickable; i<containers.length; i++) {
clickable = containers[i].getElementsByClassName("clickable")[0];
Event.observe(clickable, "click", function(e) {
Event.stop(e);
showHide.doIt(containers[i]);
});
}
}
,doIt: function(container) {
if(this.cachedExpandable) this.cachedExpandable.hide();
var expandable = container.getElementsByClassName("expandable")[0];
if(expandable.style.display == "none") {
expandable.show();
} else {
expandable.hide();
}
this.cachedExpandable = expandable;
}
};
window.onload = function() {
showHide.init();
};
</script>
<div class="container">
<div class="clickable">
Storage Space
</div>
<div class="expandable" style="display: none;">
Description for storage space
</div>
</div>
<div class="container">
<div class="clickable">
Galleries
</div>
<div class="expandable" style="display: none;">
Description for galleries
</div>
</div>
Its also caching the earlier expandable element, so it hides it when you click on a new one.

Categories

Resources