I'm trying to define and declare an image from a sprite sheet in javascript.
I've defined the image within an external style sheet as follows:
#myimage{ background-position: 0 -751px; width: 21px; height: 21px; }
.dwg { background:url(spriteSheet.png) no-repeat;}
I've tried various arrangements similar to the following, none of which, of course, works.
myimage=new Image();
myimage.src="background:url('spriteSheet.png') 0 0; width: 35px; height: 16px; no-repeat";
I use the image as follows:
document.stat.src = myimage.src;
My Javascript conditional logic switches between various images depending upon status. The code has worked fine with individual images, but I have combined them into a sprite sheet and now need to assign individual images from the sheet. And in order to do so, I need to define each image as a JavaScript variable.
What should be inserted in place of the background: url... string?
A few months I a started using the following approach and it became the easiest to me:
JS code:
$('[class*=sprite-]').each(function(){
var crr = this.className.match(/sprite\-(\d+)\-(\d+)/);
if ( crr && crr[2]) {
$(this).css('background-position', '-'+ crr[1] +'px -'+ crr[2] +'px');
$(this).addClass('sprite');
}
});
CSS code:
.sprite {
border: none;
background-color: transparent;
background-image: url(your-sprite-image.gif);
background-repeat: no-repeat;
}
HTML code (You may replace "50x50" by your sprite coordinate):
<img class="sprite-50-50" width="100" height="200" src="use-a-blank-image.gif" alt="" >
I am not 100% sure what you are trying to do because the code is a little weird. The src attribute is the src of the image. If you are doing a sprite... then you should probably be using a div tag, not even using an img. Sprites are usually not "img" tags, but usually "div" tags that are formatted to show just a single frame of your sprite sheet using a background-image. You would only need to adjust the background properties of the div using backgroundImage and backgroundPosition properties and show the sprite you have created. There is no reason to create an Image object in javascript and try to apply it to your code.
Related
I'm trying to re-create an Instagram like sort of page with some jQuery included. This is for a course I'm taking, so I'm a student basically.
This particular part of the exercise is asking me to:
- Empty the content of a class div.
- iterate over the media that is given.
- create an empty div and assign two classes, background image and append to the "empty" class.
The code I have so far is the following:
function renderUserMedia (media) {
// The class that is being emptied.
$('.user-media').html('');
// iteration
media.forEach(function (mediaItem) {
// empty div to add to every iterated picture with whatever is needed
var div = $('<div>').addClass('user-media-item u-pull-left').css('background-image', mediaItem).appendTo('.user-media');
});
}
All media is fetched through an API which I have no idea how is being configured (school configuration and what not), and the media is from a "dummy" insta page I guess.
What's happening is that images are not happening on the browser, and I think it has something to do with the .css implementation of the images iterated. The property background-image does not exist in the css file, so there might be something going on.
I have also tried to append to '.user-media' with $('.user-media').append(div); on the next line, but it didn't produce the desired result, which is to have all pictures iterated from forEach with the '.user-media-item' class.
.user-media-item {
margin-right: 10px;
margin-bottom: 10px;
width: 230px;
height: 230px;
overflow: hidden;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
Could someone please help me understand what am I doing wrong?
After having checked everything and not being able to retrieve images, the only needed thing was (thanks to #freedomn-m and #CBroe for directions) to include the actual key that holds the location of the file. In this case a local folder.
function renderUserMedia (media) {
$('.user-media').html('');
media.forEach(function (mediaItem) {
var div = $('<div>').addClass('user-media-item u-pull-left').css('background-image', 'url(' + mediaItem.media_url + ')').appendTo('.user-media');
});
}
In case of using the url key, then we should change to .css('background-image', 'url(' + mediaItem.permalink + ')') as it was showing in the object containing the info of the images.
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
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/
I want to add text onto an image giving the text a transparent black background. Essentially, I want to achieve the effect described in the following link:
http://www.google.com/url?sa=t&source=web&cd=4&ved=0CD8QFjAD&url=http%3A%2F%2Fcss-tricks.com%2F3118-text-blocks-over-image%2F&rct=j&q=text%20on%20image&ei=IsmITsK4DYWc0AWj-4H9Dw&usg=AFQjCNHD2pL0MiEQObwT53pWzFq2gJoH6g&cad=rja
The problem is that I am dynamically generating these images and randomly placing them on the screen. Therefore, I cannot absolutely position the text (at least, not without knowing the height of the text in total). Is there another way to do this?
Thanks!
you can position text absolutely. once images are loaded, even if randomly, jQuery's position() method will provide you will all the information you need.
obviously, you would like to to encapsulate images in containers e.g. or use and set image using div's background image. then you have all the freedom to put whatever text/effects you want in the container.
I am dynamically generating these images and randomly placing them on the screen.
Without seeing some of the code you have so far, it’s a bit difficult to help. If you’re dynamically generating the images, couldn’t you also dynamically generate the text along with it?
I.e. instead of generating:
<img style="position: absolute; top: RANDOMVALUE; left: RANDOMVALUE;">
Could you generate:
<div class="image-with-text-over-it" style="position: absolute; top: RANDOMVALUE; left: RANDOMVALUE;">
<img>
<p>Text to be overlaid on image</p>
</div>
And then in your stylesheet, write some CSS that positions the text in every instance of this over the image in that instance:
.image-with-text-over-it p {
position: absolute;
bottom: 2em;
left: 0;
color: #fff;
background: rba(0, 0, 0, 0.8);
}
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 :(