Can I animate the opacity of a CSS background-image? - javascript

CSS/Javascript is not my strong point so I would like to ask if is possible to change the background-image opacity to, let's say, 0.5.
I have a div with
background-image: url(images/nacho312.png);
background-position: -50px 0px;
background-repeat: no-repeat no-repeat;
but when I load a certain view it does not look very good, so I want to have a "half-disolve" effect when that view is shown. Is it possible?
Thanks

Here is a start.
var element = document.getElementById('hello'),
targetOpacity = 0.5,
currentOpacity,
interval = false,
interval = setInterval(function() {
currentOpacity = element.getComputedStyle('opacity');
if (currentOpacity > targetOpacity) {
currentOpacity -= 0.1;
element.style.opacity = currentOpacity;
} else {
clearInterval(interval);
}
}, 100);
See it on jsFiddle.
Run this on window.onload = function() { } or research cross browser on DOM ready events.
Of course, it is much easier with a library like jQuery.
$(function() {
$('hello').fadeTo('slow', 0.5);
});
This relies on your container's children inheriting the opacity. To do it without affecting them is a bit of a pain, as you can't reset children's opacity via opacity: 1.

If you want to animate smoothly and without doing too much extra work - this is a good task for jQuery (or another, similar library).
With jQuery you could do:
$('#id_of_div').fadeTo('fast', 0.5);
To get a fast animated fade effect on the relevant DIV.
Update: if you want to actually fade the background image, but not any foreground contents of the DIV, this is a lot harder. I'd recommend using one container DIV with position:relative and two inner DIVs with position:absolute; . The first of the inner DIVs can have the background image and a lower z-index than the second of the DIVs, and the second DIV would contain any text, etc. to show in foreground. When needed you can call $('#id_of_first_div').fadeTo('fast', 0.5); to fade just the DIV containing the background image.
By the way, the literal answer to your question is "No, you cannot animate the opacity of a CSS background image" - you can only (currently) animate the opacity of a DOM element, not its attributes, thus the need for the above hack.
Other Update: if you want to avoid using any third-party library, you can handle the fade of the background DIV using approach in Alex's answer.

background-image: url(images/nacho312.png);
background-position: -50px 0px;
background-repeat: no-repeat no-repeat;
opacity:0.5; //for firefox and chrome
filter:alpha(opacity=50); //for IE

Related

Fade in new background and fade out after 10s

I've tried to make my website change background every 10 seconds. It was successful. Now, I want to fade them in and fade them out, so they will appear smoothly. I've searched other forumpages and found related questions, but I wasn't able to understand the answers well.
Javascript:
function run(interval, frames) {
var int = 1;
function func() {
document.body.id = "b"+int;
int++;
if(int === frames) { int = 1; }
}
var swap = window.setInterval(func, interval);
}
run(10000, 6); //milliseconds, frames
CSS:
#b1 { background-image: url("standaard01.jpg"); }
#b2 { background-image: url("standaard02.jpg"); }
#b3 { background-image: url("standaard03.jpg"); }
#b4 { background-image: url("standaard04.jpg"); }
#b5 { background-image: url("standaard05.jpg"); }
#b6 { background-image: url("standaard06.jpg"); }
#b7 { background-image: url("standaard07.jpg"); }
#b8 { background-image: url("standaard08.jpg"); }
#b9 { background-image: url("standaard09.jpg"); }
#b10 { background-image: url("standaard10.jpg"); }
Unfortunately it's not possible to transition between two images set to the background of a single element. (correction: it is, by animating the background-image property of an element - given browser support)
However, you can fade one element out while another element lays behind it.
Jquery has a method called .fadeToggle() that you could use in this case.
Set up a "stack" of img elements or divs with bg images, positioned on top of eachother, with the position:absolute, left, and top CSS properties.
Then, in your javascript loop, every 10 seconds, .fadetoggle() the currently visible div, revealing the next image. You could keep track of the state with an index variable.
Upon reaching the final element, fade the top image again. Then before the second element fades, .show() the remaining elements so they once again visible for the revealing.
A note about z-index: The CSS property z-index will position elements either in front, or behind other elements. So it would be wise to set the correct z-index of each item either in it's css class, or programmatically on loading the page.
Image size note: If the images or divs are different dimensions, you would fade one in, while fading the other out. From here we can talk about different crossfading methods but that's beyond the scope of this discussion
Good luck :)

How to make image change color while mouse is moving over?

First off, sorry for the weird title, I don't really know a better way of describing it.
Basically I want the image to change color while the mouse is moving (hovering) over it, but for it to stop when the mouse is still,
While the mouse is stationary, color doesn't change,
While the mouse is moving, color changes.
I know there is the hover attribute in CSS, but it only has 2 states, when the mouse is hovering over it, and when it is not, what i'm looking for is something a bit trickier.
Hopefully that explains it :/
Please try this:
document.getElementById("myDiv").onmousemove = function() {
//Set random background color
myDiv.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}
Demo:
document.getElementById("myDiv").onmousemove = function() {
//Set random background color
myDiv.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}
#myDiv {
width: 150px;
height: 150px;
background-color: #ccc;
text-align: center;
line-height: 140px;
}
<div id="myDiv">Hover ME !</div>
You can achieve this with CSS animations, using Javascript to toggle a class when the mouse moves over the image, or stops doing so.
The image will need to be wrapped within another tag, if it isn't already, and then a pseudo-element will need to be added to that tag, positioned to sit directly on top of the image, with an initial opacity of 0. We ensure the image is visible behind the pseudo-element by setting the mix-blend-mode property of the latter. When the mouse first moves over the image it is, optionally, converted to grayscale and the background-color of the pseudo-element begins animating. When the mouse stops moving, the timeout in the JavaScript adds a class to the parent element which sets the animation-play-state property of the pseudo-element to paused and, when the mouse is moved again, this class is removed.
You can refine & tweak everything in this (e.g., removing the image's filter, adding/removing keyframes, chaning the mix-blend-mode, adjusting the animation-duration) just by editing the CSS, no need to touch the JavaScript.
var figure=document.querySelector("figure"),
img=figure.querySelector("img"),
timer;
img.addEventListener("mousemove",function(){
clearTimeout(timer);
figure.classList.remove("paused");
setTimeout(function(){
figure.classList.add("paused");
},300);
},0);
*{box-sizing:border-box;margin:0;padding:0;}
figure{
display:inline-block;
position:relative;
}
img{
vertical-align:middle;
transition:-webkit-filter .25s linear 99999s,filter .25s linear 99999s;
}
img:hover{
-webkit-filter:grayscale(1);
filter:grayscale(1);
transition-delay:0s;
}
figure::after{
animation:colours 5s linear infinite;
bottom:0;
content:"";
left:0;
mix-blend-mode:overlay;
opacity:0;
pointer-events:none;
position:absolute;
right:0;
top:0;
transition:opacity .25s linear 99999s;
}
figure:hover::after{
opacity:.75;
transition-delay:0s;
}
figure.paused::after{
animation-play-state:paused;
}
#keyframes colours{
0%{background:#f00;}
16.667%{background:#ff0;}
33.333%{background:#0f0;}
50%{background:#0ff;}
66.667%{background:#00f;}
83.333%{background:#f0f;}
100%{background:#f00;}
}
<figure>
<img src="https://unsplash.it/500/500/?random">
</figure>
I'm posting here as I need almost something like this. I need to change the back ground position on each mouse move. Image is set as background, here is the image:
http://pbdlbd.org/ipositive/wp-content/uploads/2015/02/one10.jpg
And I want to move the background position on each mouse move. This image has 4 parts(height of each part is 523px) and first it will show the top portion and after mouse move over it will show the 2nd portion and on another mouse move it will show 3rd portion and after 4th part it will repeat for further mouse move over it. After mouse is removed from the image, it will show the default top portion of the image.
Something like this:
document.getElementById("#ipos .flex_cell").onmousemove = function() {
//Set background position 523px bottom on each mouse move
#ipos .flex_cell.style.background-position = center -523px (here i can't make it so that it changes to -1046px by code);
}
Here is the site
TIA

Hover over image, darken background only

I would like to be able to hover over an image and only the background itself to turn black (with opacity to control how much). I already have have an effect for the image itself when it's on hover, but I would like to add an effect where the background which is white to turn to a darker color. Being able to manipulate it later on with opacity and transition would be best, but I have not been able to find css3 or jquery code that works for this so far to get me to that point. Any help would be appreciated.
html
<div class="template_design2" style="margin-top:100px; margin-left:5px;"></div>
css
.template_design2 {
background-image:url(img/template_design2.jpg);
width:740px;
height:280px;
background-repeat:no-repeat;
float:left;
}
.template_design2:hover {
background-position:0 -280px;
}
You need to add a class to your <a>s that contain the background images, so you can target them.
You use .template_design:hover, so to target the first one (since it has no class, but you can use its ID to test it works quickly, then assign all <a>s inside .template_design a class so you can target them all at the same time):
.template_design:hover a#zapzonePoster { opacity: 0.5; }
Here's a fiddle showing how it works:
http://jsfiddle.net/v6aNY/
So once you know that's working, you could then assign a class so it would be more like:
.template_design:hover a.thumbnail { opacity: 0.5; }
... which will target all of them, so you only need one rule to govern it, instead of many.
Here's the same fiddle updated with a class of .thumbnail:
http://jsfiddle.net/v6aNY/1/

How can I affect Opacity of an image whilst hovering a div?

I'm so so close to acheiving what I want... but I'm wondering if I've hit the limit of what is possible with css.
If you navigate to http://host17.qnop.net/~gjcwebde/ecocamel/index.php?option=com_content&view=article&id=28&Itemid=49
We have a product slider. I'm trying to get it so that..
1) products start at 100% opacity on load.
2) hover over a product.. and the one you are hovering over stays at 100% opacity, the others all go to say 0.5 opacity (dim down).
I have ALMOST achieved this with css. Yo can see it working, except, when you hover over the description that pops up... the active image goes back to 0.5 opacity. Is it possible to control the opacity of this image, whilst hovering over the popup description? I really really hope so! Failing that... how might I acheive this with js? Looked at some on here, but none really apply to my situation. Hope I've given enough information for you to understand. Cheers!
#containingDiv:hover img { } will affect the img when any of the containing div is hovered over so I would use that if I were you, Ryan's solution will only affect the img if you are hovering over it
I picked up your html and put it in a fiddle. Take a look http://jsfiddle.net/hMW8N/
Anyway, this is all you basically need. I'm over specifying with these selectors, but I'm doing it so you can better understand.
#slider-list-stick-1:hover .slide-index{
opacity: 0.5;
filter:alpha(opacity=50); //ie
}
#slider-list-stick-1 .slide-index:hover {
opacity: 1;
filter:alpha(opacity=100); //ie
}
This should work for the opacity on the images when the user is not hovering.
divName img {
opacity:0.3;
filter:alpha(opacity=30);(IE)
}
And then when they hover (this should include your product info styling to as you have that displayed when hovering.)
diveName img:hover{
opacity:1.0;
filter:alpha(opacity=100);(IE)
}
Also throw in an active class on start so that at least one product is being shown when the page loads
For example:
divName img .activeLoad{
opacity:1.0;
filter:alpha(opacity=100);(IE)
}
Add to your styles this declaration
.slide-index:hover img{
opacity: 1;
}
As other divs are also in the slide-index container - the hover effect will still be applied.

Can I set a div's background to be two different images filled to 2 different %'s?

After looking through W3Schools I'm still not sure if this is possible or not.
The idea is to have the div be a progress bar. (Yes, I am aware of jQuery UI's progress bar.) I would like it to start out 100% filled with one background-image, but overtime have it fill from 0%/100% to 100%/0%.
I see that it is possible to have multiple background images specified using css: http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_background_multiple
but I am not sure how to extend that logic to having only % widths. Any ideas? Thanks
You can't set the width of a background image. But the solution is easy. The div by itself is the progress bar at 0% (so has the unloaded background image), then have another div inside that which is the actual progress (which animates from 0% to 100% and has the loaded background image). So you animate the width of the div inside the progress bar to represent progress.
This site has a few examples that use a span within a div:
http://css-tricks.com/css3-progress-bars/
it's not using images (just CSS3), but you could easily update it have background images on both the span and the div. CSS3 does allow multiple background images (http://www.css3.info/preview/multiple-backgrounds/) but I'm not really sure if it's the best use for your example.
Using position: absolute; or position: relative;, it's possible to overlay one image with another; you'll have to be careful with the z-index, though. You'll then be able to animate the width of the image you want to act as the 'progress meter' using jQuery's animate() function, like this (assuming your progress meter image width starts out at 0px and will end up at 100px):
$("#progress_meter").animate( {"width": "100px"}, 5000);
No, but you can set another div on top of the initial div and have a higher z-index property.
For example, on the code below, div-a will be on top of div-b:
.div-a {
with: 50%;
height: 30px;
z-index: 2;
}
.div-b {
width: 100%;
height: 30px;
z-index: 1;
}

Categories

Resources