I have an absolutely positioned div that I want to show when the user clicks a link. The onclick of the link calls a js function that sets the display of the div to block (also tried: "", inline, table-cell, inline-table, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari).
I've tried adding alerts before and after the call, and they show that the display has changed from none to block but the div does not display.
I can get the div to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc.
I've tried everything I can think of, including:
Using a different doctype (XHTML 1, HTML 4, etc)
Using visibility visible/hidden instead of display block/none
Using inline javascript instead of a function call
Testing from different machines
Any ideas about what could cause this?
Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript I found that that was the case. Here's the function I ended up using to show the popup:
function openPopup(popupID)
{
var divs = getObjectsByTagAndClass('div','popupDiv');
if (divs != undefined && divs != null)
{
for (var i = 0; i < divs.length; i++)
{
if (divs[i].id == popupID)
divs[i].style.display = 'block';
}
}
}
(utility function getObjectsByTagAndClass not listed)
Ideally I'll find out why the same item is being inserted multiple times, but I don't have control over the rendering platform, just its inputs.
So when debugging issues like this, remember to check for duplicate IDs in the DOM, which can break getElementById.
To everyone who answered, thanks for your help!
Can you provide some markup that reproduce the error?
Your situation must have something to do with your code since I can get this to work on IE, FF3 and Opera 9.5:
function show() {
var d = document.getElementById('testdiv');
d.style.display = 'block';
}
#testdiv {
position: absolute;
height: 20px;
width: 20px;
display: none;
background-color: red;
}
<div id="testdiv"></div>
Click me
Found the answer :
I need to use the following to make it work on both browsers :
document.getElementById('editRow').style.display = '';
Actually I was experiencing the same problem you're describing here. What actually fixed my issue was changing the document properties.
Old DOCTYPE/html spec
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
Replaced with
<html>
Check the error console (Tools Menu > Error Console in Firefox 3) to make sure that there isn't another error happening that you're not seeing, which is stopping your script from working.
Try setting the height and width of the div, and make sure it is on top by setting its z-index higher than everything else. If the absolutely positioned div is inside an element that is relatively positioned, it's top and left location is based off the top and left of the relatively positioned element. Try putting your div just under the body element.
You must write a window.onload method:
window.onload = document.getElementById('testdiv').style.display='inline';
Or you can also make a variable:
var d = document.getElementById('testdiv');
window.onload = d.style.display = 'inline';
There is an annoying display error on Firefox 3.5 but not on IE7 or Firefox 2.0.9
I have 3 DIV's position absolute - the first with plain text; the second with a CSS menu (sucklefish type with UL and LI) and the third ditto. The third will not display at all even though the coding has been checked and found to be perfect with W3C's HTML validator.
As a temporary measure, I have merged the second and third DIV's contents.
Things must be bad at Mozilla when IE7 and FF2 display OK but not FF 3.5
I'll give you a BIG hint:
<div style="..." class="..."> ... </div>
If you have something in style, then document.style will work!
If you have something in class, it will not show up in document.style and class="..." will OVERRIDE it!
Think about this and this will clear up SO MANY ISSUES. Just this one little understanding will RID you of this MIND VIRUS. Have a good day. Cheers, Ron Lentjes, LC CLS.
Related
Update 3 - 10/09/2013: Just tested this with Version 29.0.1547.66 m and the problem still persists. If anyone else can test this out and let me know the results that would be great. You need an inline element such as a span with some text in, have it relatively positioned and moved by however many pixels you want from left and top. Then set up some jScript to change the current inner html of the element to something else and you should see it remain the same in the viewport but change correctly in the DOM.
Update 2: After a bit more testing the problem seems to occur on elements that are inline such as span, or have CSS that makes them inline, but that are also relatively positioned, it seems to be this combination that is causing the issue. After posting the bug on Chromium it has been flagged as a cr-Blink-Rendering issue which looks to be the engine that renders the DOM in the broswer viewport. I am using Version 29.0.1547.57 (the current version ends .66 but mine has not updated due to an error). So if you're on the latest version this issue may no longer be there.
Update: On further investigation I think the problem is with the latest Chrome build Version 29.0.1547.57 m As I tested the element in an inline fashion in IE9 and Firefox 21 and it worked fine. I have filed a bug report for this on chromium
I'm having a problem (that I have not been able to recreate with jsfiddle) where I perform an ajax request, obtain some values and place them within span elements that exist within my page.
I have a very odd problem where the ajax request is working and bringing the values back. The values are being inserted into the span elements via jQuerys .html' method and when I check the DOM using Chrome developer tools I can see the new value in the span.
However, what I see on the page doesn't reflect this, it still shows the old value. Yet if I attempt to highlight the value, it instantly changes to the correct value (the value that is showing in the DOM).
I have even tried to update the spans value before the ajax call (as the value I am using is being obtained from jQuery UI's slider widget) but this still yields the same results.
Has anyone else come across this?
EDIT: Here is some of the code
HTML
<div id="NewLoanSliderAmount" class="NewLoanSliderRules"></div>
<span id="NewLoanSliderAmountDisplay" class="NewLoanDisplay">£600</span>
The slider code. This is the version where I attempt to update it directly from the slider value
$("#NewLoanSliderAmount").slider({
value: amount,
min: 300,
max: amount,
step: 100,
change: function (event, ui) {
$("#NewLoanSliderAmountDisplay").html("£" + ui.value);
window.CkSpace.GetLoanValues();
}
});
Here is the ajax code:
(function (CkSpace, $, undefined) {
CkSpace.GetLoanValues = function () {
var url = "/Home/UpdateAPR";
$.get(url, { Amount: $("#NewLoanSliderAmount").slider("value"), Length: $("#NewLoanSliderLength").slider("value") }, function (data) {
$("#NewLoanAmount").html("£"+data.LoanAdvance);
$("#NewLoanLength").html(data.LoanTerm);
$("#NewLoanMonthlyCost").html("£"+data.LoanInstalment);
$("#NewLoanTotal").html(data.LoanGrossRepyable);
$("#NewLoanAPR").html(data.LoanAPR+"%");
$("#NewLoanSliderAmountDisplay").html("£" + data.LoanAdvance);
});
}
} (window.CkSpace = window.CkSpace || {}, jQuery));
EDIT 2:
Another thing to note is that if i set a break point on the span being populated and step through it, it updates perfectly every time in Chrome developer tools
I've figured out what was causing the problem although I don't know WHY it is causing the problem.
First off I tried changing the span to a div and adding display:inline to the css. It still didn't work.
I then removed the inline display and all of a sudden, as a block level element it works.
If anyone knows more about why this is and can elaborate then please do!
EDIT: On further investigation I think the problem is with the latest Chrome build Version 29.0.1547.57 m As I tested the element in an inline fashion in IE9 and Firefox 21 and it worked fine. I think it's time to file a bug report!
The problem I found is the following:
Situation: I have overall div that has a inline-block display. Inside it are two element that have an inline-block display as well.
Then I add (thanks to JavaScript) a <br/> between the two elements. The second goes to the next line, which is the normal behavior.
Buggy part: The <br/> is then removed (JavaScript again) and... the display doesn't change. It appears that the box of the overall div is not recalculated. In the end I have two similar markup that doesn't appear the same way (which is a bit problematic, isn't it).
It works fine on Firefox (it appears to be webkit based as the Android browser behave the same way). So my question is, is there a workaround that doesn't use methods that will alter the DOM? The library used is jQuery.
A test case here.
EDIT: As suggested by duri, I filled a bug report in webkit bugzilla, it's here. But I'm still looking for a workaround ;)
Way what I found: remove all childs from overall DIV, and then append all except BR's:
function removeBr(){
var ahah=document.getElementById("ahah");
var childs=[],child;
while(child=ahah.firstChild) {
if(!child.tagName||child.tagName.toLowerCase()!=='br')
childs.push(child);
ahah.removeChild(child);
}
for(var i=0;i<childs.length;i++)
ahah.appendChild(childs[i]);
}
http://jsfiddle.net/4yj7U/4/
Other variant:
function removeBr(){
var node=$("#ahah")[0];
node.style.display='inline';
$("#ahah").children("br").remove();
setTimeout(function(){node.style.display='';},0);
}
As a work around, you could set the style to display: block when you want them on individual lines and revert to inline-block when you want them to be friends.
I have created a JS Fiddle example
Which demonstrates this fix:
function addBr(){
$('span').css({ display: 'block'});
}
function removeBr(){
$('span').css({ display: 'inline-block'});
}
$("#add").click(addBr);
$("#remove").click(removeBr);
This bug still exists, so here's another workaround: http://jsfiddle.net/4yj7U/19/
$("span").css('display', 'none');
setTimeout(function(){
$('span').css('display', 'inline-block');
}, 0);
This makes Chrome re-render the spans and displays them properly.
When we run following script under Firefox ...
var d = $("<div class='test'></div>");
d.hide();
$("body").prepend(d);
d.show();
... and look to HTML, this inserted element will have style attribute:
style="display: block;"
Under Webkit, element will have:
style="display: none;"
This scenario in used in a JavaScript component, i develop. This component has a collection of HTML elements in it's internal variables, and inserts they to specified destination container.
Because inserted element having display-property initialized in style attribute, it overrides CSS. This breaks the layout of a page.
As a quick solution, i can store "style" attribute, before element is inserted to the DOM, and, after inserting, write stored version over created one.
Is there any better solution ?
Why this ever happens and how can i check, whether element is not yet inserted to the DOM ?
When I do that with either Chrome or Safari (both WebKit-based browsers), if I inspect the element with the built-in tools, it has no style.display property at all, and so the default div style of display: block is used. (Here's a version with some text in the div, so it's easier to see and to find with the DOM inspector.)
So I suspect the problem lies elsewhere. For instance, is there intervening code that may be failing on WebKit, so that d.show(); never ends up getting called? That would certainly explain it. Easy enough with the built-in tools in Chrome or Safari to set a breakpoint on the code creating the div and walk through it.
Re your question:
...how can i check, whether element is not yet inserted to the DOM ?
That question was asked here on StackOverflow just recently, and one of the answers specific to jQuery was rather elegant:
if (d.closest("body").length == 0) {
// It's not in the DOM yet
}
Update: Re your comment below
Look at this test page with Firefox. The div has "style=display: block;" explicitly defined. Under Webkit, it has empty style attr. I'm using built-in inspector in both Firefox and Safari.
Ah, okay, so the problem isn't a display: none in WebKit browsers (your statement about that in the question led me astray), but rather that Firefox (and possibly other Gecko browsers) end up having display: block on the element.
I'd probably approach this like this:
var d = $("<div class='test'></div>");
d.addClass("hidden");
$("body").prepend(d);
d.removeClass("hidden");
...with this CSS:
.hidden {
display: none;
}
Live copy
That way, you know you won't end up with a style.display property set at all.
Update 2: The other thing you can do is remove the style.display property directly:
var d = $("<div class='test'>Hi there</div>");
d.hide();
$("body").prepend(d);
d.show();
d[0].style.display = "";
Live example
You alluded to effects, so if you're doing fadeIn or something like that, use the callback:
var d = $("<div class='test'>Hi there</div>");
d.hide();
$("body").prepend(d);
d.fadeIn(function() {
this.style.display = "";
});
Live example
How about if you do
var d = $("<div class='test'></div>");
d.hide();
$("body").prepend(d);
d.removeAttr('style'); // this will revert to the original styling
I have a small portion of code which works well on FF but I can't seem to get it to work on Safari unless I put an alert instruction anywhere inside of the whiles.
Anyone knows what may be the problem ?
var liste_ele = document.getElementsByClassName('accordion_content');
i=0;
while(i<liste_ele.length)
{
var j=0;
var liste_sel = liste_ele[i].getElementsByTagName('select');
while(j<liste_sel.length)
{
liste_sel[j].style.visibility = '';
j++;
}
i++;
}
Why don't you try setting visibility to visible instead of ''.
liste_sel[j].style.visibility = 'visible';
And are they really hidden by setting visibility to hidden or are the hidden by display:none that might also make a difference.
If putting an alert in your while loop solves the problem, it's almost certainly a timing issue. Where in the DOM is this code being run? Are you sure it's being run AFTER the elements you're trying to find are created?
A simple test would be to put your code inside a timeout:
window.setTimeout(function(){
// your code here
},100);
If that works, then your issue is related to order of operations; make sure your DOM is created before attempting to access it.
#jitter : I already tried to set visibility to visible, but I didn't have a result so I just tried '', hoping it would help. And yes, my elements are hidden and not undisplayed, otherwise my script wouldn't run perfect on FF.
#jvenema : This looks like a good solution indeed :)
Even though I don't know why would my elements not be created since they are initialised as visibility:hidden by another script in my firmware before I pass on them with this script :/
Anyway thanks, you just solved my problem (well I had solved it the good way, by modifying the script that sets it to hidden but I was curious :p) ! :)
If you don't need to block off the position then use the style display:none. Otherwise hide it initially as Safari will render the page initially with the style visibility:hidden you just won't be able to toggle it with Javascript. As a workaround just toggle the opacity with the javascript;
document.getElementById('Div').style.opacity = 0; to make it disappear
and
document.getElementById('Div').style.opacity = 100; to make it reappear.
Its holding up for me until Safari gets it together.
I'm working on a Javascript-based replacement for a Flash applet. The site is having rendering problems only in IE, where it exhibits a behavior that has me at wit's end.
http://janetalasher.com/new/content/portfolio/artcloth/ (This is the page)
What does IE do that's so strange (in this case only)? If you look in Firefox, you'll see a table of images on the right which has the thumbnails. IE6 and IE7 don't show this... unless you are in print preview. It's not a CSS glitch - I've disabled all stylesheets and the error still occurs. I'd provide more relevant source code, but I don't even know where the problem is. The .js files that I suspect (if it's any help) are:
/common/gallery/display.js
/common/gallery/loader.js
Okay - update: It is definitely rendering properly in print preview mode only. Can someone please explain to me in what world this happens? The div is present in the normal mode, but the table won't render. Using the IE developer toolbar confirms it and all the cells are present.
Try adding semi-colons here:
function loadGallery(xml)
{
thumbpath = $(xml).find("thumbpath").attr('dir') // add here
imagepath = $(xml).find("imagepath").attr('dir') // here
detailpath = $(xml).find("detailpath").attr('dir') // and here
cSheet = contactSheet(xml);
$('.contactSheet')[0].appendChild(cSheet);
display($(cSheet).find('img')[0]);
}
Also, on this line:
jQuery.get('/new/content/portfolio/artcloth/gallery.xml' , 'xml' , function(data) { loadGallery(data); } ) // missing one here too
Actually, your Javascript files are missing semi-colons on the end too. Make sure you go through each file and add one to the end of each line.
Javascript does not actually require them, but for the sake of sanity and knowing exactly what your code is going it is a good idea to put them in. For example:
return
1
Can become:
return;
1;
Which returns nothing at all, not exactly the desired effect.
According to Microsoft Script Editor, there's an error inside jQuery caused by this line:
$('#lower').css('padding-left' , paddingLeft - (lowerRightProtrusion < 0 ? 0 : lowerRightProtrusion) + "px");
Since lowerRightProtrusion is NaN, and NaN < 0 calculates to false, you're actually setting padding-left to "NaNpx". Does not compute ;)
See my previous answer for info about MS Script Editor:
Using the IE8 'Developer Tools' to debug earlier IE versions
It would seem that IE is not picking up the styles. If I open the page in chrome, the "float:left" style appears on the description div. however, in IE this is not the case.
You currently have your includes in a div in the body of the document. If it is possible try moving these into the head. I'm talking about the link and script tags directly descendant of div id="pageHead".
(I am using IE6 and the developer toolbar to get this information)
In /common/css/generic.css:
div#information
{
margin-left:188px;
m\argin-left:94px; <------ not sure if that would cause this, but thought i would point it out
}