Reputation: 9835
I have some code that depends on the css being loaded.
I load css on the header before I load the javascripts on the footer
I tried the javascript with $(document).ready
$(document).ready(function() {
var bar_position, width;
bar_position = $('body').height() - 38;
width = $('body').width();
console.log(bar_position);
if (width <= 480) {
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
I tried $(window).ready
, $(window).load
, but all of them fail.
Upvotes: 0
Views: 7655
Reputation: 2293
The ready event should suffice.
When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
Also, your javascript is invalid. If it is supposed to be CoffeeScript, you are missing ->:
$(document).ready ->
bar_position = $('body').height() - 38 #38 is the size of the bar
width = $('body').width()
console.log(bar_position)
if (width <= 480) #480 is the mobile width
console.log("Entered");
$('#accounts-bar').css("top", bar_position)
return
If it's supposed to be JavaScript, you have more issues:
$(document).ready(function(){
bar_position = $('body').height() - 38; //38 is the size of the bar
width = $('body').width();
console.log(bar_position);
if (width <= 480) //480 is the mobile width {
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
Upvotes: 0
Reputation: 207501
JavaScript comments are not #
, they are //
wrong
bar_position = $('body').height() - 38 #38 is the size of the bar
right
bar_position = $('body').height() - 38 //38 is the size of the bar
And there are a bunch of other errors where that code would not run. Guessing you missed a tag and this is not pure JavaScript since it is indented for block scope and missing braces/closures all over.
Upvotes: 0
Reputation: 5126
With CSS being loaded in the header, JS in the footer, and wrapped in a doc-ready, you should be fine as far as the CSS being applied before the JS code is executed. I'm guessing the reason your element has no width is that it is display: none;
, or contains only floated elements, or something along those lines. In other words - I think this is a CSS issue, not a JS timing issue. Try going into your Firebug/Chrome console, selecting the element in question, and getting its width.
Upvotes: 0
Reputation: 2794
You code is really messed up (unless you are using CoffeeScript.) This is what it should be:
$(function () {
bar_position = $('body').height() - 38; //38 is the size of the bar
width = $('body').width();
console.log(bar_position);
if (width <= 480) { //480 is the mobile width
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
Upvotes: 3