views:

69

answers:

2

I have a to rewrite code written couple of years ago to work with modern browsers. That site includes couple of Javascript files.

In on of them there is a code something like this - it's generating DOM elements dynamically:

createTabs();
createTabsContent();

Now, I'm opening site in Chrome and after page is loaded I try to change some fresh generated element style by

document.getElementById('element').style.display = 'none';

and it's not working - either form script or Chrome console. Yes, element with id #element exists in DOM). What is wierd - Chrome doesn't reporting any errors.

But, when I modify code and do something like that:

alert('test'); //i put alert here 
createTabs();
createTabsContent();
//alert('test'); // or put it here

everything working properly.

In other browsers: IE8, FF, Opera everything works, also no errors. I used jQuery document.ready, then tried with window.onload events - and they failed - nothing changed.

What may cause this behaviour?

+1  A: 

When code "works" after you insert an alert, it usually means that there is some sort of race condition that you are bypassing by having the alert pause execution. For instance, you might have an AJAX request followed by a function call which is supposed to work on the AJAX result (however is called improperly after the AJAX request instead of being passed in to be called by the AJAX handler on completion). Without an alert, the function doesn't have the data yet, so it fails, but when you put an alert in, the request has the time needed to complete and the function succeeds.

It is hard to say for sure what the problem you are experiencing is due to without having more context about your code.

Daniel Vandersluis
I can't paste whole code - whole code, which is needed to generate content is more than 500 lines.
singles
Code, what I mentioned is triggered after AJAX request is complete: readyState == 4 and status = 200 - and that request gives all needed data which is needed to generate content. There is no other AJAX request after that.
singles
+1  A: 

This symptom of something DOM-related not working, but starting to work when an alert is added is usually solvable by deferring the second step:

this.foo();
var me = this;
setTimeout(function() { me.bar(); }, 0); // Whatever library you're using may provide a cleaner way of deferring execution.

IE is especially prone to things not instantly being ready to be interacted with. I haven't really encountered it much with Chrome.

jhurshman
I wrapped all functions in setTimeout and it works (altought I'm not proud of it, but if the code would be written properly at the first time, I wouldn't have to do that, so I have clear conscience:) . Thx!
singles