Last created DIV to be above other DIVs - javascript

I'm creating DIVs dynamically and appending them to a particular DIV.
My question is how do I always make the last created DIV to be above other DIVs within the appended (its parent) DIV?
So basically I want the last created DIV to be on the top level of the other.
DIV 4 - [created at 4:32pm]
DIV 3 - [created at 4:29pm]
DIV 2 - [created at 4:27pm]
DIV 1 - [created at 4:26pm]
the dynamic DIV css:
.dynamicDIV{
width:100%;
position: relative;
}
the append DIV css:
.parentDiv{
width: 100%;
margin-top: 5px;
}
I'm not referring to the z-index. I want to position it above the others.

var parentElement;
var newFirstElement;
parentElement.insertBefore(newFirstElement, parentElement.firstChild);

As I pointed out in my comment, .prepend() can be used here:
$('.parentDiv').prepend('<div class="dynamicDIV">New Div</div>');
but there is a second possibilty:
$('<div />').addClass('dynamicDIV').text('New Div').prependTo('.parentDiv');
This solution is a bit more maintainable.
Demo
Reference
.prepend()
.prependTo()

Use .prepend() on whatever element you want to be preceeded with the new one:
http://api.jquery.com/prepend/

When a DIV is at position: absolute, the last sibling in the DOM is over the others. This doesn't depend on the time you inserted it.
But you can override this behavior by using z-index: 1.
Look at this HTML code:
<style>
div.container > div {position: absolute; z-index: 0}
div#C {z:index: 7}
</style>
<div class="container">
<div id="A">A</div>
<div id="B">B</div>
<div id="C">C</div>
<div id="D">D</div>
</div>
This code will display C hidding D, hidding B, hidding A.

CSS with display:flex and flex-direction:column-reverse; can help you:
body {/* parent container of div to shw in a reverse flow*/
display:flex;
flex-direction:column-reverse; /* row-reverse if on line*/
}
div {
width:50%;
border:solid;
margin:auto;
}
div:last-of-type:after {
content:'last in document !';
color:red;
}
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 4 </div>
anyway, in the DOM or for CSS selector, last will be last. reverse order only shows at screen.

Related

Toggle or Show/Hide

I need help toggling overlays with multiple divs. I don't want to have a separate function for each one (there's 6 with 6 different overlay popups). The onclick div will reveal the overlay popup. Help is appreciated!
I need help toggling overlays with multiple divs. I don't want to have a separate function for each one (there's 6 with 6 different overlay popups). The onclick div will reveal the overlay popup. Help is appreciated!
function on() {
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
#overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.8);
z-index: 2;
cursor: pointer;
}
#text{
position: absolute;
top: 50%;
left: 50%;
font-size: 1rem;
color: white;
transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
}
<!-- //DIV -->
<div class="row ">
<div class="col-md-6 col-lg-4 d-flex align-items-stretch" onclick="on()">
<div class="card mb-3">
<img src="img/ballet.jpg" class="embed-responsive w-100 classpic" alt="...">
<div class="card-body">
<h5 class="card-title">BALLET</h5>
</div>
</div>
</div>
<!-- //POPUP -->
<div id="overlay" onclick="off()">
<div id="text">
<h3>Ballet</h3>
<p>Ballet is an artistic dance form performed to music using precise and highly formalized set steps and gestures.
Classical ballet, which originated in Renaissance Italy and established its present form during the 19th century,
is characterized by light, graceful, fluid movements and the use of pointe shoes.
</p>
<h4>Shedule:</h4>
<p>Ages 4-8: Thursdays • 4PM<br>
Ages 9-14: Fridays • 7PM</p>
</div>
</div>
There's a problem with your approach, namely, when an element has display:none it is removed from the html tree and cannot receive a click event. Also, no two elements can share the same id attribute and so your function cannot be applied by reference to an id directly.
I've made a working snippet that achieves what I think you are after. There are undoubtedly others that would work but it's quite straight forward and works.
Firstly, arrange each of your alternative div pairs (one hidden, one visible) inside a parent div and give it a class name. This has the advantage that, if you size the container div appropriately, the content will not jump about when you swap the hidden div for visible and vice versa. Next, give classes to distinguish the (initially) hidden content from the visible div. Your markup pattern then will be repeats of:
<div class='container'>
<div class='main'>my first main content</div>
<div class='hidden'>my first hidden content </div>
</div>
In the style sheet, set the class display properties:
.hidden {
display: none;
}
.main {
display: block;
}
Then, set up a click event listener in javascript. This will take a click event from anywhere on the page.
document.addEventListener('click', event => {
})
inside the event listener, place an if block to test whether the click event was received by an element that was inside a div of .container class:
if (event.target.parentElement.className=='container') {
}
I slightly modified this, see edit note and bottom.
If the click event got that far, the click must have been recieved by the visible div inside that container (since the hidden one cannot receive click events and they are the only two elements present.
So you can go ahead and swap the classes applied to the visible div that received the click:
event.target.classList.add('hidden');
event.target.classList.remove('main');
You now have to do the opposite to the other div in the container class to make that sibling visible. The problem is, you don't know whether the hidden class was the first child, or the second child of the container div. What you do know for sure, is that the other div is a sibling of the div you just made invisible.
So we can test to see if there is a next sibling using a conditional:
if (event.target.nextElementSibling) {
event.target.nextElementSibling.classList.add('main');
event.target.nextElementSibling.classList.remove('hidden');
}
If the hidden div followed the visible one, a nextElementSibling will be found and the classes swapped. If no nextElementSibling was found, we know the other div had to come before the one we already hid.
so, an else extension of that if block can be added to switch the classes on the previousElementSibling:
...} else {
event.target.previousElementSibling.classList.add('main');
event.target.previousElementSibling.classList.remove('hidden');
} // end else;
And you're done!
I wanted to explain the logic in detail to make sure you know what's going on, but it's not that complicated.
The advantage of an approach like this is that the single event listener will cope with 1, 2, or 1,000 pairs of divs and none need any special IDs or anything other than an initial class of .main or .hidden (and that they be grouped inside a .container div.
document.addEventListener('click', event => {
if (event.target.parentElement && event.target.parentElement.className=='container') {
event.target.classList.add('hidden');
event.target.classList.remove('main');
if(event.target.nextElementSibling) {
event.target.nextElementSibling.classList.add('main');
event.target.nextElementSibling.classList.remove('hidden');
} else {
event.target.previousElementSibling.classList.add('main');
event.target.previousElementSibling.classList.remove('hidden');
} // end else;
} // end parentElement if;
}) // end click listener;
.hidden {
display: none;
border: 1px solid red;
margin: 5px;
}
.main {
display: block;
border: 1px solid black;
margin: 5px;
}
<div class='container'>
<div class='main'>my first main content</div>
<div class='hidden'>my first hidden content </div>
</div>
<div class='container'>
<div class='main'>my second main content</div>
<div class='hidden'>my second hidden content </div>
</div>
Edit the conditional to detect whether the parent element of the click event was a .container div was modified to check that the event target has a parent AND that the parent is a .container div. This prevents an error if a click is received anywhere outside of the container div.
** Displaying an Opaque Overlay in Response to Click **
Again, this solution allows the functionality to be applied to limitless div elements without the need for independent ids. Again, two classed .main and .hidden are used to decide which div has been clicked from a single event listener applied to the document rather than to multiple divs.
The basic process of displaying, and then re-hiding the (originally hidden) .overlay div is very simple:
if (element.className == 'main') {
element.parentElement.getElementsByClassName('overlay')[0].classList.remove('hidden');
}
if (element.className == 'overlay') {
element.classList.add('hidden');
}
However, a problem arises because of the use of class names, rather than ids. Namely, when the overlay is displayed, a click on it may be received by a descendent element that does not have the class name .hidden. To work properly, every descendent of the overlay div would have to be given the .hidden class and the class swapped applied for ever element inside the .hidden div. This could get very complicated if the div had many child elements (perhaps with their own descendents).
Instead, when a click is received, the target element is inspected to see if it has a relevant class (main or hidden). If it does, the script flows to the simple class switching blocks. If it has no, or a different class name however, a do-while loop examined the parent element of the click to see if it was contained in a relevant (main or hidden) class. The loop continues searching up the document tree until either a relevant element is found, or there are no more parent elements to examine.
If a parent is found to have the required class name, a reference to the element is passed onto the class switching block.
do {
if (element && (element.className == 'overlay' || element.className == 'main')) {
// foundElementClassName = element.className;
break;
} // end if;
if (element.parentElement) {
element = element.parentElement;
} else {
break;
}
} while (element.className != "overlay" || element.className != "main");
The following working snippet demonstrates the functionality. In it, three divs (coloured pink) have an associated (initially) hidden overlay div, while a fourth div has no associated overlay and should ignore clicks.
If a click is made on a pink div, it's specific overlay appears. A click anywhere on the overlay dismisses it, regardless of whether the click was received by the overlay div itself, or by a child element or deeper descendent (e.g. clicking on the text of the overlay (which is in a child h2 element still allows the correct .overlay div to have its styles switched to hide it again.
document.addEventListener('click', (event) => {
let element = event.target;
do {
if (element && (element.className == 'overlay' || element.className == 'main')) {
// foundElementClassName = element.className;
break;
} // end if;
if (element.parentElement) {
element = element.parentElement;
} else {
break;
}
} while (element.className != "overlay" || element.className != "main");
// end do-while loop;
// if a relevant element was found, the element object is stored in element variable;
if (element.className == 'main') {
element.parentElement.getElementsByClassName('overlay')[0].classList.remove('hidden');
}
if (element.className == 'overlay') {
element.classList.add('hidden');
}
}) // end click event listener;
.main {
display: block;
width: 50%;
margin: 10px;
border: 1px solid black;
background: pink;
}
.overlay {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
top: 0px;
left: 0px;
width: 100%;
min-height: 100%;
bottom: auto;
z-index: 1;
background: rgba(255,255,0,0.7);
padding: 20px;
}
.hidden {
display: none;
}
.other {
display: block;
width: 50%;
margin: 10px;
border: 1px solid black;
background: yellow;
}
<div class="container">
<div class="main">Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1 </div>
<div class="overlay hidden"><h1>overlay for first pink div</h1> </div>
</div>
<div class="other">
some other content that doesn't have an associated overlay and that should ignore clicks.
</div>
<div class="container">
<div class="main">Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2.</div>
<div class="overlay hidden"><h1>overlay for SECOND pink div</h1> </div>
</div>
<div class="container">
<div class="main">Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. </div>
<div class="overlay hidden"><h1>overlay for Third pink div</h1> </div>
</div>

How hide div inside div when inner div mode left by jquery animate:left function?

I have html:
<div style='width:300px; height:40px; float:left;' class='outerDiv'>
<div style='width:200px; height:40px; float:right;' class='innerDiv'>
Some text
</div>
</div>
I try to make small move div.innerDiv by:
$('.innerDiv').animate({ left: '+=200px' });
Basic idea - when div.innerDiv move to border of div.outerDiv, div.outerDiv should hide part of div.innerDiv. I stuck on css styles on div's.
see here : jsfiddle
you need to set a position ( relative,absolute,fixed ) so the css left:200px can work.
css :
.outerDiv {
overflow:hidden;
}
.innerDiv {
position:relative;
}
jq :
$('.innerDiv').animate({ left: '+=200px' });
let me know if this was what you were looking for.
If i understand you correctly, you want to hide the outer div but show the inner div.
You should not hide parent div, because if you hide parent div, child will be hidden.
You can change the background color of the outer div.
js fiddle link
$('.innerDiv').animate({left:'200px'}, {
complete: function () {
$('.outerDiv').addClass('hide');
}
}
);

Floating visible div inside horizontal scrollable div CSS

The issue is the following :
I have a calendar in which the user can create an appointment (using DHTMLX Scheduler Timeline View), the main problem is the Scheduler doesn't support a scrollable view , only fits the schedule into the view.
I Solve the previous problem, creating a div with a FIXED width (in this way can i have a longer horizontal scheduler ) and wrapping it inside a div that allows to scroll horizontally its content.
However , I dont have a clear idea of how to solve the following problem caused :
When the calendar is loaded , you can see which div belongs to its horizontal Row
And when the user scrolls horizontal (to see 7:00 PM for example)
You cannot see in which div with color you need to create the appointment !
So i need something like this, where the div is still visible although the user scrolls horizontally :
I already tried with something like the following :
May be a problem too with the parent container, because it hides the div if the following works maybe ?
.visible-division{
position:relative; /*Because the div with color is inside a table, and i need that still floating in the same row !!*/
float:left;
z-index:9000;/*a higher z-index in case something cover the div*/
}
without any luck ..
My CSS
#calendar-container{
width: 2000px;
}
#calendario {
height: 900px;
width: 100%;
border: 1px solid #cecece;
}
.scrolling_container {
height: 100%;
overflow: auto;
}
And my Markup
<div class="scrolling_container">
<div id="calendar-container">
<div class="dhx_cal_container panel" id="calendario">
<div class="dhx_cal_navline">
<div class="dhx_cal_prev_button"> </div>
<div class="dhx_cal_next_button"> </div>
<div class="dhx_cal_today_button"></div>
<div class="dhx_cal_date"></div>
<div class="dhx_cal_tab" name="day_tab"></div>
<div class="dhx_cal_tab" name="week_tab"></div>
<div class="dhx_cal_tab" name="month_tab"></div>
<div class="dhx_cal_tab" name="timeline_tab" style="right:280px;"></div>
</div>
<div class="dhx_cal_header"></div>
<div class="dhx_cal_data"></div>
</div>
<div class="well text-right">
<div>
a link
</div>
</div>
</div>
It can be solved via CSS ? Otherwise, Should I apply classes to it in case of scroll event ?
Any help is appreciated, thanks !
This may help you do the trick.
.visible-division{
position:fixed;
width: /* specifiy */
height: /* specify */
top: /* specify */
left: /* specify */
}
.scrolling_container {
height: 100%;
overflow: auto;
}
Though not supported by most browser, you may try sticky position value position: sticky.
Hope this will be helpful, apply this class to the floating div only.
.floating{
position:fixed;
top:20px;
right:0px;
width:80%; /* as required */
}

Prevent parent div from resizing when child div resizes

What I want to accomplish is after calling jQuery $().hide(), the animation to hide a child div on a current page and then show a new div in its place.
When I call the .hide(), the parent div resizes and I do not want that.
The parent has two divs in it, a text filled div, and the div in question so when I call the hide, only the text-only div remains. I want the height to remain the same because the new content is going to be the same height.
Here is what I have:
<div class="adminContent"> //Wrapper div, this should not change in height of 668px
<div class="adminTitle"> // Text only div, remains after .hide is called
Admin > Manage Class Roster
</div>
<div class="resetBody" id="manageClassBody1"> // Div that is being hidden/replaced
... // div contents
</div>
CSS
.adminContent {
background: #F7F7F7;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
min-height: 668px;
}
How should I have it so that its height is static after I hide the child div? Thanks!
EDIT: I want to do an in place swap of the two divs with an animation to switch between the two. I looked at the replaceWith() provided by jQuery but I'm not sure how to use it for my needs.
I would suggest using the animation features of JQuery to accomplish your task.
I created a sample JSBin for you.
Example:
$(document).on("click", "#togglebtn", function() {
var divs = $('.resetBody, .resetBody2');
var hiddenDiv = divs.filter(":not(:visible)");
var visibleDiv = divs.filter(":visible");
visibleDiv.fadeToggle({
complete: function() {
hiddenDiv.fadeToggle();
}
});
});
.adminContent {
background-color: lightgreen;
padding: 10px;
}
.resetBody {
background-color: #880000
}
.resetBody2 {
background-color: lightblue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="adminContent">//Wrapper div, this should not change in height of 668px
<div class="adminTitle">much text wow! much text wow! much text wow! much text wow! much text wow!
Admin > Manage Class Roster
</div>
<div class="resetBody">Div 1
<br/>Div 1
<br/>Div 1
<br/>Div 1
<br/>Div 1
<br/>Div 1
<br/>
</div>
<div class="resetBody2" style="display:none">Div 2 is taller
<br/>Div 2
<br/>Div 2
<br/>Div 2
<br/>Div 2
<br/>Div 2
<br/>Div 2
<br/>
</div>
</div>
<div style="margin-top:10px;">
<button id="togglebtn">Toggle</button>
</div>

Horizontal centering of a div without knowing the div width, possible?

I'm currently building a popup box script using css/jquery and i can't seem to get the div centered on the screen on all cases. It it possible to center it without knowing the div width?
Instead of posting all the code here i put up a live example at http://goo.gl/N45cp
Any kind of help is much appreciated!
Best Regards
John
<div id="wrapper">
<div id="child"></div>
</div>
If the position of the #child is not absolute, you can set left and right margins to auto:
#child {
margin: 0 auto;
}
Or if the position is absolute you can try the following:
$("#child").css("left", function(){
return ($("#wrapper").width() - $(this).width()) / 2;
});
You can achieve this with pure CSS if you have a containing div:
HTML
​<div id="outer">
<div id="inner">some content here</div>
</div>
CSS
​body, html, div#outer { height:100%; }
div#outer { text-align:center; }
div#inner { display:inline-block; }
http://jsfiddle.net/NjZbW/
​​​​​​​​​​​​​​

Categories

Resources