jQuery: Load background image from css class into variable? - javascript

How can I load the background-image (url) from a css class into a JavaScript variable (preferably using jQuery) ?
Example:
.myCssClass { background-image: url(/images/checkered.gif) no-repeat; }
...and now load checkered.gif into a var CheckeredGraphic = ??? using JavaScript.

One way you could do it is to just ask jQuery what the background image is. If you don't have any elements with class myCssClass perhaps just generate one and don't add it to the DOM.
var checkeredGraphic = $('<div class="myCssClass"></div>').css("backgroundImage");
I haven't tested that, but if it doesn't work, perhaps add it to the body with a large negative margin so it doesn't render on screen.
That line above will return url(/images/checkered.gif) so then you could just use a regex to clean it up:
...css("backgroundImage").replace(/url\(['"]?([^\)'"]+)['"]?\)/, "$1")
Also, your css definition is wrong. It should be:
background-image: url(...);
background-repeat: no-repeat;

You can access CSS properties from JavaScript pretty easily. Check this out for an in depth explaination: http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript

Related

Using a JavaScript function with CSS via <style>

I am working on a simple slideshow. I am using Javascript for the process of the slideshow and CSS for display of it. For some reason the CSS shows the first image perfectly but the JavaScript function is not engaging with the CSS to change the images. Suggestions?
Here is my code:
<body>
<style scoped id="slider">
html{
background: url('Africa Twin Mountainside.jpg') no-repeat center center fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
</style>
<script type="text/javascript">
var images = [
"Africa Twin Mountainside.jpg",
"FZ-10.jpg",
"GSXR track.jpg",
"Pioneer 1k mountain.jpg",
"Raptor sand.jpg"
];
var step = 0;
function slideit(){
var imageUrl = images[step];
document.getElementById('slider').src = background;
step++;
if(step>=images.length)
step=0;
setTimeout("slideit()", 1000);
}
slideit();
</script>
</body>
This should work for you:
var images = [
"Africa Twin Mountainside.jpg",
"FZ-10.jpg",
"GSXR track.jpg",
"Pioneer 1k mountain.jpg",
"Raptor sand.jpg"
];
function slideit(step){
document.getElementById('slider').src = images[step || 0];
step++;
if(step === images.length) {
step = 0;
}
setTimeout(function() {
slideit(step);
}, 1000);
}
slideit();
This is going to be somewhat long, but hopefully this will point you in the right direction to rework your solution properly.
I'll start with this: <style scoped id="slider">
Firstly, the scoped attribute for <style> tags are currently only supported by Firefox, so I would avoid it altogether for the time being. The purpose of the scoped attribute is to constrain the style to the enclosing element, but you can easily do the same thing with the class attribute instead.
Since this is a simple, single-page idea you're implementing, it's perfectly acceptable to use <style> tags directly in your html document, but in general, it's better to create a separate css stylesheet and attach it to your page with a <link> tag. If you do include styles in the html document, it would typically be found inside the <head> tag.
Additionally, I don't think I've ever seen someone declare styles for the html tag; from my experience that's typically used for the body tag instead, but perhaps someone more knowledgable that I can comment on that.
Lastly, you've given this style tag an id, however I can think of no practical use for this, and when you try to manipulate it in your javascript with document.getElementById('slider').src = background;, you're selecting this <style> block - which doesn't have a src attribute, so that piece of code does nothing at all.
What you really want to use here is an <img> tag, which does have a src attribute that can be manipulated - you were on the right track here, but used the wrong tools. I would ditch the <style> element you have here altogether and just use an <img> like so:
<img id="slider" src="Africa Twin Mountainside.jpg">
You can then style this in css:
#slider {
width: 100%;
height: auto;
margin: auto;
}
This will scale up your image to take up the entire width of the browser; the size can be adjusted to your preference. It will also center your image in the browser if you choose a width < 100%.
Now we can look at your script. Peter Chon's answer is a well-written, working solution that will work when combined with the <img> tag that I've written above, and is essentially the same thing I would have written. You almost had the script part right, and if you compare what's written in Peter's answer to yours you can see that you were nearly on the mark. He would probably be willing to explain further if you have questions.
You had the methodology for how to implement your slideshow (mostly) correct, but the execution didn't work because you didn't understand what tools to use to get the job done. W3Schools get's a bad rap around these parts, but it's not a bad place to start if you're looking to learn about the basics without investing in a book, and if you read through their tutorials you can get at least a basic understanding of how tags and their attributes can be used to accomplish things.
If I had book references I'd provide them, but I don't. One that I considered getting was "HTML and CSS: Design and Build Websites" by John Duckett. It's got good reviews on Amazon, but I haven't read it personally.

Standardize image into div

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

Update CSS rule property value

I have a html element which is styled (using jquery) with a background image targeted thru its class name.
When I remove the class the background image stays - which is not what I expected or want.
test.html
<div id='log' class='tile'>HELLOWORLD</div>
test.css
.tile{
background: none;
}
test.js
$('.tile').css("background-image", "url(tile.jpg)"); // We see image
$('#log').toggleClass('tile'); // We still see image
After banging my head I think I know whats happening. The css is being applied to the element - NOT to the 'class'.
How can I target a specific css rule so that its key values can be updated?
If that makes sense.
If you wan to change the css rules of the ".tile" class, then you can do it.
There is a post that explains it very well :
function changeBackgroundImage(className, value){
var ss = document.styleSheets;
for (var i=0; i<ss.length; i++) {
var ss = document.styleSheets;
var rules = ss[i].cssRules || ss[i].rules;
for (var j=0; j<rules.length; j++) {
if (rules[j].selectorText === className) {
rules[j].style.backgroundImage = value;
}
}
}
}
You can call it like this :
changeBackgroundImage(".tile","url(tile.jpg)");
The problem is that you´re setting the background-image as an inline stlye that overrides any stylesheet rules. Toggling the class won´t have any affect.
You can either have set the background through a styleheet rule and then add a class that removes it;
#log {
background-image: url(tile.jpg);
}
#log.tile {
background: none;
}
or you could just use !important as;
.tile {
background: none !important;
}
...it might be the other way around but you get the point? :)
try removing class tile and applying new class with bg: none
in effect - when needed apply class with bg, when not needed - without
No need for jQuery in this case. You can use plain old JavaScript. Check out this tutorial:
javascriptkit.com - Changing external style sheets using the DOM
You can't change the class itself without re-writing that declaration in the stylesheet, you ARE working only with the element in the selector.
Try:
$('.tile').css("background-image","none")
$('#log').toggleClass('tile',true);
I would make the background image part of the class as a css style:
.tile {background-image: url('tile.jpg')};
and then remove the class when necessary with jquery
$('#log').removeClass('tile');
you could have two classes in your css...
.tile{
background: none;
}
.tile-w-image
{
background-image: url(tile.jpg);
}
and then with jquery just toggle the classes...
$("#log").toggleClass('tile').toggleClass('tile-w-image');
I'm sure this is just one of many ways of doing this. I hope it helps.
You are very close.
It seems like you are adding inline CSS to your element and then trying to toggle the class. You should keep CSS styling separate in most cases:
HTML:
<div id='log' class='tile'>HELLOWORLD</div>
jQuery (I imagine this should be done on click or another event):
$('#log').toggleClass('tile'); // We still see image
If the "tile" class is already written to the HTML, then toggle-ing it will remove it.
CSS:
.tile{
background-image: url(tile.jpg);
}

CSS - Extra background image for when the first image doesn't load?

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/

How to override HTML image using CSS

I have my current code:
#content img[src="/img/test.gif"] {
background-image:url(dark-img.png) !important;
}
From my understanding !important; overrides existing values?
Why isn't this overriding the current HTML image in place there? The background shows up, behind the HTML image.
I want it in front of the HTML image, is this possible using CSS or JS?
Edit: For what its worth, im making a userscript that will modify the existing style of the site. So I do not have direct access to the HTML image.
You don't need javascript for image replacement! As long as you can identify the image by a CSS selector, you can use CSS to do the trick.
See the solution here
http://www.audenaerde.org/csstricks.html#imagereplacecss
Here is the code using only css:
<img src="tiger.jpg"
style="padding: 150px 200px 0px 0px;
background: url('butterfly.jpg');
background-size:auto;
width:0px;
height: 0px;">
sets the image size to 0x0,
adds a border of the desired size (150x200), and
uses your image as a background-image to fill.
If you upvote this answer, give #RobAu's answer an upvote, too.
The replacement of an image in CSS can be done in several ways.
Each of them has some drawbacks (like semantics, seo, browsercompatibility,...)
On this link 9 (nine!) different techniques are discussed in a very good way :
http://css-tricks.com/css-image-replacement/
If you are interested in css in general : the whole site is worth a look.
The background-image property, when applied to an image, refers to (drum roll ... ) the background-image of the image. It will always be behind the image.
If you want the image to appear in front of the image, you are going to have to use two images, or another container with a background-image that covers the first image.
BTW, it is bad practice to rely on !important for overriding. It can also be ineffective since 1) it can't override declarations in an element's style attribute, and 2) it only works if it can work based on the markup and the current CSS. In your case, all the huffing and puffing and !important declarations won't make an image do something it can't do.
I answered a similar question in another SO page..
https://robau.wordpress.com/2012/04/20/override-image-src-in-css/
<img src="linkToImage.jpg" class="egg">
.egg {
width: 100%;
height: 0;
padding: 0 0 200px 0;
background-image: url(linkToImage.jpg);
background-size: cover;
}
So effectively hiding the image and padding down the background. Oh what a hack but if you want an with alt text and a background that can scale without using Javascript?
Use your 'userscript' to change 'src' attribute value.
If there is an ID there, you can do this:
document.getElementById('TheImgId').src = 'yournewimagesrc';
If there is no ID:
var imgElements = document.getElementsByTagName('img');
Do iteration of imgElements. When its src value is match with your criteria, change the value with your own, do break.
Update:
Javascript:
<script language="javascript">
function ChangeImageSrc(oldSrc, newSrc) {
var imgElements = document.getElementsByTagName('img');
for (i = 0; i < imgElements.length; i++){
if (imgElements[i].src == oldSrc){
imgElements[i].src = newSrc;
break;
}
}
}
</script>
HTML:
<img src="http://i.stack.imgur.com/eu757.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<script language="javascript">
setTimeout("ChangeImageSrc('http://i.stack.imgur.com/eu757.png', 'http://i.stack.imgur.com/IPB9t.png')", 5000);
</script>
Preview:
The first image will be replaced after 5 secs. Try Live Demo.
you'll have to place the first image as a background-image too. Then you can override it. You could do in a "standard" css file for the site, and every user gets its own, where he can override what he wants.
i agree with all the answers here, just thought id point out that 'browsers' such as IE won't like the img[src="/img/test.gif"] as a means of selecting the image. it would need a class or id.
The images shown in tags are in the foreground of the element, not the background, so setting a background image in an won't override the image; it'll just appear behind the main image, as you're seeing.
What you want to do is replace the image. Here's your options:
Start with an element with a background image, not an tag. Then changing the background image in CSS will replace it.
Start with an tag, but use Javascript to change the src attribute. (this can't be done in CSS, but is simple enough in JS)
EDIT:
Seeing your edit in the question, I'd suggest option 2 - use Javascript to change the src attribute. It's quite simple; something like this would do the trick:
document.getElementById('myimgelement').src='/newgraphic.jpg';
You should be able to replace it by just doing something like:
.image {
content: url('https://picsum.photos/seed/picsum/400');
width: 200px;
height: 200px;
}
Unfortunately seems that it does not work in Firefox :(

Categories