I am using the .css() jQuery method to change the background of a div with an ID of "background". The method accepts as parameters the property name and the value you want to set for it. Therefore, my code is as follows:
function changeBackground() {
$("#background").css("background-image", "url(../assets/background2.jpg)");
}
window.onload = function() {
window.addEventListener("click", changeBackground);
};
Originally, background-image had a value of url(../assets/background.jpg). The curious thing is that it works fine in the Chrome session that my editor (Brackets.io) uses as Live Preview, but it doesn't when I open Chrome normally or I use Firefox and Opera.
EDIT: The issue was with the path: instead of temporarily changing the value in the css sheet (what I thought the code did), apparently jQuery itself makes sure the background source changes. This means that the path for the image must be set relative to the javascript file—in this case url(assets/background2.jpg) instead of url(../assets/background2.jpg). I'd like anyone more knowledgeable or better spoken to correct me if needed.
However, another issue arose—the rest of the styling for the background image (see below) gets completely ignored after jQuery changed its source. How can you fix this?
#background {
background-image: url(../assets/background.jpg);
background-attachment: fixed;
background-position: center;
background-size: cover;
position: fixed;
top: 0em;
left: 0em;
height: 100%;
width: 100%;
margin: 0em;
}
Use ' instead of " :
$("#background").css("background-image", 'url(../assets/background2.jpg)');
If doesn't work, try this
$("#background").css({backgroundImage : 'url(../assets/background2.jpg)'});
or this
$("#background").css('background', 'url("../assets/background2.jpg")');
add class .new-background
// css
.new-background {
background-image: url(../assets/background2.jpg);
}
and
// js
function changeBackground() {
$("#background").addClass('new-background');
}
$(window).click(changeBackground);
Related
So I'm trying to have the background of my website change when a user does something.
The initial background is set in css:
#container {
height: 100vh;
width: 100%;
position: relative;
background-image: url("'../../gallery/image1.png");
display: flex;
}
So I tried this:
window.getComputedStyle(document.getElementById("container")).getPropertyValue("background-image") = 'url("'../../gallery/image1.png")'
But I get an error saying the property I'm trying to change is read only.
I've tried looking online and the only things I've seen to change the background image does it like this:
document.getElementById("container")).style.backgroundImage = 'url("'../../gallery/image1.png")'
However, the when I try this the backgroundImage is undefined and not the one I set.
Does anyone know if I can change the computed background-image part of the css?
Remove the extra ' and ). This should work:
document.getElementById("container").style.backgroundImage = 'url("../../gallery/image1.png")'
I have a gif that loads once (i.e gif doesn't loop) when a button is clicked. This is used to signify that a user has successfully copied their serial number as shown in this screenshot:
I have set this up using the following code, CSS:
.greentickactive {
visibility: hidden;
}
JS:
<script>
document.getElementById("copyButton2").onclick = function() {
document.getElementById("greentickactive").style.visibility = "visible";
}
</script>
With 'greentickactive' as the gif CSS class and 'copyButton2' representing the trigger for the state change. This is all working, but the gif must be loading when the page loads (I am presuming as I can't see it on load), and I need it to only load when the button (copyButton2) is clicked. I tried replacing;
document.getElementById("greentickactive").style.visibility = "visible";
with
document.getElementById("greentickactive").style.display = "block";
and amending the CSS to;
.greentickactive {
display: none;
}
but this causes spacing issues on the page and still doesn't allow the gif animation to play at the correct time. Does any one know of another method to achieve this or maybe something that's wrong with this setup?
You can defer the loading of the image until copy is clicked, and to handle the spacing issues, just set the height & width of the element.
Assuming you have the following css for .greentickactive:
.greentickactive {
width: 64px;
height: 64px;
display: inline-block;
background-color: transparent;
background-repeat: no-repeat;
}
you can then change your javascript to:
document.getElementById("copyButton2").onclick = function() {
document.getElementById("greentickactive").style.backgroundImage = 'url("/path/to/image/greentick.gif")';
}
Let me know how that works out for you.
I'm working with Bootstrap and I want to put some photos into my div and I want them to be all at the same size ("standardize").
If they're too big (and they will always be) I want to resize them to fit in my div and crop them if necessary.
For the moment her is what I do :
I've tried to change the style of the image in jQuery in a function:
• If the height is bigger than the width, I switch the style to max-width:100% and height auto.
• Inversement if the width is bigger than the height.
But I'm still new to jQuery and I am probably doing something wrong; can someone light my lantern please?
Here is my jQuery
$(document).ready(function(){
photoResize();
$(window).resize(function(){
photoResize();
});
});
function photoResize(){
image_w = $('img').width();
image_h = $('img').height();
if(image_h > image_w)
{
$('img').css("max-width","100%");
$('img').height("auto");
}
else if(image_w > image_h)
{
$('img').css("max-height","100%");
$('img').width("auto");
}
}
And here is a Fiddle for a better view : https://jsfiddle.net/Baldrani/DTcHh/9801/
Simplicity
I do this quite often in the CMS we use at work for galleries etc. The method I use involves a jQuery library called imgLiquid.js.
This will turn an inline image into a background image on the parent div. It's good because you can achieve your desired effect. It will crop the image (as it technically becomes a background image) and will apply background-size: cover; and background-position: center center; as inline styles.
You can find the plugin here
To initialize the plugin you just need:
$(".myele").imgLiquid();
Overheads
The plugin is very small (roughly around 5.106 KB) so you don't need to worry about adding weight to the page. It really it the most simple method I've come across (bar using thumbnails generated from the sever-side - see note at the bottom).
Cue CSS
I've tested this thoroughly and found it gives excellent results. You may then ask... what happens to my parent divs (as technically the plugin hides the img element - which therefore means the parent element doesn't know what height to make itself).
An easy method to make things work responsively, or not:
.myelement:before{
content: "";
padding-top: 50%;
display: block;
}
This CSS will give your heights back to the wrapping element. So if you wanted certain proportions you could use this math:
h / w * 100 = your percentage for the padding-top.
Working Example
Small note
Technically if I had the control I'd advise just using thumbnails.. I assume you're using some sort of system that could technically just render cut down versions of the images? The reason I use this method — and suggested it — is that I don't have control over the CMS and I'm assuming you just want to manage the code that's being produced as it's not stated.
if you want to make your images the same size then you dont need any javascript or calculations, why not just set it in css?
.someUniqueContainer img{
width:300px;
height:300px; // or what ever height you want
}
I'm guessing that in reality you actually want to crop all your images to a set width/height. if that's the case you'll need a serverside script for that.
where are the images coming from? it would be easyer to just edit them. if they are coming from a user then you would resize/crop on the server on file upload
There were several mistakes in your code.
Please look at this jsfiddle, please see https://jsfiddle.net/DTcHh/9796/
$(document).ready(function () {
photoResize();
$(window).resize(function () {
photoResize();
});
});
function photoResize() {
image_w = $('img').width();
image_h = $('img').height();
if (image_h > image_w) {
$('img').css("max-width", "100%");
$('img').height("auto");
} else if (image_w > image_h) {
$('img').css("max-height", "100%");
$('img').width("auto");
}
}
sth like this?, although this is pure css, not jquery included, might not be suit in your case..
body {
margin-top:20px
}
.col-xs-3 {
margin: 5px 0;
width: 500px;
height:120px
}
.col-xs-3 > div {
width: 100%;
height: 120px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
JsFiddle
I am using a widget in my layout and I have it now so when a certain breakpoint is hit it will not display that larger widget and then goes to the smaller one. The larger widget does hide and the smaller one shows up but the text that is associated with both isn't right.
The text for the large widget displays and the smaller text for the small widget doesn't. I am pretty sure it has to do with the scripts each are using. The display none does hide the elements but the scripts seem to be still running.
I have absolutely no clue about JavaScript yet and would prefer a HTML or CSS answer if possible. If not then I will go with JS but will need some direction please. I have read numerous articles and even in the process of learning JS but still not sure how some of what I've read applies.
#media all and (max-width: 900px) {
// styles
}
if (document.documentElement.clientWidth < 900) {
// scripts
}
This is what I've found that seems like it is what I need but I'm not sure on the syntax of how to call the script I need. Do I just put the script itself in there without any other information? I have also read about using jquery to do this with something like this
$(window).resize(function() {
if ($(this).width() > 480) {
// call supersize method
}
});
And I've even read about using Modernizer to do this but I still have to go through the documentation.
In the bin it doesn't show any of the text at all but the larger text is there and off to the side of the small widget. I just need to shut that large script off and turn the other on at a certain media query.
Any help is greatly appreciated.
HTML
<aside class="smallScreen">
<div class="smallWeather" style='width: 200px; height: 440px; background-image:
url(http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/red_500x440_bg.jpg
); background-repeat: no-repeat; background-color: #993333;' ><div
id='NetweatherContainer' style='height: 420px;' ><script src='http://...'></script>
</div></div></aside>
</div></div></div></aside>
<aside class="largeScreen">
<div class="largeWeather" style='width: 500px; height: 440px; background-image:
url(http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/red_500x440_bg.jpg
); background-repeat: no-repeat; background-color: #993333;' ><div
id='NetweatherContainer' style='height: 420px;' ><script src='http://...'></script>
</div></div></aside>
CSS
#media screen and (min-width: 564px) and (max-width: 604px) {
.largeScreen {
display: none;
}
.smallScreen {
display: block;
width: 55%;
min-width: 240px;
height: 100%;
font-size: 0;
margin-left: auto;
margin-right: auto;
margin-bottom: 1.2rem;
}
.smallWeather {
position: relative;
display: block;
width: 240px;
height: 420px;
background: white;
margin-left: auto;
margin-right: auto;
}
What is the best way to do this and why please? Is jQuery the best way from a mobile performance standpoint?
UPDATE: Going to use enquire.js because of it's straightforward approach (although I'm still a bit sketchy on it's use) and how small it is.
This is the basic code:
enquire.register("screen and (max-width: 605px)", {
// OPTIONAL
// If supplied, triggered when a media query matches.
match : function() {},
// OPTIONAL
// If supplied, triggered when the media query transitions
// *from a matched state to an unmatched state*.
unmatch : function() {},
// OPTIONAL
// If supplied, triggered once, when the handler is registered.
setup : function() {},
// OPTIONAL, defaults to false
// If set to true, defers execution of the setup function
// until the first time the media query is matched
deferSetup : true,
// OPTIONAL
// If supplied, triggered when handler is unregistered.
// Place cleanup code here
destroy : function() {}
});
Still not done and looking for more support with this. Now that I've chose this route, I see that there is quite a few articles and questions already about enquire.js. I will update my situation as I read up.
UPDATE: This is where I'm at but it's not working yet. I have the styles associated with each script still in the HTML and display none used accordingly. Will doing this work once I get the enquire.js correct?
Here is the new jsbin
Thanks again for everything!!
I think you are looking for something like enquire.js, which is a lightweight JavaScript library for responding to CSS media queries.
If you don't want to use a library, this post on reacting to media queries in JavaScript runs through a way of doing what you are after with vanilla JavaScript.
Here's a jsFiddle Demo with some working example code, and here's a Fullscreen jsFiddle Demo, which is handy when trying to test how it works. If you use the fullscreen version and make the browser window less than 600px wide, a javascript alert will tell you that you have done so. Because the alert comes up, the browser will jump back to its original size and tell you that it got bigger than 600px again. So you can see, it calls the match function when it matches (so at the time of loading and at the time of resizing to a larger width), and it calls the unmatch function when resizing to a smaller width, because then the media query doesn't match any more. That's how you call a certain function only for mobile or only for desktop based on their screen size.
JS
enquire.register("screen and (min-width:600px)", {
match: function () {
alert("Now the screen width is more than 600px");
},
unmatch: function () {
alert("Now the screen width is less than 600px");
}
});
Okay, let's say you have something like this:
<span class="image" style="background-image: url('http://www.example.com/images/image1.png')"></span>
Every CSS tutorial I've ever read has covered the concept of using a background color after the background-image code, which of course takes the place of the image when one is unavailable, but...
How do you specify a backup background-image - one that should be displayed if the image referenced is unavailable? If there's no CSS trick for this, maybe JavaScript could handle it?
In modern browsers you can chain background images and have more than one on each node. You can even chain background-position and background-repeat etc!
This means you can declare your first image (which is the fallback) and then the second one appears over it, if it exists.
background-color: black;
background-image: url("https://via.placeholder.com/300x300?text=Top Image"), url("https://via.placeholder.com/300x300?text=Failed To Load");
background-position: 0 0, 0 0;
background-repeat: no-repeat, no-repeat;
JFIDDLE DEMO
Simple answer:
You could either nest the span inside another span - with the outer span set to use the backup background image. If the inside span's background isn't available, then you'll see the outside one's
Better, more difficult answer:
You could achieve a similar result in pure CSS, by adding some psuedo content before the span, and then styling that to have the fallback background. However, this usually takes some trial and error to get it right;
Something lile
span.image:before{content:" "; background:url(backup.png); display: block; position:absolute;}
Well, I know that the actual tag has onload, onerror, and onabort events.
You could try loading it in an image, then if that succeeds, use JS to set the background property of the body.
EDIT: Never mind. I like his answer better.
Just declare the preferred default image after your background declaration:
.image
{
background: #000 url('http://www.example.com/images/image1.png') 0 0 no-repeat;
width: xxpx;
height: xxpx;
background-image: url('http://www.example.com/images/image1.png');
}
<span class="image"></span>
idk the dimensions of your img, so they are "xxpx"
working demo: http://jsfiddle.net/jalbertbowdenii/rJWwW/1/