How to style a div underneath another div in a fluid layout - javascript

I have a somewhat complex HTML/css combination that I want to achieve. I can have any number of divs in a row and each of them will have some information pertaining to that div. The divs are represented as the red boxes in my picture.
Each div will have its own blue box that I want to be within it via HTML but display below it via css. This blue box should only be displayed when the div is clicked, should appear beneath the div (and all others in that row but ABOVE all the divs in the next row), and should span the entire width of the parent container (so it will be the width of the 5 red divs in this picture). Is anything like this possible? I can't think of a way to really do anything like this. I've created a fiddle with a quick mock up that you can alter: https://jsfiddle.net/hL8r9fu9/
.wrapper {
width:500px;
background:white;
height:500px;
}
.item {
float:left;
width: 18%;
margin-right:2%;
height:120px;
background:red;
margin-bottom:2%;
}
.info {
height:20px;
background:blue;
}
.info.is-hidden {
display:none;
}

One way you can determine the items in a row against in another row is to use .offset().top on the elements ( since the value would return same for all div in the same row ).
$(document).ready(function(){
$(".item").each(function(){
var $this = $(this);
$this.click(function(){
$this.find(".info").toggleClass("is-hidden");
if($this.offset().top > 10) // just an example value , you need to adjust this .
$this.find(".info").css("top","0%");
});
});
});
Working example : https://jsfiddle.net/DinoMyte/hL8r9fu9/3/

I was able to do this with the following jquery code:
$('.inherit-wrapper').each(function( element ) {
var $this = $(this),
property = $this.attr('wrapper-property'),
value = $this.parent().parent().css(property);
if(property && value) $this.css(property, value);
});
See the fiddle. I borrowed the function from this fiddle by iConner.

I messed with your jsfiddle and here is what I got. You will have to tweak it to get what you want, but you can see where I was going with it.
html is the same and tweaked css a bit.
js:
$(document).ready(function(){
$(".item").click(function(){
var $this = $(this);
var info = $this.find(".info");
var infoTopPos = $this.offset().top;
var infoHeight = $this.height();
var parentWidth = $this.parent().width();
var parentLeftPos = $this.parent().offset().left;
$(".info").not(info).addClass('is-hidden');
$(info).toggleClass('is-hidden');
info.css({width: parentWidth, top: (infoTopPos+infoHeight)+'px', left: parentLeftPos});
});
});

Related

Trying to get a div to always match the height of a div whose height is constantly increasing and decreasing

I have a div that contains a list of items. The user is able to add to/remove items from the list, so the div constantly changes height to compensate for the changing size of the list.
I have another div to its right that is supposed to give details about the items on the left. How can I get the div on the right to constantly keep vertically aligned with the left div and change height so that it equals the height that the left div currently is, as items are added and removed from the left div's list?
I tried to implement tables for this solution, but I find that it isn't working with my code, so instead I tried this JS code...
See this fiddle: http://jsfiddle.net/r6sc27ck/
The code might achieve what I want but the background on the left div isn't displaying so something's going wrong...
HTML
<div id="Div2">Hello2</div>
<br>
<div id="Div1">Hello1</div>
CSS
#Div1{
background-color:blue;
}
#Div2{
background-color:red;
}
JS
$(document).ready(function(){
document.onchange=setDivHeight();
function setDivHeight(){
var x=Number(document.getElementById('Div1').style.height)
document.getElementById('Div2').style.height=x;
}
});
setInterval(function() {
$('#Div1').eq(0).append('<p>appended content</p>')
}, 1000)
http://jsfiddle.net/r6sc27ck/
Instead of using document.onchange, you should call setDivHeight() in the end of the process that add content to the div.
I also modified the style and the content of setDivHeight().
http://jsfiddle.net/r6sc27ck/4/
var prevHeight;
$(document).ready(function(){
prevHeight = $('#Div1').height();
});
function setDivHeight(){
var curHeight = $('#Div1').height();
if (prevHeight !== curHeight) {
prevHeight = curHeight;
setDivHeight();
}
$('#Div2').height($('#Div1').height());
}
setInterval(function() {
$('#Div1').eq(0).append('<p>appended content</p>');
setDivHeight();
}, 1000)
If you have 2 divs next to eachother you can allign them by setting vertical-allign:
div{
vertical-align: top;
}
JSFiddle
You can set the two divs to display:table-cell and the containing div to display:table. Here is the updated fiddle http://jsfiddle.net/r6sc27ck/1/
Also there are many ways to achieve this, have a look here. https://css-tricks.com/fluid-width-equal-height-columns/
Try
css
#Div1 {
display:inline-block;
position:relative;
background-color:blue;
width:35%;
}
#Div2 {
display:inline-block;
position:relative;
background-color:red;
width:35%;
}
js
$(document).ready(function () {
setInterval(function () {
$("#Div1").eq(0).append("<p>appended content</p>");
$("#Div2").eq(0).append("<p> </p>");
}, 1000)
});
jsfiddle http://jsfiddle.net/vnt83hz7/4/

Get the first Element that is floating on next line

I have a list of Elements that are floating left:
<style>
ul {
overflow: hidden;
width: 100%;
}
ul li {
float: left;
width: 100px;
}
</style>
<ul>
<li id="#one">One</li>
<li id="#two">Two</li>
<li id="#three">Three</li>
...
</ul>
...having a window width of 200px the first Element that is floating on the second line would be #three... having a window width of just 100px that would be #two.
Now on every <li> there is a click-event bound, that should tell me which Element is the first Element on the next Line, seen by itself.
Clicking on #one with a window width of 200px I want to get #three, and with a window width of 100px I want to get #two.
I tried to solve this by getting the position of the Element that is clicked on, query the Position inside the window using .getBoundingClientRect(), get the height of the Element (taking 20px here), and then get the Element by using document.elementFromPoint(y,x)...something like this:
y = clicked_element.getBoundingClientRect().left
x = clicked_element.getBoundingClientRect().top + 21
first_element_on_next_line = document.elementFromPoint(y,x)
so far, so good... but of course this is just working if the first element on the next line is really inside the window! :-\
and this is where I'm stuck...if I have a window width of 200px and a window height of just 20px (just for the example), I just can't select #three with document.elementFromPoint() because its position is outside the window.
I could also use jQuery, it's included anyways, but everything came across was using document.elementFromPoint()
Any Ideas??
You could use following logic using jQuery .position() method: {as suggested by maja}
$(function () {
var $lis = $('ul li').on('click', function(){
var $nextFirstElement = $(this).nextAll('.first').first();
console.log($nextFirstElement);
});
$(window).on('resize', function () {
var initialLeft;
$lis.each(function(i){
if (i === 0) { // this could be put out of the loop, but...
initialLeft = $(this).position().left;
}
$(this).toggleClass('first', i === 0 || $(this).position().left === initialLeft);
});
}).resize();
});
-jsFiddle-
The Solution I'm using now (which in fact is the Solution charlietfl brought up in the Comments) is this:
$(function(){
var list = $("ul"),
lis = list.children(),
first_li = lis.first(),
list_width, first_li_width, items_per_line
var set_vars = function(){
list_width = list.width()
first_li_width = first_li.width()
items_per_row = Math.floor(list_width / first_li_width)
}
set_vars()
lis.click(function(){
index = lis.index(this)
next_first_index = index + (items_per_row - (index % items_per_row))
console.log(next_first_index)
})
$(window).resize(function(){
set_vars()
})
})

Insert inline element and animate shift to left

I've been trying to solve this problem for a week now and it seems basic, so maybe I'm missing something.
I want to have a div centered on the screen (or its container), and then insert a second div to the right of it, so that afterwards the two of them are centered (space on each side is equal).
Inserting the second div is not a problem, but I need the first block to slide over to where its going to be after the new block is inserted.
http://jsfiddle.net/rdbLbnw1/
.container {
width:100%;
text-align:center;
}
.inside {
border:solid 1px black;
width:100px;
height:100px;
display:inline-block;
}
$(document).ready(function() {
$("#add").click(function() {
$(".container").append("<div class='inside'></div>");
});
});
<div class="container">
<div class="inside"></div>
</div>
<input id="add" type="button" value="add"/>
Do I need to explicitly calculate where the original box is going to end up and then animate that, or is there a better way to do it?
I like your question so decide to write this:
$(document).ready(function() {
var isInAction = false;
var intNumOfBoxes = 1;
var intMargin = 10;
$containerWidth = $(".container").width();
$insideWidth = $(".inside").width();
$(".inside").css('margin-left',($containerWidth - $insideWidth - intMargin)/2 + 'px');
$("#add").click(function() {
if (!isInAction){
isInAction = true;
intNumOfBoxes +=1;
$(".current").removeClass("current");
$(".container").append("<div class='inside current'></div>");
$('.inside').animate({
'margin-left': '-=' + ($insideWidth + intMargin)/2 + 'px'
}, 300, function () {
$(".current").css('margin-left',($containerWidth + ((intNumOfBoxes - 2) * ($insideWidth + intMargin)))/2 + 'px');
$(".current").fadeIn(500,function(){
isInAction = false;
});
});
}
});
});
Also add this class in CSS:
.current {
display:none;
}
You don't need to change variables in JS code except intMargin. you can change this var to set margin between boxes.
Note: This code works fine on older browsers too and not need to support CSS3 features like transition.
Update: Some bugs like repeated clicks fixed.
Check JSFiddle Demo
First, we can animate only things that have explicit numerical values such as width, left or margin. We can't animate things like alignment (which actually use the same margin property but implicitly, never mind). So if we know width of inserted div let's just add it to our container.
1) Let's centre container itself and add transition to it
.container {
width: 102px; /* set explicit width; 102 - because of borders */
margin: auto; /* set margin to 'auto' - that will centre the div */
transition: width 0.5s;
}
2) Then increase the width when add div
$(".container").width($(".container").width() + 102);
3) But wait! If we add div to too narrow container it will be added to bottom not to right. So we need another container set to appropriate width before.
See final example on JSFiddle.
BTW, remove all line breaks and tabs from your code when you use inline-block, because it will cause spaces between your blocks.

jQuery show div on hover with image map

I have an image map that I want to show a new div when I hove over the hotspots. It starts with a default listing of text but once I mouseover the hotspots, I want that to change out to the corresponding div's. I'm using the following code and am getting no joy:
$(".office-default").mouseover(function () {
var elementId = "#office-" + $(this).attr("id").split("-")[1];
$(elementId).removeClass("hidden");
});
$(".office-default").mouseout(function () {
var elementId = "#office-" + $(this).attr("id").split("-")[1];
$(elementId).addClass("hidden");
});
Here's the entire code:
http://jsfiddle.net/leadbellydesign/jR6pa/1/
I've done tons of searches and have come up with nothing helpful. I don't want to change images, I just want to show div's.
You still need to fix the space below the divs, but this should work
DEMO
$("area").hover(function () {
$office = $(this).attr("href");
$(".office-default > div").addClass("hidden");
$($office).removeClass("hidden");
}, function(){
$(".office-default > div").addClass("hidden");
$("#office-1").removeClass("hidden");
});
UPDATE
To fix the spacing issue, update your .office-default CSS:
DEMO
.office-default {
background:#444;
padding:5px 15px 0;
width: 80%;
height:150px;
}

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