show div as popoup when clicking on image [closed] - javascript

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an image.
I want to show different divs as popup when user clicks on particular area of the image.
I want to do it using jquery & html.
Can any one help me with this.

Here is an example of sample solution: http://jsfiddle.net/htEvT/2/
JavaScript
$('#rabbit').click(function (e) {
var offset = $(this).offset(),
left = e.pageX - offset.left,
top = e.pageY - offset.top;
if (top > $(this).height() / 2) {
alertDiv('You\'ve cliked under the middle.', 'alert-white');
} else {
alertDiv('You\'ve cliked above the middle.', 'alert-gray');
}
});
function alertDiv(text, cssClass) {
var alrt = $('<div class="alert ' + cssClass + '">' + text + '</div>');
$(document.body).append(alrt);
alrt.click(function () {
alrt.remove();
});
}
​
CSS
.alert {
position: absolute;
left: 30px;
top: 30px;
width: 300px;
height: 200px;
border: 1px solid black;
}
.alert-white {
background: white;
}
.alert-gray {
background: #ccc;
}
​
HTML
<img src="http://www.clermontanimal.net/images/lop_rabbit_easter.jpg" id="rabbit" alt="" />​
If there are any issues with my solution please let me know. :)

Use Image Map on image and attach fancy box on different sections of image. Since, you have not posted code so I can't provide coding solution for the same.

Something like below should give you an Idea how to do this:
$("img").click(function() {
$("body").append("<div class='newdiv'></div>")
})
.newdiv{width:100px; height:300px;border:1px solid red;}

My favorite is Fancybox.
I'm yet to see something it cannot do. Great documentation and widely used so if you need help there is a high chance somebody else has asked the same question, and can be resolved with a simple google.

Create a DIV named "imgbox" on the HTML page on which your thumbnail images will be shown. The DIV and the CSS element ID associated with the DIV is shown below
<div id="imgbox"></div>
the css
#imgbox
{
vertical-align : middle;
position : absolute;
border: 1px solid #999;
background : #FFFFFF;
filter: Alpha(Opacity=100);
visibility : hidden;
height : 200px;
width : 200px;
z-index : 50;
overflow : hidden;
text-align : center;
}
Here is the JavaScript code to show the popup image:
Get the left and top positions of the thumbnail image:
function getElementLeft(elm)
{
var x = 0;
//set x to elm’s offsetLeft
x = elm.offsetLeft;
//set elm to its offsetParent
elm = elm.offsetParent;
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x
//offsetTop to y and set elm to its offsetParent
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
elm = elm.offsetParent;
}
return x;
}
function getElementTop(elm)
{
var y = 0;
//set x to elm’s offsetLeft
y = elm.offsetTop;
//set elm to its offsetParent
elm = elm.offsetParent;
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x
//offsetTop to y and set elm to its offsetParent
while(elm != null)
{
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return y;
}
Get the thumbnail image source, make the DIV visible, increase the height and width to the required size, and attach the image to the DIV.
function Large(obj)
{
var imgbox=document.getElementById("imgbox");
imgbox.style.visibility='visible';
var img = document.createElement("img");
img.src=obj.src;
img.style.width='200px';
img.style.height='200px';
if(img.addEventListener){
img.addEventListener('mouseout',Out,false);
} else {
img.attachEvent('onmouseout',Out);
}
imgbox.innerHTML='';
imgbox.appendChild(img);
imgbox.style.left=(getElementLeft(obj)-50) +'px';
imgbox.style.top=(getElementTop(obj)-50) + 'px';
}
Hide the DIV at mouse out.
function Out()
{
document.getElementById("imgbox").style.visibility='hidden';
}
Add a OnMouseOver client-side event call for the thumbnail images to show the popup image on mouse-over.
<img id='img1' src='images/Sample.jpg' onmouseover="Large(this)" />

If the area is square, you can place a transparent element over the desired area, and give it a simple onClick event.

Use SimpleModal
You can use the plugin SimpleModal to achieve what you wanna do.
SimpleModal is a lightweight jQuery Plugin which provides a powerful interface for modal dialog development. Think of it as a modal dialog framework. SimpleModal gives you the flexibility to build whatever you can envision, while shielding you from related cross-browser issues inherent with UI development.
Using that, you can either call an already existing div or create a modal on the fly.
Calling an existing div:
$("#element-id").modal();
Making a modal on the fly:
$.modal("<div><h1>SimpleModal</h1></div>");
Giving options:
$("#element-id").modal({options});
$.modal("<div><h1>SimpleModal</h1></div>", {options});
Demos:
More demos here: http://www.ericmmartin.com/projects/simplemodal-demos/

Related

HTML full size div containing a draggable table

I'm not sure how to explain what I exactly want (which makes it really hard to google for as well), but I would like to create a table with each cell a specific width and height (let's say 40x40 pixels).
This table will be way larger than the viewport, so it would need some scrolling, but I don't want scrollbars (this part ain't a problem), but a way to drag the table around "behind the viewport".
To make it a bit more complex, I need to be able to center a specific cell and know which cell is centered too (although if I know for example that the table is on left: -520px; I can calculate what the situation is).
Long story short, I'm looking for something that looks and works like maps.google.com, but then with a table and cells instead of a canvas or divs.
What you're trying to achieve is relatively simple. You have a container div element with position: relative; overflow: hidden applied via CSS and the content set to position: absolute. For example:
<div class="wrapper">
<div class="content-grid">
... your grid HTML ...
</div>
</div>
You then need to set up some mouse/touch tracking javascript, you can find plenty of examples around Stack Overflow or Google, which monitors the position of the mouse at mousedown or touchstart events and then tests this repeatedly on an interval to see where the pointer is and update the content-grid top and left position, until mouseup or touchend.
You can make this animation smooth using CSS transition on left and top.
The tricky bit is calculating the position for the centre cell. For this I would recommend calculating a central zone, the size of your grid cells (i.e. 40x40) in the middle of your container element. Then checking if any grid cell is currently more than 1/4 inside that zone, and treating it as the "central" element.
Here is a basic example for position a cell within a grid within a wrapper: https://jsfiddle.net/tawt430e/1/
Hope that helps!
I was a bit disappointed to see the down votes of my question at first. I can imagine that stackoverflow has a lot of issues with new people just trying to get their code written here, but that's not what I asked.
Anyway, with the "you share the problem, you share the solution", mindset, I fixed the code with help of tw_hoff and it all works now. It even saves the coordinates in the local storage so this example HTML keeps you in the same position if you refresh the page. I added the two example images I used as well (store the left one as farm.png, the right one as tile.png, same directory as the html page).
The actual code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game map demo</title>
<style>
body { margin: 0; padding: 0; }
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="map" style="position: absolute; overflow: hidden; width: 100%; height: 100%; background-color: darkgreen;">
<div id="content" style="white-space: nowrap;">
</div>
</div>
<script>
for(i = 0; i < 20; i++) {
for(j = 0; j < 20; j++) {
var tile;
if((i == 4 || i == 5) && (j == 2 || j == 3)) {
tile = 'farm';
} else {
tile = 'tile';
}
$("#content").append('<div style="background: url(\'' + tile + '.png\'); width: 128px; height: 128px; position: absolute; margin-left: ' + (i * 128) + 'px; margin-top: ' + (j * 128) + 'px;"></div>');
}
}
$("body").css("-webkit-user-select","none");
$("body").css("-moz-user-select","none");
$("body").css("-ms-user-select","none");
$("body").css("-o-user-select","none");
$("body").css("user-select","none");
var down = false;
var current_left = 0;
var current_top = 0;
if(localStorage.getItem("current_left") && localStorage.getItem("current_top")) {
current_left = Number(localStorage.getItem("current_left"));
current_top = Number(localStorage.getItem("current_top"));
console.log(current_left);
$("#content").css('marginLeft', (current_left) + 'px');
$("#content").css('marginTop', (current_top) + 'px');
}
$(document).mousedown(function() {
down = true;
}).mouseup(function() {
down = false;
});
var cache_pageX;
var cache_pageY;
$( "#map" ).mousemove(function( event ) {
if(down == true) {
current_left += (-1 * (cache_pageX - event.pageX));
if(current_left > 0)
current_left = 0;
if(current_left < (-2560 + $("#map").width()))
current_left = (-2560 + $("#map").width());
current_top += (-1 * (cache_pageY - event.pageY));
if(current_top > 0)
current_top = 0;
if(current_top < (-2560 + $("#map").height()))
current_top = (-2560 + $("#map").height());
localStorage.setItem("current_left", current_left);
localStorage.setItem("current_top", current_top);
$("#content").css('marginLeft', (current_left) + 'px');
$("#content").css('marginTop', (current_top) + 'px');
}
cache_pageX = event.pageX;
cache_pageY = event.pageY;
});
</script>
</body>
</html>
It still needs some work, and of course a lot of work to be actually used in a game, but this part works and I hope if someone else ever might have the same issue and searches for it on stackoverflow my solutions gives them a push in the right direction :).
Thanks for those that helped!

Using .outerWidth() & .outerHeight() with the 'resize' event to center a child element in parent

I am attempting to write some JavaScript code that will allow me to center a child element within it's parent using padding. Then using the same function to recalculate the spacing using the 'resize' event. Before you start asking me why i am not doing this with CSS, this code is only a small part of a larger project. I have simplified the code as the rest of the code works and would only serve to confuse the subject.
Calculating the space - This is the function that caculates the amount of space to be used on either side of the child element.
($outer.outerWidth() - $inner.outerWidth()) / 2;
($outer.outerHeight() - $inner.outerHeight()) / 2;
The problem
Although i have successfully managed to get the desired results with margin. Padding is causing me problems.
It appears to be increasing the width on the outer element when resized
It does not center the child element perfectly (there appears to be an offset)
The inner element collapses on resize and becomes invisible.
I realize that there may be some fundamentals regarding padding that are causing my problems however after numerous console logs and observing the data returned i still can't put my finger on the problem. Any suggestion would be very welcome. It may turn out that this is not feasible at all.
HTML
<div id="demo" class="outer">
<div class="inner">
</div>
</div>
CSS
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
.outer {
width:97%;
height:400px;
border:1px solid black;
margin:20px;
}
.inner {
width:40%;
height:100px;
background-color:grey;
}
JAVASCRIPT
var $outer = $(".outer");
var $inner = $(".inner");
var getSpace = function(axis) {
if (axis.toLowerCase() == "x") {
return ($outer.outerWidth() - $inner.outerWidth()) / 2;
} else if (axis.toLowerCase() == "y") {
return ($outer.outerHeight() - $inner.outerHeight()) / 2;
}
}
var renderStyle = function(spacingType) {
var lateralSpace = getSpace("x");
var verticalSpace = getSpace("y");
var $element;
if (spacingType == "padding") {
$element = $outer;
} else if (spacingType == "margin") {
$element = $inner;
}
$.each(["top", "right", "bottom", "left"], function(index, direction) {
if (direction == "top" || direction == "bottom") {
$element.css(spacingType + "-" + direction, verticalSpace);
}
else if (direction == "right" || direction == "left") {
$element.css(spacingType + "-" + direction, lateralSpace);
}
});
};
var renderInit = function() {
$(document).ready(function() {
renderStyle("padding");
});
$(window).on("resize", function() {
renderStyle("padding");
});
}
renderInit();
EXAMPLE - link
Although I completely disagree with this approach to horizontally centring an element, hopefully this will help you on your way.
Fiddle: https://jsfiddle.net/0uxx2ujg/
JavaScript:
var outer = $('.outer'), inner = $('.inner');
function centreThatDiv(){
var requiredPadding = outer.outerWidth() / 2 - (inner.outerWidth() / 2);
console.log(requiredPadding);
outer.css('padding', '0 ' + requiredPadding + 'px').css('width','auto');
}
$(document).ready(function(){
// fire on page load
centreThatDiv();
});
$(window).resize(function(){
// fire on window resize
centreThatDiv();
});
HTML:
<div class="outer">
<div class="inner">Centre me!</div>
</div>
CSS:
.outer{ width:80%; height:300px; margin:10%; background: tomato; }
.inner{ width:60px; height:60px; background:white; }
Furthered on from why I disagree with this approach - JavaScript shouldn't be used to lay things out. Sure - it can be, if it really needs to be used; but for something as simple as centring an element, it's not necessary at all. Browsers handle resizing CSS elements themselves, so by using JS you introduce more headaches for yourself further down the line.
Here's a couple of examples of how you can achieve this in CSS only:
text-align:center & display:inline-block https://jsfiddle.net/0uxx2ujg/1/
position:absolute & left:50% https://jsfiddle.net/0uxx2ujg/2/ (this can be used for vertically centring too which is trickier than horizontal)
You can create the new CSS class to adjust for elements size on $window.onresize = function () {
//add your code
};

JavaScript: How to get a dynamically created element's width?

I'm a JavaScript novice. Have patience with me.
I searched this site for relevant questions and found two: How to get width of a dynamically created element with $comiple in Angularj and jQuery + CSS. How do I compute height and width of innerHTML?. Their relevance and their answers are discussed below. If I missed a relevant question and this is a duplicate question, please direct me to it.
I dynamically create a <div class="popup"> (call it "popup"), populate it with innerHTML from a display: none; <div> in the markup, and insert it on the page. The relevant CSS is:
.popup {
top: 0;
left: 0;
width: 200px;
height: 250px;
}
Using event.clientX, I position popup relative to the cursor position at the time the mouseover event fired, as follows:
var widthOffset = 75, heightOffset = 0;
var windowWidth, popupWidth;
// other code ...
windowWidth = $(window).width();
popupWidth = 200; // popup.style.width returns nothing (not null,
// not undefined, just nothing).
// when event.clientX is in the left half of the window, display popup
// offset to the right of clientX;
// when clientX is in the right half, display popup offset to the left.
if( event.clientX > windowWidth/2 ){ widthOffset = -(widthOffset + popupWidth);}
popup.style.top = event.clientY - heightOffset + "px";
popup.style.left = event.clientX + widthOffset + "px";
There is a working reduced case at the Pen Popup Project Reduced Case on CodePen.
The problem is that I want to programmatically obtain popupWidth not set it as a fixed quantity. But, as the comment states,
popupWidth = popup.style.width;
is nothing. (Maybe it's a null string: popupWidth === "". I'm uncertain.)
The answer to the first question referenced above said to insert popup into the DOM before trying to obtain its width. I have done this. (See the Pen.) Still, it doesn't work.
A comment to the second answer to the second question said:
the root issues is that height cannot be set on an element with display:none.
I had display: none but when I changed it to display: block, and set popupWidth = popup.style.width;, popup "stuttered" fiercely on mouseover.
So the question remains: How do I programmatically get popupWidth just as I did with windowWidth?
With help from #Redu and #torazaburo, the answer became clear.
popupWidth = popup.offsetWidth; is the correct statement but both these conditions must be true:
popup must have been inserted into the DOM, and
display: block; must have been set.
If popup is still in memory or display: block; has not been set, then popup.offsetWidth === 0. If both of the conditions are true, then popup.offsetWidth is equal to the width set in the CSS.
Thanks to both commenters for their help.
You can do like
var popupDiv = document.getElementsByClassName("popup")[0],
width = window.getComputedStyle(popupDiv).width;
If you deal with a window or document type of element then getElementsByClassName(element,null), element.offsetWidth or element.clientWidth doesn't work. You have to access the width value like
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

How can I Animate an Element to its natural height using jQuery [duplicate]

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.

Categories

Resources