Chrome/Webkit inline-block refresh problem - javascript

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.

Related

Updating visited status of a link when changing its href attribute, under Chrome

When I am updating links with JavaScript
$('#link_id').attr('href', some_new_url)
the color theme for visited/non-visited links persists, regardless of the status of the new url address.
Is there a way to change link address forcing browser to re-check its visited status?
Further notes:
I am (on OSX 10.8) experiencing this problem in Chrome (32) and Safari (6.1). In Firefox (26) the links status gets updated automatically, as desired.
The example above is in jQuery, but the problem is the same way with with vanilla JavaScript, i.e. document.getElementById and setAttribute.
(I would prefer to avoid deleting and adding <a></a>, if possible.)
EDIT:
Minimal (non-)working example (by Joeytje50): http://jsfiddle.net/3pdVW/
Definitive answer
What you could do to fix this, is simply forcing the browser to recalculate the styles by completely removing the href attribute, and then re-adding it back again immediately afterwards. That will make the browser first calculate the styles, since the <a> is no longer a link without the href, and then you add the href you want to give it. The code would then be:
$('#link_id').removeAttr('href').prop('href', some_new_url);
Demo
PS: in this case, using .attr('href', some_new_url); would probably work equally fine.
Previous attempts
What I'm thinking is that this is a rendering glitch. It doesn't recalculate the styles when the :visited state changes because of the script. This minimal example of your problem shows this well. What you could try is either of the following:
Using the element's properties
What the problem might be is that you're changing the attribute, which in turn changes the href property. If you directly change the href property it might work. You can do this via jQuery.prop, which would use the following code to change the link:
$('#link_id').prop('href', some_new_url);
Demo. I don't really have very high hopes about this one, but it's worth trying. What I do suspect will work much better is:
Forcing to recalculate the styles
If you want to force a recalculation of the styles, you can simply change a class on the highest element you want updated. Since you're updating the <a> element alone, you'd need something like this:
$('#link_id').prop('href', some_new_url).toggleClass('webkit-force-recalculate');
Demo
I think that is quite likely to do the trick.
If neither of these approaches work for you, you could of course use maximgladkov's solution.
You can change it like this:
$('#link_id').replaceWith($('' + $('#link_id').text() + ''));
It should do the trick. Tested: http://jsfiddle.net/maximgladkov/L3LMd/
Frequently experience similar issues, e.g. when setting size of elements with border, there are stray borders left etc.
Though this is not directly the same, I have found that hiding the element does the trick. Have not had any trouble with it.
Simple fiddle
$("#change_link").on("click", function(e) {
$("#anchor1").hide();
$("#anchor1").attr('href', $("#url").val());
$("#anchor1").show();
});
This should force a redraw of the element.
I think what you might be looking for is the following CSS code:
a:link {
text-decoration: none;
color: #00F;
}
a:visited {
color: #00F;
}

Firefox - how to get selected text when using double click

I created a contentEditable div with a text portion and a link. Double clicking the link will select the link text.
<div contentEditable="true">
This is a text and This_is_a_link
</div>
Afterwards calling document.getSelection().getRangeAt(0).startContainer will return the div:
// => <div contenteditable="true">
Instead of the link. I cannot find a way to find which part of the div is selected.
See this jsfiddle (double click the "This_is_a_link" and there will be a console log with startContainer):
http://jsfiddle.net/UExsS/1/
(Obligatory JS code from the fiddle)
$(function(){
$('a').dblclick(function(e) {
setTimeout(function() {
console.log(window.getSelection().getRangeAt(0));
}, 500);
});
});
Note, that Chrome has the correct behavior, and running the above jsfiddle in Chrome will give textElement for startContainer.
Has anyone run into this issue? did you find a workaround?
Don't think its a bug of Firefox, just a different kind of implementation. When you double click the link, Firefox selects not only the text, but the whole a-tag, so the parent node of the selection is correctly set to the div container.
I added these few lines of code to your fiddle to proof that point:
var linknode = window.getSelection().getRangeAt(0).commonAncestorContainer.childNodes[1];
console.log(linknode);
console.log(window.getSelection().containsNode(linknode, false));
Forked fiddle: http://jsfiddle.net/XZ6vc/
When you run it, you'll see in the javascript console that linknode contains your link, and the check if the link is fully contained in the selection returns true.
This is also one possible solution to the problem, albeit not ideal one. Iterate over all the links in your contenteditable and check if one of them is fully contained in the selection.
Though one word of advice: Don't reinvent the wheel if you don't have to ;-) There's quite possibly some libraries / frameworks out there that fit your needs.

JS : Compatibility problem with Safari

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.

JQuery: Why is hoverIntent not a function here?

I'm modifying some code from a question asked a few months ago, and I keep getting stymied. The bottom line is, I hover over Anchors, which is meant to fade in corresponding divs and also apply a "highlight" class to the Anchor. I can use base JQuery and get "OK" results, but mouse events are making the user experience less than smooth.
I load JQuery 1.3 via Google APIs.
And it seems to work. I can use the built in hover() or mouseover(), and fadeIn() is intact... no JavaScript errors, etc. So, JQuery itself is clearly "loaded". But I was facing a problem that it seemed everyone was recommending hoverIntent to solve.
After loading JQuery, I load the hoverIntent JavaScript. I've triple-checked the path, and even dummy-proofed the path. I just don't see any reasonable way it can be a question of path.
Once the external javascripts are (allegedly) loaded in, I continue with my page's script:
var $old=null;
$(function () {
$("#rollover a").hoverIntent(doSwitch,doNothing)
});
function doNothing() {};
function doSwitch() {
var $this = $(this);
var $index = $this.attr("id").replace(/switch/, ""); //extract the index number of the ID by subtracting the text "switch" from its name
if($old!=null) $old.removeClass("highlight"); //remove the highlight class from the old (previous) switch before adding that class to the next
$this.addClass("highlight"); //adds the class "highlight" to the current switch div
$("#panels div").hide(); //hide the divs inside panels
$("#panel" + $index).fadeIn(300); //show the panel div "panel + number" -- so if switch2 is used, panel2 will be shown
$old = $this; //declare that the current switch div is now "old". When the function is called again, the old highlight can be removed.
};
I get the error:
Error: $("#rollover a").hoverIntent is not a function
If I change to a known-working function like hover (just change ".hoverIntent" to ".hover") it "works" again. I'm sure this is a basic question but I'm a total hack when it comes to this (as you can see by my code).
Now, for all appearances, it SEEMS like either the path is wrong (I've zillion-checked and even put it on an external site with an HTTP link that I double-checked; it's not wrong), or the .js doesn't declare the function. If it's the latter, I must be missing a few lines of code to make the function available, but I couldn't find anything on the author's site. In his source code he uses a $(document).ready, which I also tried to emulate, but maybe I did that wrong, too.
Again, the weird bit is that .hover works fine, .hoverIntent doesn't. I can't figure out why it's not considered a function.
Trying to avoid missing anything... let's see... there are no other JavaScripts being called. This post contains all the Javascript the page uses... I tried doing it as per the author's var config example (hoverIntent is still not a function).
I get the itching feeling I'm just missing one line to declare the function, but I can't for the life of me figure out what it is, or why it's not already declared in the external .js file. Thanks for any insight!
Greg
Update:
The weirdest thing, since I'm on it... and actually, if this gets solved, I might not need hoverIntent solved:
I add an alert to the "doNothing" function and revert back to plain old .hover, just to see what's going on. For 2 of my 5 Anchors, as soon as I hover, doNothing() gets called and I see the alert. For the other 3, doNothing() correctly does NOT get called until mouseout. As you can see, the same function should apply for any Anchor inside of "rollover" div. I don't know why it's being particular.
But:
If I change fadeIn to another effect like slideDown, doNothing() correctly does NOT get called until mouseout.
when using fadeIn, doNothing() doesn't get called in Opera, but seems to get called in pretty much all other browsers.
Is it possible that fadeIn itself is buggy, or is it just that I need to pass it an appropriate callback? I don't know what that callback would be, if so.
Cheers for your long attention spans...
Greg
Hope I didn't waste too many people's time...
As it turns out, the second problem was 2 feet from the screen, too. I suspected it would have to do with the HTML/CSS because it was odd that only 2 out of 5 elements exhibited strange behaviour.
So, checked my code, dug out our friend FireBug, and discovered that I was hovering over another div that overlapped my rollover div. Reason being? In the CSS I had called it .panels instead of .panel, and the classname is .panel. So, it used defaults for the div... ie. 100% width...
Question is answered... "Be more careful"
Matt and Mak forced me to umpteen-check my code and sure enough I reloaded JQuery after loading another plugin and inserting my own code. Since hoverIntent modifies JQuery's hover() in order to work, re-loading JQuery mucked it up.
That solved, logic dictated I re-examine my HTML/CSS in order to investigate my fadeIn() weirdness... and sure enough, I had a typo in a class which caused some havoc.
Dumb dumb dumb... But now I can sleep.

Style display not working in Firefox, Opera, Safari - (IE7 is OK)

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.

Categories