i've created simple code that should set/change image background depending on window width
var backgroundBig = "url(../img/logo1.svg)";
var backgroundSmall = "url(../img/logo2.svg)";
function logoBG(){
var windowWidth = $(window).width();
if (windowWidth < 700){
$("#wrapper1").css({"background-image": backgroundSmall});
} else {
$("#wrapper1").css({"background-image": backgroundBig});
};
};
logoBG();
$(window).resize(logoBG);
as simple as that...
optional background image proprieties are set in css file
#wrapper1{
background-repeat: no-repeat;
background-size: cover;}
everything works fine in website code - when i'm tracking changes by firebug, code changes as it should. however, images don't load, nothing changes regarding website display. what is wrong with that?
thanks in advance
PM
Try this https://jsfiddle.net/2Lzo9vfc/23/
JS
var backgroundBig = "url(http://placehold.it/1980x960)";
var backgroundSmall = "url(http://placehold.it/1980x960/000000)";
function logoBG(){
var windowWidth = $(window).width();
if (windowWidth <= 700){
$("#wrapper1").css("background-image", backgroundSmall);
} else {
$("#wrapper1").css("background-image", backgroundBig);
};
};
logoBG();
$(window).resize(logoBG);
$(document).ready(logoBG);
HTML
<div id="wrapper1">Lorem</div>
Because the images must be loaded FIRST, why it's working with firebug ? it's surely because firebug reload the DOM so he can parse it, and when he do so, the images are already loaded.
I can recommend you jquery.waitForImages because it can even wait for images background, so your JavaScript code is not executed before your images are loaded, and you dont need to Reload the DOM too.
Thank you for all advices. The problem with my code was... the paths to my image files.
url(../img/logo1.svg)
works in css file, that's why I assumed that it's must be correct, but
url(img/logobg.svg)
should be inserted by the jQuery script. What a lame mistake :)
Related
This is essentially a follow up question to this question:
Positioning a div relative to a fixed div with responsive content
So we are on the same page, it might help if you read through that article! :)
Thank you in advance.
I am using the Javascript from the linked article's answer for a separate project where the "color" div is now a "content" div and inside of my content div are roughly 30 images. I'm having no issue getting my "content" div to position correctly with the fixed div now, but the issue I'm having is when I incorporate the Javascript that positions the "content" div, it is calculating and positioning the "content" div AFTER everything in that div is loaded. So essentially the first image is getting hidden under the fixed header until all the images are loaded and then it will position it where it needs to be. I need it to position the "content" div prior to any of the images inside of the "content" div loading.
I have done research trying to figure out how to pick and choose which code gets read first, but all of the things I have tried haven't worked yet. My most recent attempt was putting the JS that positions the "content" div right below the "head" and before the "body" so it is read first, but it still doesn't position the "content" div until everything in it fully loads.
Where am I going wrong?
Here is a JSFiddle with the code: https://jsfiddle.net/8wkotamf/
Here is the Javascript (also in the JSFiddle):
window.addEventListener('load', function() {
var headerHeight = document.getElementById('header').clientHeight;
document.getElementById("content").style.paddingTop = headerHeight + "px";
var footerHeight = document.getElementById('footer').clientHeight;
document.getElementById("content").style.paddingBottom = footerHeight + "px";
}, true);
window.addEventListener('resize', function() {
var headerHeight = document.getElementById('header').clientHeight;
document.getElementById("content").style.paddingTop = headerHeight + "px";
var footerHeight = document.getElementById('footer').clientHeight;
document.getElementById("content").style.paddingBottom = footerHeight + "px";
}, true);
It will be nearly impossible to recreate the issue on the JSFiddle because since the images aren't actually embedded, it loads instantly and you can't tell that the positioning happens after they are all fully loaded. Hopefully all the code will make it an easy fix though! Fingers are crossed!
Thank you guys so much. I appreciate it immensely.
window.addEventListener('load' ... fires when everything in the window has loaded - the HTML document and all content including images. You want your function to run when the document is loaded, ie the DOM is ready, but not necessarily waiting till all other resources such as images are fully loaded.
If you don't need to support IE 8 or lower try document.addEventListener("DOMContentLoaded", function() {... instead. This will fire when the DOM is parsed and ready, not waiting till images etc are loaded. If you do need to support old IE versions use Jquery's $(document).ready().
See window.onload vs $(document).ready() for more information.
My dev site uses lots of Skrollr animation at 1024px resolutions and up. Under 1024px, I don't want the animation to show, so I hid all of the images and whatnot.
However, the javascript that gets called to make the animation work is still getting called on smaller resolutions and causing some issues.
Is there a way to basically say "If the resolution is less than 1024px, ignore these JS files"?
I tried putting them in a DIV and using my existing CSS media queries to "display: none" the DIV on smaller resolutions, but that doesn't work.
FYI, these are the files being called:
<script type="text/javascript" src="/js/skrollr.min.js"></script>
<script type="text/javascript" src="/js/homepageanimation.js"></script>
On top of the jQuery(function($) { in http://workwave.joomlatest01.mms-dev.com//js/homepageanimation.js put something like
jQuery(function($) {
if(screen.width < 1024) {
return;
}
// skrollr stuff....
}
so all the skrollr functions won't be called on screen sizes with a width below 1024px.
The easiest way is too use jQuery..
$(window).width();
plain Javascript:
var w = window.innerWidth;
var ow = window.outerWidth; //toolbars and status, etc...
if(w > 1024) {
//Skrollr
}
from there an small if to trigger the Skrollr event
I would suggest conditionally loading the script. Basically the script only gets loaded if the screen size is greater than 1024.
if(window.innerWidth >= 1024){
var file = document.createElement('script')
file.setAttribute("type","text/javascript")
file.setAttribute("src", "/js/skrollr.min.js")
}
A nice approach here would be to only call the function that initiates the Skrollr functionality at given screen sizes. A real quick Google suggests that Skrollr has a .init() function that gets things rolling.
Without seeing how the JS is set up it's hard to give any solid advice, but here's an idea:
You have a JS file for the page/site that contains a conditional that checks the width of the window before initializing the plugin after the document is ready.
$(document).ready(function() {
if ($(window).width() > 1023) {
skrollr.init();
}
});
jQuery makes this a lot easier too, so it's worth taking advantage of that.
Another option to consider instead of going via window width (which can sometimes be inconsistent with the CSS widths among different browsers) is to test against a CSS rule and whether it is true, so use one you know would be true at a size above 1024px, and this would eliminate any inconsistency.
Within this condition link the JQuery files as demonstrated in other answers.
Really struggling with this one. I'm trying to replace the img src for different window widths (responsive design) and I cant get it to work. It works ok if I use $(window).resize() but that will only change the image src on actual window resizing dragging the browser window back and fourth.
What I cant get it to do is use the desired img src on load regardless of resizing the browser window. I know this is a bit confusing so my code below will explain what I'm trying to do a bit better. Would really appreciate the help on this one!
$(function(){
if($(window).width() >= 0 && $(window).width() <= 400){
$("img").attr("src","small.jpg");
}
else if($(window).width() > 400 && $(window).width() <= 768){
$("img").attr("src","medium.jpg");
}
else{
$("img").attr("src","large.jpg");
}
});
If you already have it working with $(window).resize(), you can try triggering the resize event when the document is loaded.
$(window).trigger('resize');
OK, got this working. The code was right all along i'm just stupid and and didn't FTP my files back to the server!!! Thanks for helping guys really appreciate it.
At least people know how to do this now with out using #media to use different images per screen size!!!!
I have a slight alternative to the original post to change image source because I'm also doing a couple other things on page resize that I didn't want to do using #media.
$(window).resize(function() {
if ($(window).width() > 1130) {
$('#logo').attr("src", "large.jpg");
}
else {
$('#logo').attr("src", "small.jpg");
}
});
Since I have a couple other changes to make on resize (for navigation menu) I can list everything in the if/else.
Sorry in advance if this is a minor question, but I'm new to javascript. I'm writing code for a webpage with full-width color backgrounds. Essentially, what I'm trying to do is detect the height of the window, and then make sure that the color block is the size of the window. The function works well on page load.
The problem is when I shrink the window, the div height doesn't change with the window size. I get all sorts of errors, like graphics poking out from behind the div.
I think what I'm missing is a way to detect the height of the content within each div and resize the height accordingly.
You can see how it works at http://pressshoppr.com
Here's the code:
$(function(){
var windowH = $(window).height();
if(windowH > wrapperH) {
$('.fullWidthSectionBG').css({'height':($(window).height())+'px'});
$('.fullWidthSectionBGFirst').css({'height':($(window).height())-120+'px'});
}
$(window).resize(function(){
var windowH = $(window).height();
var wrapperH = $('.fullWidthSectionBG').height();
var newH = wrapperH + differenceH;
var truecontentH = $('.fullWidthSection').height();
if(windowH > truecontentH) {
$('.fullWidthSectionBG').css('height', (newH)+'px');
$('.fullWidthSectionBGFirst').css('height', (newH)-120+'px');
}
});
});
I am not sure I totally understand the effect you are going for here, but I would imagine that if your initial bit of code achieves it, all you have to do is reuse exactly that. Treat each resize as if the page had just loaded, and get the results you want, eg:
$(function(){
// encapsulate the code that we know WORKS
function init() {
var windowH = $(window).height();
if(windowH > wrapperH) {
$('.fullWidthSectionBG').css({'height':($(window).height())+'px'});
$('.fullWidthSectionBGFirst').css({'height':($(window).height())-120+'px'});
}
}
// call on page ready
init()
// ...and call again whenever the page is resized
$(window).resize(init)
});
How do I go about getting what the height of an element on a page would be if it ignored the 'height' css property applied to it?
The site I'm working on is http://www.wncba.co.uk/results and the actual script I've got so far is:
jQuery(document).ready(function($) {
document.origContentHeight = $("#auto-resize").outerHeight(true);
refreshContentSize(); //run initially
$(window).resize(function() { //run whenever window size changes
refreshContentSize();
});
});
function refreshContentSize()
{
var startPos = $("#auto-resize").position();
var topHeight = startPos.top;
var footerHeight = $("#footer").outerHeight(true);
var viewportHeight = $(window).height();
var spaceForContent = viewportHeight - footerHeight - topHeight;
if (spaceForContent <= document.origContentHeight)
{
var newHeight = document.origContentHeight;
}
else
{
var newHeight = spaceForContent;
}
$("#auto-resize").css('height', newHeight);
return;
}
[ http://www.wncba.co.uk/results/javascript/fill-page.js ]
What I'm trying to do is get the main page content to stretch to fill the window so that the green lines always flow all the way down the page and the 'Valid HTML5' and 'Designed By' messages are never above the bottom of the window. I don't want the footer to stick to the bottom. I just want it to stay there instead of moving up the page if there's not enough content to fill above to fill it. It also must adapt itself accordingly if the browser window size changes.
The script I've got so far works but there's a small issue that I want to fix with it. At the moment if the content on the page changes dynamically (resulting in the page becoming longer or shorter) the script won't detect this. The variable document.origContentHeight will remain set as the old height.
Is there a way of detecting the height of an element (e.g. #auto-resize in the example) and whether or not it has changed ignoring the height that has been set for it in css? I would then use this to update the variable document.origContentHeight and re-run the script.
Thanks.
I don't think there is a way to detect when an element size changed except using a plugin,
$(element).resize(function() //only works when element = window
but why don't you call refreshContentSize function on page changes dynamically?
Look at this jsFiddle DEMO, you will understand what I mean.
Or you can use Jquery-resize-plugin.
I've got it working. I had to rethink it a bit. The solution is on the live site.
The one think I'd like to change if possible is the
setInterval('refreshContentSize()', 500); // in case content size changes
Is there a way of detecting that the table row has changed size without chacking every 500ms. I tried (#content).resize(function() but couldn't to get it to work.