Reputation: 500
I am building a calendar using <div>
elements and CSS.
Using jQuery, when a day on the calendar is clicked, a class is applied to the <div>
element. This causes the day to expand.
The Problem:
When the day expands, it displaces all of the other divs in the calendar. Seen in the images below.
HTML
The HTML is created by a PHP for loop, displaying every day in the selected month.
<div id="calender">
<div id="cal-day" class="1" onclick="expand(1)">
<div id="datenum"><p>1</p></div>
</div>
<div id="cal-day" class="2" onclick="expand(2)">
<div id="datenum"><p>2</p></div>
</div>
</div>
CSS - I have removed the aesthetic styling code for readibility.
#calender{
position: relative;
width: 1230px;
height: 800px;
}
#cal-day{
float: left;
width: 200px;
height: 200px;
margin: 2px;
overflow: hidden;
}
#datenum{
width: 30px;
height: 30px;
}
.dayselected{
overflow: scroll !important;
width: 400px !important;
height: 400px !important;
}
#content{
display: none;
}
#content.show{
display: block;
}
jQuery:
function expand(date){
if($("." + date).hasClass("dayselected")){
$("." + date).removeClass("dayselected");
$(".content" + date).removeClass("show");
}else{
$("." + selectedDay).removeClass("dayselected");
$("." + date).addClass("dayselected");
$(".content" + date).addClass("show");
}
selectedDay = date;
}
Before is day is selected:
After a day is selected, with the other <div>
elements displaced:
Would it be possible to have the day clicked overlay the other divs instead of displacing them?
Here is a JSFiddle: https://jsfiddle.net/quucxwpy/
Upvotes: 2
Views: 679
Reputation: 337666
Firstly you have several duplicated id
attributes, which means your HTML is invalid. These should be changed to classes.
To solve the issue, one possible solution to this would be to clone()
the original cal-day
element and position it absolutely over the original. This would then not break the document flow of the other sibling cal-day
elements. Try this:
<div id="calender">
<div class="cal-day">
<div class="datenum">
<p>1</p>
</div>
</div>
<div class="cal-day">
<div class="datenum">
<p>2</p>
</div>
</div>
<!-- other days...
</div>
$('.cal-day').click(function() {
$('#dayselected').remove();
var $day = $(this);
var $dayClone = $day.clone(false)
.prop('id', 'dayselected')
.css({
top: $day.position().top,
left: $day.position().left
})
.appendTo('#calender');
});
$('#calender').on('click', '#dayselected', function() {
$(this).remove();
});
Upvotes: 3