I have a partial view that contains an img like so:
<img src="" alt="test" id="chartImage" style="display: none;" />
And then in my view that contains it my javascript looks like this:
if ($(this).val() != '') {
setTimeout(function() {
$('#chartImage').attr("style", "")
}, 1);
}
If I don’t put the timeout the image does not show. However, if I don’t put the timeout and I put an alert prior to setting the attr the image appears. Kinda weird?
If you want to traverse the DOM while the page loads, you have to wait for the page to finish loading and building up the whole DOM tree. Otherwise the Javascript is interpreted immediately as the browser reads in the particular code line (usually in the HTML
<head>) while the desired DOM element (which appears later in<body>) insn’t built up fully yet.You normally hook a function to the
window.onloadevent, but in in jQuery you can hook up thereadyevent to thedocumentto execute something when the document is finished loading/building.