I have a image that is created to have 4 images in one See this image
Now, what I am trying to do is get the css to load just the first square at the top. Then when a user hovers over that image it will switch between all four images.
So it will display black on load, then when a user hovers over it, the image changes to red, then blue, then green, then back to black. It then repeats over and over until the mouse is moved off the image area.
I know that I can do this by converting the png to a gif but the image is generated outside of my control so this method is needed.
If anyone can help I will be forever grateful.
Cheers.
You should use CSS sprites and to make the change happend when over use setInterval function to change position ( here the height of each block of your image mesures 300px , so we incerement by +300 ) every defined interval time ,
Below snippet I've used .hover() jquery function to set and clear annimation .
var interval;
$(function(){
$("#image").hover(
function() {
var bottom = 0;
$this = $(this);
interval = setInterval(function() {
bottom >= 900 ? bottom = 0 : bottom+=300;
$this.css({'background-position' : '0px -'+bottom+'px'});
} , 1000)
},
function(){
$this.css({'background-position' : '0 0'})
clearInterval(interval);
}
);
});
#image {
width:150px;
height:150px;
background: url('https://i.stack.imgur.com/h8h14.png') 0 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image" ><div>
I am using jQuery rotate plugin to rotate an image. The problem is that when the image rotates it comes out of the boundry of the container as the width and height of the container are not updated.
Is there away to update the container dimensions also? If you want to look at the application you can go here. Upload an image and press rotate to see the problem.
There is a callback function which will be called when the animation is done.. In this function you can reset the img container width and height like this (not tested):
var img = $('#img');
var cont = img.parent();
img.rotate({bind:{
click: function(){
$(this).rotate({
angle: 0,
animateTo:180,
callback: function(){
cont.css({ width: img.css('height'), height: img.css('width') });
}
})
}
}
});
I am having difficulty finding a tutorial on enlarging an image on mouse hover, then shading the enlarged image dark so I can put some text over it.
This example does almost everything except make the image larger:
http://jsfiddle.net/balupton/FZG3v/
CSS:
.ih { position:relative; }
.ih, .ih-image, .ih-info { display:block;width:330px;height:220px; }
.ih-image, .ih-info { z-index:500;position:absolute;top:0;left:0;right:0;bottom:0; }
.ih-info { z-index:501;background:black;color:white; }
HTML:
<img class="ih-image" src="http://designsnack.com/screenshots/image.php width=330&height=220&cropratio=330:220&image=/screenshots/8264948088.jpg"/>
<div class="ih-info">
Your overlay content
</div>
</div>
JS:
$(function(){
$('.ih').hover(
// Over
function(){
var $ih = $(this);
$ih.find('.ih-info').stop(true,true).animate({opacity:0.8}, 400);
},
// Out
function(){
var $ih = $(this);
$ih.find('.ih-info').stop(true,true).animate({opacity:0}, 400);
}
).find('.ih-info').css('opacity',0);
});
It's my first question, apologies if I am not clear or am missing some information.
Many thanks for any help!
EDIT: Thanks ghost! My end goal is to enlarge the image from the center as ultimately there will be 4 images in a 4X2 configuration.
You can do this many ways using jQuery, one of them is to use animate() method to smoothly change image size: http://jsfiddle.net/FZG3v/44/
I am trying get this background to fade in on click. I found one tutorial that was helpful, and I ended up created the code so it has two images, and they fade in and out on click to bring up the picture.
Here's the work: http://www.mccraymusic.com/bgchangetest.html
Only a couple of issues though:
How do I make this work without the images getting selected at random? I'd like it to just switch from the plain black image to the image with the drum set. (And cross-fade to if possible, but not necessary)
How do I center the image on the page, so the image of the drums are centered?
I'm guessing this is what you're after:
$(function() {
var images = ["black.jpg","bg.jpg"];
$('<img>').attr({'src':'http://www.mccraymusic.com/assets/images/'+images[0],'id':'bg','alt':''}).appendTo('#bg-wrapper').parent().fadeIn(0);
$('.entersite').click(function(e) {
e.preventDefault();
var image = images[1];
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'http://www.mccraymusic.com/assets/images/'+image);
$(this).fadeIn(1000);
});
$(this).fadeOut(1000, function() {
$(this).remove();
});
});
});
DEMONSTRATION
Also added :
display: block;
margin-left: auto;
margin-right: auto;
to your #bg element to center the image.
Alright, assuming you use JQuery
You have #backgroundid and #imageid
Begin by setting
$('#backgroundid').css('opacity',1);
$('#imageid').css('opacity',0); // setting opacity (transparency) to 0, invisible
Now you have #buttonid.
Set up a jquery event so that when it's clicked, you fade out the background, and fade in the image using JQuery's animate.
$('#buttonid').click(function() {
$('#backgroundid').animate(function() {
opacity : 0 // fade it to 0 opacity, invisible
}, 1000); // animation will take 1000ms, 1second
$('#imageid').animate(function() {
opacity : 1 // fade it to full opacity, solid
}, 1000);
});
Now about that image centering.
You can either let css manage it with
body { /* Body or #imageid parent */
text-align : center;
}
#imageid {
margin: 0px auto;
}
Or you can stick to a JQuery solution, using absolute/fixed positioning.
First, use some css to fix the position of your image
#imageid {
position: absolute; // or fixed, if you want
}
Now use JQuery to reposition it
function positionImage() {
var imagewidth = $('#imageid').width();
var imageheight = $('#imageid').height();
$('#imageid').css('left', ($(window).width() - imagewidth) / 2);
$('#imageid').css('top', ($(window).height() - imageheight) / 2);
}
$(document).ready(positionImage); // bind the ready event to reposition
$(window).resize(positionImage); // on window resize, reposition image too
if you keep a div element with height and width as 100% and bgcolor as black. And then change the opacity of the div as desired to get the fade in/out effect, that should generate the same effect. I guess..
You are better off using any available jQuery plugin as they would have optimized and fixed bugs for multiple browsers.
Try lightBoxMe plugin
http://buckwilson.me/lightboxme/
This is the simplest plugin available!
This question already has answers here:
Animate element to auto height with jQuery
(21 answers)
Closed 7 years ago.
I'm trying to get an element to animate to its "natural" height - i.e. the height it would be if it had height: auto;.
I've come up with this:
var currentHeight = $this.height();
$this.css('height', 'auto');
var height = $this.height();
$this.css('height', currentHeight + 'px');
$this.animate({'height': height});
Is there a better way to do this? It feels like a bit of a hack.
Edit:
Here's a complete script to play with for anyone that wants to test.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>jQuery</title>
<style type="text/css">
p { overflow: hidden; background-color: red; border: 1px solid black; }
.closed { height: 1px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$().ready(function()
{
$('div').click(function()
{
$('p').each(function()
{
var $this = $(this);
if ($this.hasClass('closed'))
{
var currentHeight = $this.height();
$this.css('height', 'auto');
var height = $this.height();
$this.css('height', currentHeight + 'px');
$this.animate({'height': height});
}
else
{
$this.animate({'height': 1});
}
$this.toggleClass('closed');
});
});
});
</script>
</head>
<body>
<div>Click Me</div>
<p>Hello - I started open</p>
<p class="closed">Hello - I started closed</p>
</body>
</html>
I permit myself to answer this thread, even if it's been answered a long time ago, cuz it just helped me.
In fact, i don't understand the first answer : why opening a half-closed element to get its height, and then closing it again ?
At the beginning, you hide the element so that just a part of it appears, right ? The best way (i believe) to do this is onready, with javascript. So, when you hide the element onready, just save the orig height in a var, so you don't have to hide(onready)-show-save height-hide to be able to toggle the elements visibility.
Look at what i did, it works perfectly :
$(document).ready(function(){
var origHeight = $("#foo").css('height');
$("#foo").css({"height" : "80px"});
$("#foo .toggle").bind("click", function(event){ toggleFoo(event, lastSearchesMidHeight); });
});
Here, when you call your toggle function, you know what is your original element height without wanking around.
I wrote it fast, hoping it could help someone in the future.
the easiest solution I found was to simply wrap the content element with a div that is limited in height and set to overflow:hidden. This truncates the inner content element to the height of the wrapping div. when the user clicks, hovers, etc. to show the full height of the content element - simply animate the wrapping div to the height of the inner content div.
I could suggest an equally-hackish solution...Clone the element, position it out of view, and get its height...then delete it and animate your original.
That aside, you could also use $.slideUp() and $.slideDown():
$this.hasClass('closed') ? $(this).slideDown() : $(this).slideUp() ;
If you need to keep a 1px line, you can apply that with a parent element:
<div style='border-top:1px solid #333333'>
<div class='toggleMe'>Hello World</div>
</div>
And apply the slidingUp/Down on the .toggleMe div.
I'd also like to chime in on this old thread, if I may, in case my solution helps anyone. My specific situation is this: I have some div's that are set with a max-height value that limits them to three lines tall, and when the user mouseovers them I want them to expand to their natural height; and when the mouse cursor leaves the div, I want them to shrink back down to the clipped, max-three-lines-tall height. I need to use the CSS max-height property, rather than height, because I have some div's that contain only one or two lines of text and I don't want them unnecessarily tall.
I tried many of the solutions in this thread, and the one that worked for me was the 'hackish suggestion' involving cloned elements suggested by Jonathan Sampson. I translated his idea into the following code. Please feel free to suggest improvements.
The functions are delegated to a parent element to handle div's created via an Ajax call. The div.overflow_expandable class has the following declaration: { max-height: 5em; overflow: hidden; }
$('#results').delegate('div.overflow_expandable', 'mouseenter', function() {
var $this = $(this);
// Close any other open divs
$('#results div.overflow_expandable').not($(this)).trigger('mouseleave');
// We need to convert the div's current natural height (which is less than
// or equal to its CSS max-height) to be a defined CSS 'height' property,
// which can then animate; and we unset max-height so that it doesn't
// prevent the div from growing taller.
if (!$this.data('originalHeight')) {
$this.data('originalHeight', $this.height());
$this.data('originalMaxHeight', parseInt($this.css('max-height')));
$this.css({ 'max-height':'none',
height: $this.data('originalHeight') });
}
// Now slide out if the div is at its original height
// (i.e. in 'closed' state) and if its original height was equal to
// its original 'max-height' (so when closed, it had overflow clipped)
if ($this.height() == $this.data('originalHeight') &&
$this.data('originalMaxHeight') == $this.data('originalHeight')) {
// To figure out the new height, clone the original element and set
// its height to auto, then measure the cloned element's new height;
// then animate our div to that height
var $clone = $this.clone().css({ height: 'auto', position: 'absolute',
zIndex: '-9999', left: '-9999px', width: $this.width() })
.appendTo($this);
$this.animate({ height: $clone.height() }, 'slow');
$clone.detach();
}
}).delegate('div.overflow_expandable', 'mouseleave', function() {
var $this = $(this);
// If the div has 'originalHeight' defined (it's been opened before) and
// if it's current height is greater than 'originalHeight' (it's open
// now), slide it back to its original height
if ($this.data('originalHeight') &&
$this.height() > $this.data('originalHeight'))
$this.animate({ height: $this.data('originalHeight') }, 'slow');
});
Found this post and end up using Greg's original 1px suggestion - works great!
Just added a callback to the animate function, to set the height of the element to 'auto' when the animation ends (in my case, the content of that specific element could change and be bigger).
$('div').click(function() {
if($('p').is(':hidden')) {
$('p').slideUp();
} else {
$('p').slideDown(function() { $('p').css('height','1px'); });
}
}
That should set the height of the p tags to be 1px once they've finished sliding.
This worked for me.
<div class="product-category">
<div class="category-name">
Cars
</div>
<div class="category-products" style="display: none; overflow: hidden;">
<div class="product">Red Car</div>
<div class="product">Green Car</div>
<div class="product">Yellow Car</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.product-category .category-name').click(function() {
if ($(this).parent().hasClass('active')) {
$(this).parent().removeClass('active');
var height = $(this).parent().find('.category-products').height();
$(this).parent().find('.category-products').animate({ height : '0px' }, 600, function() {
$(this).parent().find('.category-products').height(height).hide();
});
} else {
$(this).parent().addClass('active');
var height = $(this).parent().find('.category-products').height();
$(this).parent().find('.category-products').height(0).show().animate({ height : height + 'px' }, 600);
}
});
});
</script>
My solution is to store in the data attribute of the close button the original size of container (could have been stored also in the container itself, if you don't use the same button to also show again the container):
$(document).ready(function(){
$('.infoBox .closeBtn').toggle(hideBox, showBox);
});
function hideBox()
{
var parent = $(this).parent();
$(this).text('Show').data('originalHeight', parent.css('height'));
parent.animate({'height': 20});
return false;
}
function showBox()
{
var parent = $(this).parent();
$(this).text('Hide');
parent.animate({
'height': $(this).data('originalHeight')
});
return false;
}
I wanted to point to this answer, which suggest setting the height to "show" with the animate() function. I had to edit my "slideUp" style animate to use height:"hide" to work with it.