Show and hide divs with JS - javascript

I have 5 <a>...
<a id="showtrips">TRIPS</a>
<a id="showeats">EATS</a>
<a id="showfilms">FILMS</a>
<a id="showmusic">MUSIC</a>
<a id="showtravels">TRAVELS</a>
...and I have 5 <div> and each div have the content of the <a> names. I want show all <a> and show only a <div>, so I want click on a <a> and hide the others divs showing only the selected div.
I'm searching and searching but I canĀ“t find this exactly I found similar things but impossible to integrate to this problem.
This are the divs tags
<div id="trips">Content Trips</div>
<div id="eats">Content Eats</div>
<div id="films">Content Films</div>
<div id="music">Content Music</div>
<div id="travels">Content Travels</div>
#trips{ display: block };
#eats{ display: none };
#films{ display: none };
#music{ display: none };
#travels{ display: none };

This should do it, though this hides all divs on click, apart from the div matching the a tag. I'd suggest adding something to identify the divs to show/hide. This only requires vanilla js.
const test = document
.querySelectorAll('[id*="show"]')
.forEach(element => element.onclick = () => {
document
.querySelectorAll('div')
.forEach(element => {
element.style.display = 'none';
});
const divIdToShow = element.id.replace('show', '');
const divElementToShow = document.getElementById(divIdToShow);
divElementToShow.style.display = 'block';
});
console.log(test)
#trips {
display: block;
}
#eats {
display: none;
}
#films {
display: none;
}
#music {
display: none;
}
#travels {
display: none;
}
<a id="showtrips">TRIPS</a>
<a id="showeats">EATS</a>
<a id="showfilms">FILMS</a>
<a id="showmusic">MUSIC</a>
<a id="showtravels">TRAVELS</a>
<div id="trips">Content Trips</div>
<div id="eats">Content Eats</div>
<div id="films">Content Films</div>
<div id="music">Content Music</div>
<div id="travels">Content Travels</div>

This is trivial. You have 2 options: either add "onclick" events on each of your tags and then listen to these events with js. Or, since you added ids to each of your tags, you can now attach click events to them with js.
So, no more words. Here's the simple solution:
document.getElementById("showtrips").onclick = toggleShowForElement(document.getElementById("trips"));
document.getElementById("showeats").onclick = toggleShowForElement(document.getElementById("eats"));
document.getElementById("showfilms").onclick = toggleShowForElement(document.getElementById("films"));
document.getElementById("showmusic").onclick = toggleShowForElement(document.getElementById("music"));
document.getElementById("showtravels").onclick = toggleShowForElement(document.getElementById("travels"));
function toggleShowForElement(element) {
return () => {
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
}
body {
font-family: "Verdana", sans-serif;
}
* {
box-sizing: border-box;
}
a {
cursor: pointer;
color: #008800;
display: inline-block;
padding: 4px;
border-radius: 4px;
}
a:hover {
text-decoration: underline;
}
div {
background-color: #88DD99;
border-radius: 4px;
padding: 5px;
margin-bottom: 5px;
height: 30px;
text-align: center;
}
<a id="showtrips">TRIPS</a>
<a id="showeats">EATS</a>
<a id="showfilms">FILMS</a>
<a id="showmusic">MUSIC</a>
<a id="showtravels">TRAVELS</a>
<div id="trips">Content Trips</div>
<div id="eats">Content Eats</div>
<div id="films">Content Films</div>
<div id="music">Content Music</div>
<div id="travels">Content Travels</div>
Just added a bit of CSS to make it look a bit prettier. It's not needed here.

If you are using simple javascript you can toggle the div using the following code:
var mydiv = document.getElementById("myDIV");
if (mydiv.style.display === "none") {
mydiv.style.display = "block";
} else {
mydiv.style.display = "none";
}
If you using jQuery you can directly use toggle methods.
$( ".target" ).toggle();
I suggest you group your div and anchor tags using the class name, So it will be easy to maintain.
Your html code will be like:
<a id="showtrips" class="link">TRIPS</a>
<a id="showeats" class="link">EATS</a>
<a id="showfilms" class="link">FILMS</a>
<a id="showmusic" class="link">MUSIC</a>
<a id="showtravels" class="link">TRAVELS</a>
<div id="trips" class="content">Content Trips</div>
<div id="eats" class="content">Content Eats</div>
<div id="films" class="content">Content Films</div>
<div id="music" class="content">Content Music</div>
<div id="travels" class="content">Content Travels</div>
Your JS code will be look like:
document
.querySelectorAll('[class="link"]')
.forEach(element => element.onclick = () => {
document
.querySelectorAll('[class="content"]')
.forEach(element => {
element.style.display = 'none';
});
const mydiv = element.id.substr(4);
document.getElementById(mydiv).style.display = 'block';
});
I just created the working jsfiddle for you link here

Related

Is there a shorter more concise way to hide & show div with Javascript?

I am creating a dashboard with approximately 20 divs starting with "display: none;".
When the .onClick() in the sidebar will be used, it will show a specific div and keep hidden all the others.
I have used the classic solution of creating a function for each div, however, is extremely lengthy and the code looks like a mess.
Is there a better cleaner way to achieve this with Javascript?
Here is my code:
function presale() {
var x = document.getElementById("presale");
var y = document.getElementById("claim");
var z = document.getElementById("stake");
if (x.style.display === "grid") {
x.style.display = "none";
} else {
x.style.display = "grid";
y.style.display = "none";
z.style.display = "none";
}
}
function claim() {
var x = document.getElementById("presale");
var y = document.getElementById("claim");
var z = document.getElementById("stake");
if (y.style.display === "grid") {
y.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "grid";
z.style.display = "none";
}
}
function stake() {
var x = document.getElementById("presale");
var y = document.getElementById("claim");
var z = document.getElementById("stake");
if (z.style.display === "grid") {
z.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "none";
z.style.display = "grid";
}
}
*,
html {
color: #fff;
background-color: black;
}
#presale,
#claim,
#stake
/* Here I have many other divs like below */
{
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<link rel="stylesheet" href="MOD.CSS">
<script src="main2.js"></script>
<title>Base Template</title>
</head>
<body>
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li onclick="presale()">Presale</li>
<li onclick="claim()">Claim</li>
<li onclick="stake()">Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div id="presale">
<h1>Presale</h1>
</div>
<div id="claim">
<h1>Claim</h1>
</div>
<div id="stake">
<h1>Stake</h1>
</div>
</div>
</body>
</html>
Is there a better way to do this without the need to create a function and repeat the same thing over and over for each div?
There is no need for JS at all. You can simply use an anchor and use #id as hyper reference. Then you can display the element through CSS by using the :target-selector:
*,
html {
color: #fff;
background-color: black;
}
.d-none
/* Here I have many other divs like below */
{
display: none;
}
div:target {
display: grid;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<link rel="stylesheet" href="MOD.CSS">
<script src="main2.js"></script>
<title>Base Template</title>
</head>
<body>
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li>Presale</li>
<li>Claim</li>
<li>Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div id="presale" class="d-none">
<h1>Presale</h1>
</div>
<div id="claim" class="d-none">
<h1>Claim</h1>
</div>
<div id="stake" class="d-none">
<h1>Stake</h1>
</div>
</div>
</body>
</html>
Here you see a vanilla Javascript solution.
content divs are by default hidden.
If you click an element, the corresponding data-id get the class show.
window.onload = function () {
document.querySelectorAll('#nav li').forEach((elements) => {
elements.addEventListener('click', (el) => {
document.querySelectorAll('.content').forEach((item) => {
// hide all
item.classList.remove('show');
});
// show one
document.getElementById(el.target.getAttribute('data-id')).classList.add('show');
});
});
};
.content {
display: none;
}
.show {
display: block;
}
<ul id="nav">
<li data-id="presale">Presale</li>
<li data-id="claim">Claim</li>
<li data-id="stake">Stake</li>
</ul>
<div id="presale" class="content">
<h1>Presale</h1>
</div>
<div id="claim" class="content">
<h1>Claim</h1>
</div>
<div id="stake" class="content">
<h1>Stake</h1>
</div>
Something like this using data attributes and classlist toggles should also work.
I would consider minimizing your code (and CSS) by using generic CSS selectors to hide/show the individual sections. This also makes scalability and maintainability easier for the next guy.
This has the added benefit of your styling being controlled 100% using CSS and not arbitrary inline styles set by the javascript.
Adding another section is also easy as can be:
Add a new section with some id (eg. awesome-section)
Add a nav entry with the attribute data-toggle-section with the id as the value <li data-toggle-section="awesome-section">Awesome Section</li>
Profit
You're also not restricted to using just the nav elements themselves as the event listener is bound using the [data-toggle-section] selector which means that basically anything can show or hide a section as long as it has that attribute with the correct value.
const buttons = Array.from(document.querySelectorAll("[data-toggle-section]"));
const sections = buttons.map(element => {
return document.getElementById(element.dataset.toggleSection)
});
buttons.forEach(element => {
element.addEventListener('click', event => {
const selected = element.dataset.toggleSection;
sections.forEach(section => {
if(section.id === selected) {
section.classList.toggle('shown');
} else {
section.classList.remove('shown');
}
})
});
});
*,
html {
color: #fff;
background-color: black;
}
.option-section {
display: none;
}
.option-section.shown {
display: grid;
}
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li data-toggle-section="presale">Presale</li>
<li data-toggle-section="claim">Claim</li>
<li data-toggle-section="stake">Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div id="presale" class="option-section">
<h1>Presale</h1>
</div>
<div id="claim" class="option-section">
<h1>Claim</h1>
</div>
<div id="stake" class="option-section">
<h1>Stake</h1>
</div>
</div>
You could simply assign the same class (e.g. my_div) to every showable div, then pass the id to your function (that will show that and hide all the others).
function show_hide(id) {
document.querySelectorAll('.my_div').forEach(my_div => {
my_div.style.display = my_div.getAttribute('id') == id ? 'block' : 'none';
});
}
.my_div {
display: none;
}
<div>
<ul>
<li onclick="show_hide('presale')">Presale</li>
<li onclick="show_hide('claim')">Claim</li>
<li onclick="show_hide('stake')">Stake</li>
</ul>
<div class="my_div" id="presale">
<h1>Presale</h1>
</div>
<div class="my_div" id="claim">
<h1>Claim</h1>
</div>
<div class="my_div" id="stake">
<h1>Stake</h1>
</div>
</div>
Here's my attempt. It's sensibly the same as #ztom's answer but I tryed avoiding a foreach.
document.querySelectorAll("li").forEach(e => e.addEventListener("click", () => {
let shown = document.querySelector(".action:not(.d-none)")
if(shown){
shown.classList.add("d-none")
if(e.dataset.id != shown.id){
document.getElementById(e.dataset.id).classList.remove("d-none")
}
}else{
document.getElementById(e.dataset.id).classList.remove("d-none")
}
}))
.action{
display:grid;
}
.d-none{
display:none;
}
<ul>
<li data-id="presale">Presale</li>
<li data-id="claim">Claim</li>
<li data-id="stake">Stake</li>
</ul>
<div class="action d-none" id="presale">Presale</div>
<div class="action d-none" id="claim">Claim</div>
<div class="action d-none" id="stake">Stake</div>
When it comes to use the same logic on multiple elements, use classes instead of id's and your solution is shortened by default.
With jQuery, it's basically a 2-liner:
in CSS, create a class .hidden with display:none;
Your div and li elements should be grouped, using a class too.
Then you can simply refer to this classes and add the show/hide logic by:
$('h1:contains('+$(this).text()+')').parent().toggleClass("hidden");
$('h1:not(:contains('+$(this).text()+'))').parent().addClass("hidden");
$('document').ready(function(){
$('.toggle').on('click',function(){
$('h1:contains('+$(this).text()+')').parent().toggleClass("hidden");
$('h1:not(:contains('+$(this).text()+'))').parent().addClass("hidden");
});
});
*,
html {
color: #fff;
background-color: black;
}
.hidden
{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="MOD.CSS">
<script src="main2.js"></script>
<title>Base Template</title>
</head>
<body>
<div>
<ul>
<!-- Here I have other 20 options like the above -->
<li class="toggle">Presale</li>
<li class="toggle">Claim</li>
<li class="toggle">Stake</li>
<!-- Here I have other 20 options like the above -->
</ul>
<div class="hidden">
<h1>Presale</h1>
</div>
<div class="hidden">
<h1>Claim</h1>
</div>
<div class="hidden">
<h1>Stake</h1>
</div>
</div>
</body>
</html>
This is a question for Code Review section https://codereview.stackexchange.com/
However, you can try smth like this:
const elems = ["presale", "claim", "stake"];
function toggle(elem) {
elems.map(i => {
let el = document.getElementById(i);
el.style.display = "none";
});
let active_el = document.getElementById(elem);
active_el.style.display = "grid";
}
and in html add the elem name as a param, so, replace this
<li onclick="presale()">Presale</li>
<li onclick="claim()">Claim</li>
<li onclick="stake()">Stake</li>
with this
<li onclick="toggle('presale')">Presale</li>
<li onclick="toggle('claim')">Claim</li>
<li onclick="toggle('stake')">Stake</li>
If you attach data attributes to both the list items and the "panels" you can use one function to match them up, and use a CSS class to determine whether it should be active or not.
// Cache the elements, the panels container, and the list element
// separately adding one event listener to the list. We're using
// event delegation for this - one listener captures all
// the events from its child elements
const allElements = document.querySelectorAll('.list li, .panels .panel');
const panels = document.querySelector('.panels');
const list = document.querySelector('ul');
list.addEventListener('click', handlePanel);
// When the listener is triggered
function handlePanel(e) {
// Check if it's a list item
if (e.target.matches('li')) {
// Destructure its id from the dataset
const { id } = e.target.dataset;
// Remove all the active classes from the elements
allElements.forEach(el => el.classList.remove('active'));
// And then add an active class to the list item,
// and the panel where their ids match
const selector = `[data-id="${id}"]`;
const item = list.querySelector(`li${selector}`);
const panel = panels.querySelector(`.panel${selector}`);
item.classList.add('active');
panel.classList.add('active');
}
}
.panel { display: none; }
.panel h1 { font-size: 1.2em; color: darkblue; }
ul { list-style-type: none; margin-left: 0; padding: 0; }
li { padding: 0.3em; border: 1px solid white; }
li:hover { background-color: thistle; cursor: pointer; }
li.active { border: 1px solid #454545; background-color: lightyellow; }
.panel.active { display: block; }
<ul class="list">
<li data-id="presale">Presale</li>
<li data-id="claim">Claim</li>
<li data-id="stake">Stake</li>
</ul>
<div class="panels">
<div data-id="presale" class="panel">
<h1>Presale</h1>
</div>
<div data-id="claim" class="panel">
<h1>Claim</h1>
</div>
<div data-id="stake" class="panel">
<h1>Stake</h1>
</div>
</div>
Additional documentation
classList
Destructuring assignment
Event delegation
matches
querySelector / querySelectorAll
Template/string literals

jQuery .not() and :not with new classes? [duplicate]

This question already has answers here:
jQuery click event not working after adding class
(7 answers)
Closed 2 years ago.
I have some card to flip and check if one is equal to another (memory game).
If I flip the card, I don't want that is possible to click and run function if I click on the same card (that is .flipped) or on another that is flipped. But jQuery .not() and :not not working. Maybe I must read another time the DOM after .toggleClass?
$(".card:not('.flipped')").on("click", function () {
$(this).toggleClass("flipped");
if (first) {
firstCard = $(this).attr("game");
first = false;
} else {
secondCard = $(this).attr("game");
first = true;
checkGame();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The code is binding the events when it is called. So whatver the classes are at that moment in time, is what it finds and binds the event.
So you need to check for the class inside of the method and exit it
$(".card").on("click", function() {
var card = $(this);
if (card.hasClass("flipped")) return;
console.log(this);
card.addClass("flipped");
});
.wrapper {
display: flex;
}
.wrapper > .card {
flex: 1;
text-align: center;
line-height: 50px;
font-size: 30px;
}
.card.flipped {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
</div>
Other option is using event delegation where you bind the event to the parent and element and have jQuery do the checking if the class is added yet.
$(".wrapper").on("click", ".card:not('.flipped')", function() {
console.log(this);
var card = $(this);
card.addClass("flipped");
});
.wrapper {
display: flex;
}
.wrapper > .card {
flex: 1;
text-align: center;
line-height: 50px;
font-size: 30px;
}
.card.flipped {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
</div>
Apply the click event to all cards.
On click, check if the card is flipped. If it is, do nothing.
Cache your jQuery objects.
$(".card").on("click", function() {
const $card = $(this);
if ($card.hasClass("flipped")) return;
$card.toggleClass("flipped");
// .........
});
you have to check it inside your event 'click'. if the card has class 'flipped' break it
$(".card").on("click", function () {
if($(this).hasClass('.flipped')) return;
$(this).toggleClass("flipped");
if (first) {
firstCard = $(this).attr("game");
first = false;
} else {
secondCard = $(this).attr("game");
first = true;
checkGame();
}
});

Pure JS // Hide div when another divs class has been changed

Note: I can't use jQuery, only vanilla javascript
I'm not really fluent in pure JS. And this time I can't use any external resources (like jquery).
What I need:
If div1 class is active, hide text2
If div2 class is active, hide text1
I made it somehow to work, but my JS doesn't trigger when the class changes dynamic with another javascript code.
Code that triggers the active class
function activeClass(elem) {
var a = document.getElementsByClassName('item')
for (i = 0; i < a.length; i++) {
a[i].classList.remove('active')
}
elem.classList.add('active');
}
Code that should trigger hide/show when the class changes
if (document.querySelector(".text2").classList.contains("active")) {
document.getElementsByClassName('text1s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text2s')[0].style.visibility = 'visible';
}
if (document.querySelector(".text1").classList.contains("active")) {
document.getElementsByClassName('text2s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text1s')[0].style.visibility = 'visible';
}
What did I do wrong?
Codepen demo
Place your conditions inside click handler.
Add inline visibility style for inactive element
function activeClass(elem) {
var a = document.getElementsByClassName('item')
for (i = 0; i < a.length; i++) {
a[i].classList.remove('active')
}
elem.classList.add('active');
if (document.querySelector(".text2").classList.contains("active")) {
document.getElementsByClassName('text1s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text2s')[0].style.visibility = 'visible';
}
if (document.querySelector(".text1").classList.contains("active")) {
document.getElementsByClassName('text2s')[0].style.visibility = 'hidden';
document.getElementsByClassName('text1s')[0].style.visibility = 'visible';
}
}
body {
margin: 3em;
}
.item {
cursor: pointer;
}
a {
padding: 10px;
}
.active {
color: red;
border: 1px solid red;
}
<a class="item text1" onclick="activeClass(this)">show text</a>
<a class="item text2 active" onclick="activeClass(this)">hide text</a>
<br>
<br>
<h1 class="text1s" style='visibility:hidden;'>TEXT 1</h1>
<h1 class="text2s">TEXT 2</h1>
Updated Codepen

How to use the jQuery Selector in this web application?

I am trying to work out to select a delete icon in my own web application. delectIcon
HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
<ul>
<li>
<span class="itemLeft">Answer emails</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">1</span>
<b class="deleteIcon"> X </b>
</li>
<li>
<span class="itemLeft">Prep for Monday's class</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">5</span>
<b class="deleteIcon"> X </b>
</li>
</ul>
</div>
</div>
</main>
JavaScript
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});
I failed to do so by writing it myself. So I used Chrome Web Developer Tool to find the CSS path. I tried to use the XPath($"[/html/body/main/div/div[2]/ul/li[ 1 ]/b]") and CSS Path ($"(pathbody > main > div > div.content > ul > li:nth-child(1) > b)"). Neither of them worked.
I tried to mark it with an ID and made only one "li" exists. The CSS selector worked all right. But when I clicked the deleteIcon$"(#deleteIcon)", nothing happened.
#deleteIcon{
float:right;
font-weight: bold;
padding: 0 3px 0 3px;
border-radius: 5px;
background: #ccc;
cursor: pointer;
margin-left: 5px;
font-size: 1.3em;
text-align: center;
}
I also tried to select my title. I found the following worked out.
$(".container h1").on("click", function () {
alert("Oh, no!");
return false;
});
I do not what to do now. Can anyone help me out here?
Thank you! I would be really appreciate if you can answer my question.
Adding more details:
I did actually add the deleteIcon into the HTML by JavaScript. I do not know whether this can have an effect on my selector.
Actual HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
</div>
</div>
</main>
JavaScript (The important part listed below)
function Item(name,dueDate,type){
this.name=name;//1
this.dueDate=dueDate;//input2
this.type=type;//3
};
$(".tabs a span").toArray().forEach(function (element) {
var $element = $(element);
// create a click handler for this element
$element.on("click", function () {
var $content,
$input,
$button,
i;
if ($element.parent().parent().is(":nth-child(1)")) {
// newest first, so we have to go through
// the array backwards
$content = $("<ul>");
for (i = Task.length-1; i >= 1; i--) {
// $buttondelete = $("<buttonDelete>").text("X");
var txt1 = Task[i].toStringName();
var txt2 = Task[i].toStringDate();
var txt3 = Task[i].toStringType();
//alert(txt3);
$content.append('<li> <span class="itemLeft">'+txt1+'</span> <span class="itemMiddle">'+txt2+'</span> <span class="itemRight">'+txt3+'</span><b class="deleteIcon"> X </b>');
}
}
$("main .content").append($content);
return false;
});
});
If you are creating the items inside ul dynamically you should bind the click event like this :
$(".content").on("click", ".deleteIcon", function()
{
alert("clicked") ;
return false;
}
) ;
The class selector starts with a . (just like the example you say you have that works).
Try
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});

Add div below another div

I have a requirement to add 5 divs one by one on each click of a div button. ( the new div should be added below the existing div)
I done the code, but the news ones are getting attached on the top of existing div. please help to correct this.
I have another button which removes the added divs one by one(new ones to be remove first)
here is my code.
<div class="clearFix"></div>
<div id="containershowmore" >
<div id="dragbtnmore" style="cursor: default;">Show more buttons</div>
<div id="dragbtnless" style="cursor: default;">Show Fewer buttons</div>
</div>
<div class="toAdd" style="display:none;" >
<div id="dragdashboardmain" style="cursor: pointer;">dash</div></div>
<div class="toAdd" style="display:none;" >
<div id="dragrcalendar" style="cursor: pointer;">Calendar</div></div>
<div class="toAdd" style="display:none;">
<div id="dragresourcelist" style="cursor: pointer;">Rlist</div></div>
<div class="toAdd" style="display:none;">
<div id="dragdailynotes" style="cursor: pointer;">D Notes</div></div>
<div class="toAdd" style="display:none;">
<div id="dragweeklynotes" style="cursor: pointer;">W Notes</div></div>
script:
$("#dragbtnmore").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'none') {
$(this).css('display', 'block');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'none') {
i++;
}
});
if (i == 5)
$('#dragbtnmore').click(function () { return false; });
});
$("#dragbtnless").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'block') {
$(this).css('display', 'none');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'block') {
i++;
}
});
if (i == 5)
$('#dragbtnless').click(function () { return false; });
$('#dragbtnless').click(function () { return true; });
});
$("#containershowmore").mouseleave(function () {
$(this).hide();
});
function showmore() {
document.getElementById('containershowmore').style.display = "block";
}
style:
#containershowmore
{
margin-top: -75px;position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float: right;
padding-left: 5px;
}
.toAdd
{
background-color: blue;
margin-top: -55px;
position: relative;
margin-bottom: 14px;
}
*I referred this Fiddle *
**Solution:
Thankyou Shivam Chopra for helping me . Thanks a TON!! :)
for others, HEre is the solution**
jsfiddle.net/coolshivster/YvE5F/12
Remove margin top from both the div.
#containershowmore
{
position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float:right;
padding-left: 5px;
}
#dragbtnmore{
margin-bottom:10px;
border:1px solid black;
}
.toAdd
{
height:20px;
width:70px;
background-color: blue;
position: relative;
margin-bottom: 14px;
}
Then, it will work accordingly.
Here, the code : http://jsfiddle.net/coolshivster/YvE5F/
I have rewritten your code according to your requirement.
Some explanation about the code
I have create a parent div element with id="Add-element" that covers every element which contains class .toAdd .
Then I created data attribute for every div containing class .toAdd .
Now, I display the element one by one. But after first element. Every other element will prepend on the parent div i.e., #Add-element class.
Now, the code which I have rewritten.
jsfiddle link : http://jsfiddle.net/YvE5F/10/

Categories

Resources