0

I'm trying to create a dynamic element, apply some css on it from an external css file, and access the properties with jQuery. It works on Firefox but it does not on Chrome.

Here is an example :

CSS file (myFile.css):

.myClass {
    width : 200px;
    font-family : Verdana;
    font-size : 12px;
}

javascript code in a different file (myFile.js):

var title = $("<p/>").attr({id: "myId"}).addClass("myClass").appendTo(content);    
var titW = title.width();
var titFSize = parseInt(title.css("fontSize"));
var titFFamily = title.css("fontFamily");
console.log(titW, titFSize, titFFamily); // Firefox returns good values, Chrome does not

Any ideas? Thanks!

2
  • 1
    Works fine here: jsfiddle.net/nathan/jhky5. What does Chrome return for you? Commented Oct 5, 2011 at 12:23
  • I think the css file is not loading fast enough... If I use a setTimeout with a delay of 100ms, and try to get the properties again, it works. Commented Oct 5, 2011 at 13:12

1 Answer 1

4

Ok, I've got the answer based on your comment. You need to enclose all your jQuery code in a DOMReady event.

jQuery(document).ready(function ($) {
    // jQuery code goes here
});

This ensures that the Document Object Model (DOM) will be fully ready before it runs.

The 100ms delay you mentioned in your comment isn't a good idea, because you don't know that the stylesheet will always load in 100ms.

Sign up to request clarification or add additional context in comments.

1 Comment

That's very strange. The DOM-ready event shouldn't fire until the CSS has loaded. Can you isolate the problem (write the smallest subset of your page which still causes the problem) then share it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.