how to get clicked element from multiple class in javascript - javascript

I am polluting a div with the help of following codes every time the 'Add' button is clicked on the website.
const addClick = document.getElementById("addBtn");
addClick.addEventListener("click", () => {
addNote();
});
function addNote(){
const notes = document.getElementById("notes");
notes.innerHTML += `
<div class="note">
<div class="delete"><i class="fas fa-times"></i></div>
<button class="save"><i class="fas fa-check"></i></button>
<textarea type="text" class="text"></textarea>
</div>
`;
}
With this code, I am generating note(s) that has delete or save options. I want to know which class element was clicked. I want to do this with vanilla Javascript.

You can use event delegation:
add an event listener to the parent element or document and then check if the clicked element contains the class that you want to target.
You may need to also check if the element clicked is a child of the button (the icon)
document.addEventListener("click", function(event) {
var target = event.target;
if (isElement(target, 'delete')) {
console.log("delete button clicked", target.closest(".note"));
} else if (isElement(target, "save")) {
console.log("save button clicked", target.closest(".note"));
}
});
function isElement(element, className) {
return element.classList.contains(className) || element.closest(`.${className}`);
}
<div class="note">
<button class="delete"><i class="fas fa-times"></i>Delete</button>
<button class="save"><i class="fas fa-check"></i>Save</button>
<textarea type="text" class="text"></textarea>
</div>
<div class="note">
<button class="delete"><i class="fas fa-times"></i>Delete</button>
<button class="save"><i class="fas fa-check"></i>Save</button>
<textarea type="text" class="text"></textarea>
</div>
<div class="note">
<button class="delete"><i class="fas fa-times"></i>Delete</button>
<button class="save"><i class="fas fa-check"></i>Save</button>
<textarea type="text" class="text"></textarea>
</div>

Here is a snippet for your case.
HTML
<div id="app"></div>
JS
const appDiv = document.getElementById("app");
appDiv.innerHTML = `<h1>JS Starter</h1>`;
[1, 2, 3, 4].forEach((el, index) => {
const note = document.createElement("div");
appDiv.insertAdjacentElement("afterend", note);
note.classList.add("note");
note.addEventListener("click", () => {
appDiv.innerHTML = `<h1>Box number: ${index + 1}<h1>`;
});
});
CSS
.note {
border: 1px solid black;
height: 100px;
width: 100px;
margin: 10px;
}
.note:hover {
cursor: pointer;
}

Related

My active/disable Functionality no longer works after cloning

I'm using the clone method to duplicate a form. I'm adding and removing the active
class on the buttons but, once I clone the form, the duplicate buttons no longer
function because they share the same class as the original. I want the buttons to still
function regardless how many times I clone it. I used jQuery and JavaScript, and I'm
still new to programming. Can you please give me some ideas as to how to solve this.
Thanks in advance fellow developers.
Here is my HTML Code:
<div class="column-bottom phone">
<p class="para_txt">Phone</p>
<div id="main-wrapper">
<div id="wrapper_1" class="parentClass">
<div class="basic_infor">
<p>Select the nature of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_first_4 " >Private</button>
<button class="func_btns btn_second_4" >Work</button>
</div>
</div>
<div class="basic_infor">
<p>Select the type of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_5">Mobile</button>
<button class="func_btns btn_6 ">Telephone</button>
<button class="func_btns btn_7 ">Fax</button>
<button class="func_btns btn_8">Extension</button>
</div>
</div>
<div class="txt_area">
<input type="textarea" placeholder="+27 85 223 5258">
<span onclick="delete_el();">x</span>
</div>
</div>
</div>
<div class="btn_add">
<button class="repl_btns phone_repl" onclick="duplicate();">Add additional</button>
<p>Display on foreman contact list?</p>
<input type="checkbox" id="input_field" name="Phone_contact">
</div>
</div>
Here is my jQuery and JavaScript Code. I selected the class for the first button and
added a active class to it while removing the active class for the second button. I did
the same for the rest of the buttons.
//private btn
$(".btn_first_4").click(function () {
$(this).addClass("is_active");
$(".btn_second_4").removeClass("is_active");
});
//work btn
$(".btn_second_4").click(function () {
$(this).addClass("is_active");
$(".btn_first_4").removeClass("is_active");
});
//Bottom 5 btns
$(".btn_5").click(function () {
$(this).addClass("is_active");
$(".btn_6,.btn_7,.btn_8").removeClass("is_active");
})
$(".btn_6").click(function () {
$(this).addClass("is_active");
$(".btn_5,.btn_7,.btn_8").removeClass("is_active");
})
$(".btn_7").click(function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_8").removeClass("is_active");
})
$(".btn_8").click(function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_7").removeClass("is_active");
})
/*
Cloning Functions....
I tried to set the id of my new clone to "wrapper_2", but it only works when i clone it
once. I wanted to change the class attribute this way but I realize it wont work as
well. Please advise. Thanks
*/
function duplicate(){
const wrapper = document.getElementById("wrapper_1");
const clone = wrapper.cloneNode(true);
clone.id = "wrapper_2";
const main_wrapper = document.getElementById("main-wrapper");
main_wrapper.appendChild(clone)
}
function delete_el() {
const del_el = document.getElementById("wrapper_2");
del_el.remove();
}
Problems
If you use .cloneNode() any event handlers bound to the original will not carry over to the clone. Fortunately you are using jQuery which has it's own method .clone(). It has the ability to clone and keep event handlers, $(selector).clone(true) to copy with events and $(selector).clone(true, true) for a deep copy with events.
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
.clone()|jQuery API Documentation
Do not clone anything with an id, in fact you are using jQuery so don't use id at all. Convert every id to a class, it might feel like a lot of work but in the long run you'll be thankful you did.
Do not use inline event handlers
<button onclick="lame(this)">DON'T DO THIS</button>
This is especially important if you use jQuery which makes event handling incredibly easy to write and very versatile.
let count = 0;
$('output').val(++count);
$('.remove').hide();
$('.select button').on('click', function() {
const $old = $(this).parent().find('.active');
if (!$old.is(this)) {
$old.removeClass('active');
}
$(this).toggleClass('active');
});
$('.clear').on('click', function() {
$(this).parent().find('input').val('');
});
$('.remove').on('click', function() {
$(this).closest('.fields').remove();
let out = $.makeArray($('output'));
count = out.reduce((sum, cur, idx) => {
cur.value = idx + 1;
sum = idx + 1;
return sum;
}, 0);
});
$('.add').on('click', function() {
const $first = $('.fields').first();
const $copy = $first.clone(true, true);
$copy.insertAfter($('.fields').last());
$copy.find('output').val(++count);
$copy.find('.remove').show();
$copy.find('input').val('');
});
html {
font: 300 2ch/1.2 'Segoe UI'
}
fieldset {
min-width: fit-content
}
.fields {
margin-top: 1rem;
}
output {
font-weight: 900;
}
menu {
display: flex;
align-items: center;
margin: 0.5rem 0 0.25rem;
}
button,
input {
display: inline-block;
font: inherit;
font-size: 100%;
}
button {
cursor: pointer;
border: 1.5px ridge lightgrey;
}
.numbers {
display: flex;
align-items: center;
margin: 1rem 0 0.5rem -40px;
}
.clear {
border: 0;
font-size: 1.25rem;
line-height: 1.25;
}
.right {
justify-content: flex-end;
}
.left {
padding-left: 0;
}
.number-3 {
width: 9rem;
}
.number-1 {
width: 3rem;
}
[class^="number-"] {
font-family: Consolas
}
.clear {
border: 0;
background: transparent;
}
label+label {
margin-left: 6px;
}
button:first-of-type {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
button:nth-of-type(2) {
border-radius: 0;
}
button:last-of-type {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.active {
outline: 2px lightblue solid;
outline-offset: -2px;
}
#foreman {
transform: translate(0, 1.5px)
}
.btn.remove {
display: block;
border-radius: 4px;
float: right;
}
<form id='phone'>
<fieldset class='main'>
<legend>Add Phone Numbers</legend>
<section class='fields'>
<fieldset>
<legend>Phone Number <output value='1'></output></legend>
<button class='btn remove' type='button'>Remove</button>
<label>Phone number is used for:</label>
<menu class='purpose select'>
<button class="btn priv" type='button'>Private</button>
<button class="btn work" type='button'>Work</button>
</menu>
<label>Select the type of phone:</label>
<menu class='type select'>
<button class="btn mob" type='button'>Mobile</button>
<button class="btn tel" type='button'>Telephone</button>
<button class="btn fax" type='button'>Fax</button>
</menu>
<menu class='numbers'>
<form name='numbers'>
<label>Number:&ThickSpace;</label>
<input name='phone' class='number-3' type="tel" placeholder="+27 85 223 5258" required>
<label>&ThickSpace;Ext.&ThickSpace;</label>
<input name='ext' class='number-1' type='number' placeholder='327'>
<button class='btn clear' type='button'>X</button>
</form>
</menu>
</fieldset>
</section>
<fieldset>
<menu class='right'>
<button class='btn cancel' type='button'>Cancel</button>
<button class='btn done'>Done</button>
<button class='btn add' type='button'>Add</button>
</menu>
</fieldset>
<footer>
<menu>
<input id='foreman' name="contact" type="checkbox">
<label for='foreman'>Display on foreman contact list?</label>
</menu>
</footer>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
When load page , JS add event click for elements ( elements were created)
When you clone new elements ( those do not add event click) and event click of you not working on those elements
You are using Jquery then i suggest you code same as below :
$(document).on('click', ".btn_first_4", function () {
$(this).addClass("is_active");
$(".btn_second_4").removeClass("is_active");
});
//work btn
$(document).on('click', ".btn_second_4", function () {
$(this).addClass("is_active");
$(".btn_first_4").removeClass("is_active");
});
//Bottom 5 btns
$(document).on('click', ".btn_5", function () {
$(this).addClass("is_active");
$(".btn_6,.btn_7,.btn_8").removeClass("is_active");
})
$(document).on('click', ".btn_6", function () {
$(this).addClass("is_active");
$(".btn_5,.btn_7,.btn_8").removeClass("is_active");
})
$(document).on('click', ".btn_7", function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_8").removeClass("is_active");
})
$(document).on('click', ".btn_8", function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_7").removeClass("is_active");
})
function duplicate(){
const wrapper = document.getElementById("wrapper_1");
const clone = wrapper.cloneNode(true);
clone.id = "wrapper_2";
const main_wrapper = document.getElementById("main-wrapper");
main_wrapper.appendChild(clone)
}
function delete_el() {
const del_el = document.getElementById("wrapper_2");
del_el.remove();
}
.is_active {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="column-bottom phone">
<p class="para_txt">Phone</p>
<div id="main-wrapper">
<div id="wrapper_1" class="parentClass">
<div class="basic_infor">
<p>Select the nature of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_first_4 " >Private</button>
<button class="func_btns btn_second_4" >Work</button>
</div>
</div>
<div class="basic_infor">
<p>Select the type of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_5">Mobile</button>
<button class="func_btns btn_6 ">Telephone</button>
<button class="func_btns btn_7 ">Fax</button>
<button class="func_btns btn_8">Extension</button>
</div>
</div>
<div class="txt_area">
<input type="textarea" placeholder="+27 85 223 5258">
<span onclick="delete_el();">x</span>
</div>
</div>
</div>
<div class="btn_add">
<button class="repl_btns phone_repl" onclick="duplicate();">Add additional</button>
<p>Display on foreman contact list?</p>
<input type="checkbox" id="input_field" name="Phone_contact">
</div>
</div>

Make current selections visible through Javascript

To summarise the code, I have buttons that display different tabs when pressed. Within the tabs, there are more buttons that change the color of some div elements and only one tab can be opened at a time. All this works as it should for the most part.
All buttons had been using focus but I wanted to replace it with javascript so that the selection will be retained when clicking on different elements. No tabs should be visible if the current opened tab button is pressed like it does when the code first runs.
I have had a few issues trying to get this to work properly. At the moment, the color buttons remain clicked. When tab toggles, the tab button loses selection and the tab div doesn't close when I click on the current selected tab's button.
https://jsfiddle.net/gkde169x/4/
<button class="tabButton" onclick="toggle_tab('tabOne');">Tab One</button>
<button class="tabButton" onclick="toggle_tab('tabTwo');">Tab Two</button>
<div id="tabOne" class="clickedTab" style="display: none;">
<br><br>
<div id="paletteOne">
<button class="paletteButton" style="background-color: blue"></button>
<button class="paletteButton" style="background-color: red;"></button>
<button class="paletteButton" style="background-color: yellow;"></button>
<button class="paletteButton" style="background-color: Green;"></button>
<button class="paletteButton" style="background-color: Orange;"></button>
<button class="paletteButton" style="background-color: white;"></button>
</div>
</div>
<div id="tabTwo" class="clickedTab" style="display: none;">
<br><br>
<div id="paletteTwo">
<button class="paletteButton" style="background-color: blue"></button>
<button class="paletteButton" style="background-color: red;"></button>
<button class="paletteButton" style="background-color: yellow;"></button>
<button class="paletteButton" style="background-color: Green;"></button>
<button class="paletteButton" style="background-color: Orange;"></button>
<button class="paletteButton" style="background-color: white;"></button>
</div>
</div>
<div id="change1"></div>
<div id="change2"></div>
<script type="text/javascript">
const divOne = document.getElementById('change1');
const divTwo = document.getElementById('change2');
document.querySelectorAll('#paletteOne button').forEach(function (el) {
el.addEventListener('click', function () {
divOne.style.backgroundColor = el.style.backgroundColor;
el.className = "paletteSelect";
});
});
document.querySelectorAll('#paletteTwo button').forEach(function (el) {
el.addEventListener('click', function () {
divTwo.style.backgroundColor = el.style.backgroundColor;
el.className = "paletteSelect";
});
});
function toggle_tab(id) {
const target = document.getElementById(id);
if (!target) {
return;
}
// Hide unselected tabs
const tabs = document.querySelectorAll('.clickedTab');
for (const tab of tabs) {
tab.style.display = 'none';
}
// Show current tab
target.style.display = 'block';
}
What's the best way to accommodate this in my code?
to unclick the color button I would do something like this, (with each click check for clicked buttons and unclick)
const pal = document.getElementById('paletteOne')
pal.addEventListener('click', function(e) {
document.querySelectorAll('#paletteOne button').forEach(function(el) {
el.className = "paletteButton"});
if(e.target.className==="paletteButton"){
divOne.style.backgroundColor = e.target.style.backgroundColor;
e.target.className = "paletteSelect";
}
});
to hide selected tab when clicked on
const tabs = document.querySelectorAll('.clickedTab');
for (const tab of tabs) {
if(tab!== target || target.style.display === 'block'){
tab.style.display = 'none';
}else{
target.style.display = 'block';}
}
obviously these things can be done differently, I'm just working off your code...
In your javascript
function toggle_tab(id) {
const target = document.getElementById(id);
if (!target) {
return;
}
const tabShown = document.querySelectorAll('.show')
tabShown.forEach((tab) => {
if(target != tab) tab.classList.remove('show')
})
target.classList.toggle('show');
}
Also in your CSS use classes. (You can create one class and give it to both of them since they have so many styles in common and use tabTwo and tabOne classes only for differences.)
.tabContainer {/*here use this class, give this to both tabs*/
position: absolute;
margin-top: 38px;
height: 100px;
width: 100px;
padding-left: 50px;
padding-bottom: 50px;
border-style: solid;
border-color: black;
background: white;
display:none;/*here*/
}
.tabTwo {/*here use class*/
margin-left: 20px;
}
.show{
display:block;
}

update row striping after removing element

I am making a todo-list. And I added row striping on it, which worked.
Now when I delete a task it should update the row striping, which it does not. After deleting an element instead of being eg. white white beige it should update to white beige white.
I have a tried a lot of things but I couldn't get anything to work. To be fair I am new to all of this and not quite experienced in working with row striping.
Is there even a way to do it?
Here is what I have so far:
loadEvents();
function loadEvents() {
document.querySelector('form').addEventListener('submit', submit);
document.querySelector('ul').addEventListener('click', deleteOrTick);
}
function submit(a) {
a.preventDefault();
let input = document.querySelector('input');
if (input.value != '')
addTask(input.value);
input.value = '';
}
function addTask(task) {
let ul = document.querySelector('ul');
let li = document.createElement('li');
li.innerHTML = `<div class="input-group mb-3 row"><div class="col-11"><label>${task}</label></div>
<span class="delete">x</span></div>`;
ul.appendChild(li);
document.querySelector('.allToDos').style.display = 'block';
}
function deleteOrTick(a) {
if (a.target.className == 'delete')
deleteTask(a);
}
function deleteTask(a) {
let remove = a.target.parentNode;
let parentNode = remove.parentNode;
parentNode.removeChild(remove);
event.stopPropagation();
}
ul {
list-style-type: none;
}
li {
font-size: 1.3em;
color: #2f4f4f;
}
.todo li:nth-child(2n) {
background: #e0d9c3;
}
.todo {
width: 500px;
}
.delete {
cursor: pointer;
}
<div class="container">
<form action="index.html" method="post">
<div class="heading">
<h1 class="header">ToDo-List</h1>
<p class="intro">Do what you do</p>
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" name="task" placeholder="Add a todo" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Add</button>
</div>
</div>
</form>
</div>
<div class="container">
<div class="allToDos ">
<ul class="todo">
<li>
<div class="input-group mb-3 row">
<div class="col-11">
<label>hi was geht ab</label>
</div>
<span class="delete">x</span>
</div>
</li>
</ul>
</div>
</div>
deleteTask can be
function deleteTask(event) {
let remove = event.target.parentNode;
let parentNode = remove.parentNode;
remove.parentNode.remove();
event.stopPropagation();
}
document.querySelector('li').addEventListener('click',deleteOrTick); // not ul
function deleteTask(a){
let remove = a.currentTarget;
let parentNode = remove.parentNode;
parentNode.removeChild(remove);
a.stopPropagation(); //not event
}

JS remove div with button after cloning

I have problem with removing div containing button. First I clone and add button, then change its class from 'add' to 'remove'. Then I try to remove div containing button with 'remove' but I can't access remove functions.
<div class="margin"></div>
<div class='new'>
<button type="button" class="btn btn-success add"><i class="fas fa-plus"></i></button>
</div>
<script>
$(document).ready(function() {
var div = document.getElementById('new');
$(".add").click(function(){
clone = div.cloneNode(true);
$(clone).insertAfter(".margin");
$("button.add:not(:last)).removeClass('add').addClass('remove');
$(".remove").click(function(){
console.log('inside')
//$(this).parent('div').remove();
});
});
</script>
document.getElementById('new') ... ur element does not have an ID. Its class-name is 'new' but not its ID. Some corrections should make it work:
$(document).ready(function() {
var div = document.getElementById('new');
$(".add").click(function(){
clone = div.cloneNode(true);
$(clone).insertAfter(".margin");
$("button.add:not(:last)").removeClass('add').addClass('remove');
$(".remove").click(function(){
console.log('inside')
//$(this).parent('div').remove();
});
})
});
.add {
background: green;
}
.remove {
background: red;
}
button {
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="new">
<button type="button" class="btn btn-success add">
<i class="fas fa-plus"></i> new
</button>
</div>
<div class="margin"></div>
Edit:
Is there a more elegant way to do this?
Maybe like so:
$('.add').on('click', function() {
$(this).clone()
.toggleClass('add remove')
.on('click', function() {
$(this).remove()
})
.prependTo('#new');
})
.add {
background: green;
}
.remove {
background: red;
}
button {
color: white;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="new">
<button type="button" class="btn btn-success add">
<i class="fas fa-plus"></i> new
</button>
</div>

Show a hidden div while making another hidden

I am looking for a way to toggle through three stacked div's where a button press will trigger an onclick function to make that specific div visible and hiding the others. I have included a jsfiddle below with the code I currently have any help on this would be amazing!
function togglediv(id1, id2, id3) {
var idOne = document.getElementById(id1);
var idTwo = document.getElementById(id2);
var idThree = document.getElementById(id3);
idOne.style.display = idOne.style.display == "block" ? "none" : "block";
idTwo.style.display = idTwo.style.display == "none";
idThree.style.display = idThree.style.display == "none";
}
<div class="table-responsive">
<button type="button" class="btn btn-primary" onclick="togglediv('inner-dung', 'inner-boss', 'inner-item')">
Dungeon
</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-boss', 'inner-dung', 'inner-item')">
Boss
</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-item', 'inner-dung', 'inner-boss')">
Item
</button>
</div>
<div id="search-dung">
<div id="inner-dung">
DUNGEON
</div>
<div id="inner-boss">
BOSS
</div>
<div id="inner-item">
ITEM
</div>
</div>
JSFiddle
You can pass the ID you want to show to the function, use a CSS class to toggle display: none/block, toggle that class on the element you click on and hide the rest by removing the class.
.table-responsive {
margin: 0px auto;
width: 90%;
}
#search-dung {
margin: 0px auto;
width: 90%;
height: 50%;
background-color: white;
border: 1px solid red;
}
#inner-dung,
#inner-item,
#inner-boss {
position: absolute;
margin: 0px auto;
width: 90%;
height: 50%;
background-color: white;
border: 1px solid red;
display: none;
}
#inner-dung.show,
#inner-item.show,
#inner-boss.show {
display: block;
}
<div class="table-responsive">
<button type="button" onclick="togglediv('inner-dung')">
Dungeon
</button>
<button type="button" onclick="togglediv('inner-boss')">
Boss
</button>
<button type="button" onclick="togglediv('inner-item')">
Item
</button>
</div>
<div id="search-dung">
<div id="inner-dung">
DUNGEON
</div>
<div id="inner-boss">
BOSS
</div>
<div id="inner-item">
ITEM
</div>
</div>
<script>
var els = document.getElementById('search-dung').getElementsByTagName('div');
function togglediv(id) {
var el = document.getElementById(id);
for (var i = 0; i < els.length; i++) {
var cur = els[i];
if (cur.id == id) {
cur.classList.toggle('show')
} else {
cur.classList.remove('show');
}
}
}
</script>
function togglediv(id1, id2, id3) {
var idOne = document.getElementById(id1);
var idTwo = document.getElementById(id2);
var idThree = document.getElementById(id3);
idOne.style.display = "block";
idTwo.style.display = "none";
idThree.style.display = "none";
}
https://codepen.io/anon/pen/NjOpJw
a couple of of problems there.
use onClick rather than onclick
idOne.style.display = idOne.style.display == "block" ? "none" : "block"; will return a boolean so you should change it for this
idOne.style.display = "block";
set your javascript to load in the body.
here's a working version
https://jsfiddle.net/83qwrk70/1/
You can use a switch case, passing only the element you want to show in toggle div
//index.html
<button type="button" class="btn btn-primary" onclick="togglediv('inner-dung')">
Dungeon
</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-boss')">
Boss</button>
<button type="button" class="btn btn-primary" onclick="togglediv('inner-item')">
Item </button>
//index.js
function show(el) {
el.style.display = 'block';
}
function hide(el) {
el.style.display = 'none';
}
function togglediv(selected) {
var idOne = document.getElementById('inner-dung');
var idTwo = document.getElementById('inner-boss');
var idThree = document.getElementById('inner-item');
switch(selected) {
case 'inner-dung': {
show(idOne);
hide(idTwo);
hide(idThree);
break;
}
case 'inner-boss': {
hide(idOne);
show(idTwo);
hide(idThree);
break;
}
case 'inner-item': {
hide(idOne);
hide(idTwo);
show(idThree);
break;
}
}
}
Here is another option that is scaleable:
var active = "inner-dung",
inactive = ["inner-boss", "inner-item"];
var toggleDiv = function (id) {
active = inactive.splice(inactive.indexOf(id), 1, active);
document.getElementById(active).style.display = "block"; // or use style sheet
for (var i = 0; i < inactive.length; i++) {
document.getElementById(inactive[i]).style.display = "none"; // or use style sheet
}
}
If there is no default active item, you can put "inner-dung" in the array as well. If you do that, the "inactive" array will receive "undefined" the first time, but it will not get in the way of the purpose.
You don't have to use a for-loop of course, but if you have more items you would.
"Teach your children well"
Apply a rule to the parent to influence the children.
document.querySelector( "form" ).addEventListener( "click", function( evt ) {
var n = evt.target.name;
if ( n ) {
document.querySelector( "#foobarbaz" ).setAttribute( "class", n );
}
}, false );
#foo,
#bar,
#baz {
display: none;
}
#foobarbaz.foo #foo,
#foobarbaz.bar #bar,
#foobarbaz.baz #baz {
display: block;
}
<div id="foobarbaz" class="foo">
<div id="foo">Foo!</div>
<div id="bar">Bar?</div>
<div id="baz">Baz.</div>
</div>
<form>
<input type="button" value="Foo" name="foo">
<input type="button" value="Bar" name="bar">
<input type="button" value="Baz" name="baz">
</form>

Categories

Resources