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.
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);
}
});
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.
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.
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);
}
});
$(window).bind("load", function() {
// code here
});
Related
Is there any difference in page speed if you remove elements from displaying with javascript instead of CSS?
If for example I had a lot of content in the sidebar, but wanted to remove it for smaller screens, I would do:
#media screen and (max-width: 1025px) {
.sidebar {
display: none;
}
}
I'm not used to using js, but I found out how to do the same thing with jquery:
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if(width < 1025) {
$(".sidebar").remove();
}
Is there any difference in terms of speed between the two?
CSS will always outperform JS, but there are many things you can do in JS that you cannot in CSS.
Note that your JS example will work only once (unless you add an onresize listener) while the CSS example will always respond to changes.
Next, your JS example removes the element from the DOM, while the CSS only hides it by setting the display property to none (but the element is still present in the DOM and can be restored, unlike the JS example).
The equal JS code would be:
$(window).on('resize', handleWidth);
function handleWidth(){
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if(width < 1025)
$(".sidebar").hide(); // document.getElementById('sidebar').style.display = 'none';
else
$(".sidebar").show(); // document.getElementById('sidebar').style.display = 'block';
};
CSS is best. All content will be loaded either way. Then you have JS happening after!
In the code you provided, the css is hiding the element and the jquery is being deleted.
In vanilla js to hide an element you do this:
document.getElementById("El").style.display = none
The difference between that and css is so minimal it would never make a difference in speed.
This very simple function to calculate the scroll of the page works just fine on jsfiddle, but I can't get it working on my page.
http://jsfiddle.net/SnJXQ/2/
The function is thus:-
jQuery(document).ready(function($) {
$(window).scroll(function() {
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
$('.bar-long').css('width', scrollPercent +"%" );
});
});
Simple, right? Thing is, it never applies the css to the bar-long class div on my local environment, just strange.
So I thought it might be an issue with window scroll function, so I done this:-
jQuery(document).ready(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
$(window).scroll(function() {
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
$('.bar-long').css('width', scrollPercent +"%" );
});
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$("body").addClass("scrolled");
} else {
$("body").removeClass("scrolled");
}
});
});
Second function to test that I wasn't making an utterly stupid mistake, I wasn't, second function works just fine.
I'm running WordPress with their bundled version of jQuery1.11.1, hence the noconflict jQuery qualifier.
I even went as far as to paste in my entire css to jsfiddle along with a copy/pasta of my sites html, worked just fine.
I've disabled other scripts on the site, no conflict with those, no errors in console.
Just confused, really confused.
EDIT:- After some console logging;
console.log($(window).height());
console.log($(document).height());
console.log ($(document).height() - $(window).height());
=
5541
5541
0
So it thinks the window height and the document height are the same, which they are not. Hrmm.
I solved it.
Holy Christ almighty, it was because chrome gets confused with doctypes and thinks window/document height are the same if you mess that up, I was using this:
<!DOCTYPE html <?php language_attributes(); ?>>, I removed the php from it and now it works just fine.
Thanks to everyone that helped anyway. A good FYI, doctypes are important.
Based on your comment, it sounds like your code is trying to divide by zero.
If $(document).height() - $(window).height() is 0, you're doing 100 * $(window).scrollTop() / 0, which according to my firefox console comes out as Infinity.
You can't really set width: Infinity%; on an element, so check first! Something like this:
// Avoid a divide by zero error
var docHeight = $(document).height() - $(window).height();
if (docHeight < 1) {
docHeight = $(document).height();
}
var scrollPercent = 100 * $(window).scrollTop() / docHeight);
It's likely an overriding style
Try changing the class or enhancing the specificity of your selector $('.parent-div .bar-long'), etc.
Also, inspect the computed styles in your dev tools (Chrome inspector, Firebug, etc.) to see what styles in the cascade are being applied or overridden.
So I am currently working on a one page site with a responsive layout. On smaller screens I am using an animated scroll plugin to navigate between the content divs, but on larger screens I am using a plugin to simply toggle the visibility of these divs.
The issue that I am having is that I need the script to change if the window is resized after the page has been loaded. I thought that $(window).resize would do the trick but it doesn't seem to be working and continues to use the script that was initially loaded rather than executing the proper script. .anchorAnimate and .anchorTog are the plugins that I am using but I do not think that they are the problem here. I can post if necessary.
Code:
$(document).ready(function() {
var w = $(window).width();
if(w <= 767) {
$('a.anchorLink').anchorAnimate();
}
if(w >= 768) {
$('a.anchorLink').anchorTog();
}
$(window).resize(function(){
if(w <= 767) {
$('a.anchorLink').anchorAnimate();
}
if(w >= 768) {
$('a.anchorLink').anchorTog();
}
});
});
in your code, the variable "w" is out of scope for the resize function. "w" will only ever be the window width when the document has reached it's ready state. To fix this, you can redeclare the variable in your resize function so that every time we get a resize, we check the width:
$(window).resize(function(){
var w = $(window).width();
if(w <= 767) {
$('a.anchorLink').anchorAnimate();
}
if(w >= 768) {
$('a.anchorLink').anchorTog();
}
});
Responsive design usually implies CSS, not JavaScript.
In CSS3 you can define the dimensions of the screen-size you want to support using #media.
If you use CSS you can have hardware accelerated animations, which are much smoother than anything you could do in JavaScript.
Google for "responsive design css3" and you'll get many examples.
The following code crashes IE6 every time. It keeps refreshing the page and crashes after a minute:
$(window).bind("load resize", function () {
var hnf = $('#header').height() + $('#footer').height();
$('#main').height($(window).height() - (hnf));
$('.fluid').height($('#main').outerHeight());
$('#content').width($('#main').width() - $("#aside").width() - 90);
});
..whats causing it?
EDIT: Okay the "resize" in $(window).bind("load resize", function () { is causing it, how do I fix?
Many thanks for your help!
It looks as though IE6 incorrectly fires the onResize event even when the document body dimensions change. Here's a link with more information.
I would look for a non-jQuery way to do what you want. If you use CSS to control the fixed-size elements of your page, won't the browser take care of the variable-size elements on its own?
The fix Drew Wills links to sounds like it should work. Try:
var prevHeight;
$(window).bind("load resize", function () {
var height = $(window).height();
if ( prevHeight == height )
return; // hack to prevent recursion in IE6
prevHeight = height;
// resize content
var hnf = $('#header').height() + $('#footer').height();
$('#main').height(height - (hnf));
$('.fluid').height($('#main').outerHeight());
$('#content').width($('#main').width() - $("#aside").width() - 90);
});
Feel free to pretty that up a bit (attach prevHeight to something else, etc).
I think it might have to do with the fact that you are trying to set the height and width without CSS. I am not sure but if I was going to do it I would use the JQUERY .css() method to set he height and width. so it would look like this,
$(window).bind("load resize", function () {
var hnf = $('#header').height() + $('#footer').height();
$('#main').css("height", ($(window).height() - hnf));
$('.fluid').css("height", ($('#main').outerHeight()));
$('#content').css("width", ($('#main').width() - $("#aside").width() - 90));
});
This might not work I did not test it.
I know that the title is very subtle but I have absolutely no idea how I should title this issue nor what the hell is happening with this function.
function update_background(source, isSystem){
if (!isSystem) {
source.replace(/\/tn_/, '');
jQuery('div#drag_container img[alt="background"]').attr('src', source); //*1
jQuery('div#drag_container img[alt="background"]').attr('style', '');
var height = jQuery('div#drag_container img[alt="background"]').height();
var width = jQuery('div#drag_container img[alt="background"]').width();
var ratio = Storyboard['format'];
//Don't touch the paddings, they are correct!
if (height * ratio > width) {
var padding = (Storyboard['display'] - (width * (Storyboard['height'] / height))) / 2;
jQuery('div#drag_container img[alt="background"]').css({
'height': Storyboard['height'],
'padding-left': padding
});
} else {
var padding = (Storyboard['height'] - (height * (Storyboard['display'] / width))) / 2;
jQuery('div#drag_container img[alt="background"]').css({
'width': Storyboard['display'],
'padding-top': padding,
'padding-bottom': padding
});
}
} else {
jQuery('div#drag_container img[alt="background"]').attr('src', source).attr('style', '');
jQuery('div#drag_container img[alt="background"]').css({
'width': Storyboard['display'],
'height': Storyboard['height']
});
}
}
What this function is supposed to do, is take a picture, get the size of it, compare it to the the size of the container it will be shown in, resize it so that it is as big as possible without sticking out of the container and then finally, apply padding where needed to center the image. It does not matter if the picture is landscape or portrait, the function knows exactly what to do. The picture is cached so that we don't get wrong values (I already had a bug like that). In case it is a System Background, we don't care for correct size and padding. Worked flawless for 3 months.
Lately, it is behaving rather odd. At the line with the comment *1, it does not only reset the src attribute of the img-tag, but it also sets a height and a padding, as if it already were in the padding calculations. They are removed again on the next line (which wasn't actually inserted for that purpose but was inserted to get the original dimensions of a picture) and it still works.
Unless, of course, you let the function run at regular speed, where it does not reset the style. I am quite irritated by this Bug as I have no idea where to start searching.
The function is only called once. It only runs once through the function. It is not included in an event and this function is called in 2 totally different places.
Any ideas?
Edit 1
I have found out that the Bug does not occur in every Browser.
Mac OS X Snow Leopard
Firefox: behavior as described
Opera: does it all wrong, but is not supported by our company
Safari: Still works flawless
Windows XP
Chrome: Works same as Safari
Firefox: Behavior as described
IE8: Same Behavior
IE7: Actually Works!
Linux
Firefox: Behavior as described
Konqueror: does not even work with my JavaScript
You might be having problems getting the size of the image because it isn't guaranteed that it has been loaded by the time you're checking its dimensions.
var $img = jQuery('div#drag_container img[alt="background"]');
$img.bind('load', function(){
// do all of your stuff with the width and the height of the image in here...
var width = $(this).width();
var height = $(this).height();
});
$img.attr('src', source); /* kicks off the loading of the image, the bound function
* above will get called when it's done.
*/