I’m trying to change the body background image whenever orientation changes. This seemed pretty easy at first, so I tried this code:
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("orientationchange", onOrientationChange, true);
}
function onOrientationChange(e) {
var orientation = (window.orientation == -90 || window.orientation == 90) ? "landscape" : "portrait";
console.log("orientation: " + orientation);
$("body").css("background-image", "url(images/" + orientation + ".png) no-repeat fixed center top");
}
function onDeviceReady() {
console.log("at onDeviceReady");
onOrientationChange();
}
Every time I change the orientation, I get the correct orientation displayed in the console – meaning my event gets trigrerred properly. But the background does not change, or even initially set (even though I call the handler manually in onDeviceReady – and I see the console output that it was called). Something in the $("body") line just doesn’t work. I tried several combinations of CSS properties and even .css({"backgroundImage" : "..."}), but to no avail.
For the record, there’s a landscape.png and portrait.png in an images folder, in the same directory as the html page.
What am I missing?
Thanks for your time.
Maybe without jQuery?
As @scessor said you can only set the
urlof thebackground-imageproperty, so you should usebackgroundor the otherbackgroundXXXproperties instead.Using classes