Javascript: select multiple div ID's - javascript

I'm using the javascript from this answer but since I want it for multiple pages, sometimes with more or less divs to show/hide I would like to call the function without listing all divId's. I've tried applying the starts with selector and adding a class and calling the class but I can't make it work.
I also made a change to the divVisibility function (replacing the null to divId) because I want to always have one div visible. This works but it seems to me like the first function could be tightened because I have the same line for both if and else operations.
Any help appreciated.
Improving my question. Here's the script with my tiny edit on line 5 of the JS. It currently does work but I want to not have to include all div names ("Div1", "Div2", "Div3", etc) and check if it can be tightened any more.
var divs = ["Div1", "Div2", "Div3", "Div4"];
var visibleDivId = null;
function divVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = divId;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.buttons a {
font-size: 16px;
}
.buttons a:hover {
cursor:pointer;
font-size: 16px;
}
<div class="main_div">
<div class="buttons">
Div1 |
Div2 |
Div3 |
Div4
</div>
<div class="inner_div">
<div id="Div1">I'm Div One</div>
<div id="Div2" style="display: none;">I'm Div Two</div>
<div id="Div3" style="display: none;">I'm Div Three</div>
<div id="Div4" style="display: none;">I'm Div Four</div>
</div>
</div>

Here is an answer where the number of anchor (<a>) tags is derived from the number of div elements in your html body. No jQuery here either.
If you give <div class="buttons"> an id and each of the inner_div divs a common class, you can then select all of the inner_div elements by class name and generate an anchor tag for them.
You can then do away with the logic of which div is visible by just setting them all to style="display: none;" and then only setting style="display: block;" on the element matching the ID of the one you clicked on.
var divs = document.getElementsByClassName('invizdiv');
/*
This bit sets up your anchor tags dynamically depending on
how many divs you have with the class 'invizdiv'
*/
for (var i = 0; i < divs.length; i++) {
var listDivId = divs[i].id.slice();
var newAnchor = document.createElement('a');
newAnchor.innerHTML = listDivId;
newAnchor.className = "buttons";
newAnchor.href = '#';
newAnchor.setAttribute('targetdiv', listDivId);
// console.log(listDivId);
newAnchor.addEventListener('click', function(elem, event) {
// console.log(elem);
// console.log(event);
divVisibility(elem.target.getAttribute('targetdiv'));
});
document.getElementById('button_list').appendChild(newAnchor);
}
// here onwards is unchanged
var visibleDivId = null;
function divVisibility(divId) {
var div;
for (var i = 0; i < divs.length; i++) {
div = divs[i];
div.style.display = "none";
}
div = document.getElementById(divId);
div.style.display = "block";
}
.buttons a {
font-size: 16px;
}
.buttons a:hover {
cursor: pointer;
font-size: 16px;
}
<div class="main_div">
<div id="button_list" class="buttons">
<!-- We'll dynamically add here later -->
</div>
<div class="inner_div">
<div id="Div1" class="invizdiv">I'm Div One</div>
<div id="Div2" class="invizdiv" style="display: none;">I'm Div Two</div>
<div id="Div3" class="invizdiv" style="display: none;">I'm Div Three</div>
<div id="Div4" class="invizdiv" style="display: none;">I'm Div Four</div>
</div>
</div>

I see you work without jQuery so here is an answer without.
Loop over all inner_div children and hide them by default,
then show content div 1. Afterwards the hiding and showing is handled by the click handlers.
Ofcourse this is one way of doing it.
function hideAllContent(){
// loop over the inner_div children and hide them
Array.prototype.forEach.call(document.getElementById('inner_div').children, function(v){
v.style.display = 'none';
})
}
function divVisibility(divId){
var el = document.getElementById(divId);
if(el){
hideAllContent();
el.style.display = 'block';
}
}
hideAllContent();
divVisibility('Div1'); // open by default with this content
.buttons a {
font-size: 16px;
}
.buttons a:hover {
cursor:pointer;
font-size: 16px;
}
<div class="buttons">
Div1 |
Div2 |
Div3 |
Div4
</div>
<div id="inner_div">
<div id="Div1">I'm Div One</div>
<div id="Div2">I'm Div Two</div>
<div id="Div3">I'm Div Three</div>
<div id="Div4">I'm Div Four</div>
</div>

Related

change properties of two divs with one onclick and querySelectorAll()

I have multiple elements that are seperatet in two divs. The first div contains a Text and the second div a color.
When I click on one element the text and color should change and if I click it again it should change back.
The problem is that no matter which one I click, its always the last one which changes.
The HTML part:
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
The JavaScript part:
<script type='text/javascript'>
var box1Temp = document.querySelectorAll(".box1");
var box2Temp = document.querySelectorAll(".box2");
for (var i = 0; i < box1Temp.length; i++) {
var box1 = box1Temp[i];
var box2 = box2Temp[i];
box2.onclick = box1.onclick = function() {
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
}
</script>
It works, when I use only one div.
Then I can use 'this', instead of the 'box1' variable, to addres the right element.
But if I replace 'box1' with 'this' its still the text div that changes.
(I know it's obvious that this is happening, but I'm lost)
With a few small tweaks, this can be written a lot more cleanly:
// Capture click event for parent container, .toggle-set
for (const ele of document.querySelectorAll(".toggle-set")) {
ele.addEventListener("click", function() {
// Grab text and color elements
const textToggle = ele.querySelector(".toggle-text");
const colorToggle = ele.querySelector(".toggle-color");
// Toggle text
// NOTE: This could use further refinement with regex or something similar to strip whitespace before comparison
textToggle.textContent = textToggle.textContent == "Text1" ? "Text2" : "Text1";
// Toggle css classes
colorToggle.classList.toggle("colorGreen");
colorToggle.classList.toggle("colorRed");
});
}
.colorGreen { background-color: green; }
.colorRed { background-color: red; }
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
Your code is so confused
You were right for the this option.
you can do with simple onclick function :
function change(el){
box1 = el.querySelector('.box1');
box2 = el.querySelector('.box2');
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
I think following code snippet would help you to get your desired result
let box1 = document.querySelectorAll(".box1");
let box2 = document.querySelectorAll(".box2");
box1.forEach((b1,i) => {
b1.addEventListener("click",(ev) => {
ev.target.classList.toggle("colorGreen");
ev.target.classList.toggle("colorRed");
console.log(box2[i]);
if(ev.target.classList.contains("colorGreen")){
box2[i].textContent = "Text1";
}else{
box2[i].textContent = "Text2"
}
})
})

managing several show/hide divs

I have some scripts here that show and hide divs when click. Now what I need is to just only display one div at a time. I have a code that controls them all but its not working I don't know about much of javascript.
This is the first example of show/hide function that can be done simultaneously without hiding the other divs.
FIDDLE HERE
HTML:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" style="display:none;">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" style="display:none;">
<p>Content goes here.</p>
</div>
SCRIPT:
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
function HideAllShowOne(d) {
// Between the quotation marks, list the id values of each div.
var IDvaluesOfEachDiv = "idone idtwo uniquename1 uniquename";
//-------------------------------------------------------------
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/[,\s"']/g," ");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/^\s*/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/\s*$/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/ +/g," ");
var IDlist = IDvaluesOfEachDiv.split(" ");
for(var i=0; i<IDlist.length; i++) { HideContent(IDlist[i]); }
ShowContent(d);
}
The other fiddle I created would do what I need but the script seems not to be working. Fiddle here
Found the solution on my code thanks to #Abhas Tandon
Fiddle here the extra id's inside the IDvaluesOfEachDiv seems to be making some error with the codes.
If you are happy with IE10+ support then
function ReverseDisplay(d) {
var els = document.querySelectorAll('.toggle.active:not(#' + d + ')');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('active');
}
document.getElementById(d).classList.toggle('active')
}
.toggle {
display: none;
}
.toggle.active {
display: block;
}
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" class="toggle">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" class="toggle">
<p>Content goes here.</p>
</div>
I would suggest to use jQuery which is far easier.
Include thiswithin
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
HTML
<div id="id_one">Item 1</div>
<div id="content_one">
content goes here
</div>
<div id="id_two">Item 1</div>
<div id="content_two">
content goes here
</div>
Script:
$(function()
{
$("#content_one").hide();
$("#content_two").hide();
});
$("#id_one").on("click",function()
{
$("#content_one").slideDown("fast");
});
$("#id_two").on("click",function()
{
$("#content_two").slideDown("fast");
});
If you have a "Button" for every DIV inside your HTML - you can go by element index
var btn = document.querySelectorAll(".btn");
var div = document.querySelectorAll(".ele");
function toggleDivs() {
for(var i=0; i<btn.length; i++) {
var us = i===[].slice.call(btn).indexOf(this);
btn[i].tog = us ? this.tog^=1 : 0;
div[i].style.display = ["none","block"][us?[this.tog]:0];
}
}
for(var i=0; i<btn.length; i++) btn[i].addEventListener("click", toggleDivs);
.btn{/* Anchors Buttons */ display:block; cursor:pointer; color:#00f;}
.ele{/* Hidden Divs */ display:none;}
<a class="btn"> 1Click to show/hide.</a>
<div class="ele"><p>1Content goes here.</p></div>
<hr>
<a class="btn">2Click to show/hide.</a>
<div class="ele"><p>2Content goes here.</p></div>
<hr>

Make div in div clickable with Javascript

Have a problem and can't get to solve it. Tried to use QuerySelectorAll and comma separating with GetElementsByClassName, but that didn't work, so I am wondering how to solve this problem.
I have this HTML:
<div class="area">Test title
<div class="some content" style="display: none">blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
<div class="area">
Test title
<div class="some content">
blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
JS:
function areaCollapse() {
var next = this.querySelector(".content");
if (this.classList.contains("open")) {
next.style.display = "none";
this.classList.remove("open");
} else {
next.style.display = "block";
this.classList.add("open");
}
}
var classname = document.getElementsByClassName("area");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', areaCollapse, true);
}
http://jsfiddle.net/1BJK903/nb1ao39k/6/
CSS:
.two {
position: absolute;
top: 0;
}
So now, the div with classname "area" is clickable. I positioned the div with class "two" absolute and now the whole div is clickable, except where this other div is. If you click on the div with classname "two", it doesn't work (it does not collapse or open the contents). How can I make this work, without changing the structure?
One way is using a global handler, where you can handle more than one item by checking its id or class or some other property or attribute.
Below snippet finds the "area" div and pass it as a param to the areaCollapse function. It also check so it is only the two or the area div (colored lime/yellow) that was clicked before calling the areaCollapse.
Also the original code didn't have the "open" class already added to it (the second div group), which mean one need to click twice, so I change the areaCollapse function to check for the display property instead.
function areaCollapse(elem) {
var next = elem.querySelector(".content");
if (next.style.display != "none") {
next.style.display = "none";
} else {
next.style.display = "block";
}
}
window.addEventListener('click', function(e) {
//temp alert to check which element were clicked
//alert(e.target.className);
if (hasClass(e.target,"area")) {
areaCollapse(e.target);
} else {
//delete next line if all children are clickable
if (hasClass(e.target,"two")) {
var el = e.target;
while ((el = el.parentElement) && !hasClass(el,"area"));
if (targetInParent(e.target,el)) {
areaCollapse(el);
}
//delete next line if all children are clickable
}
}
});
function hasClass(elm,cln) {
return (" " + elm.className + " " ).indexOf( " "+cln+" " ) > -1;
}
function targetInParent(trg,pnt) {
return (trg === pnt) ? false : pnt.contains(trg);
}
.area {
background-color: lime;
}
.two {
background-color: yellow;
}
.area:hover, .two:hover {
background-color: green;
}
.some {
background-color: white;
}
.some:hover {
background-color: white;
}
<div class="area">Test title clickable 1
<div class="some content" style="display: none">blablbala NOT clickable 1
</div>
<div class="two">This should be clickable too 1</div>
</div>
<div class="area">Test title clickable 2
<div class="some content">blablbala NOT clickable 2
</div>
<div class="two">This should be clickable too 2</div>
</div>
<div class="other">This should NOT be clickable</div>
You need to find your two elements while you're binding classname, and bind that as well.
var classname = document.getElementsByClassName("area");
for(var i=0; i < classname.length; i++){
classname[i].addEventListener('click', areaCollapse, true);
var twoEl = classname[i].getElementsByClassName("two")[0];
twoEl.addEventListener('click', function(e) { console.log('two clicked'); });
}
If you want to use jQuery:
$('.two').click(function(){
//action here
});

Create a vertical toggle with height adjustment

I belive i am close. My toggle works perfectly horizontally however, not vertically. When my toggle is vertical the toggled information is only viewable under the 3rd toggle, not directly under its assigned toggle header(hope this makes sense - seen in coding) i can't seem to add a adjustable height for the toggle either, I've tired numerous ways none work. I want to make the height the height of the content. any help will be appreciated.
var divs = ["Soft", "Broch", "tut"];
var visibleDivId = null;
function toggleVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
a{
display: block;
}
soft
broch
tut
<div id="Soft" style="display: none;">Soft div</div>
<div id="Broch" style="display: none;">broch div</div>
<div id="tut" style="display: none;">tut div</div>
The toggle function works fine. Press one toggle the others are inactive. any suggestions will be extremely helpful
Isn't just changing the order in the dom enough?
soft
<div id="Soft" style="display: none;">Soft div</div>
broch
<div id="Broch" style="display: none;">broch div</div>
tut
<div id="tut" style="display: none;">tut div</div>

Setting background color of div on click

I have a set of dynamically generated div elements like:
<div on-click="selected">one</div>
<div on-click="selected">two</div>
<div on-click="selected">three</div>
<div on-click="selected">four</div>
<div on-click="selected">five</div>
<div on-click="selected">six</div>
<div on-click="selected">seven</div>
I want to change the background color of div on which it is clicked and lose it when another div is clicked.
I could achieve this using tabindex, but I want to retain it until I click it on the another div or clear it intentionally, which tabindex does not provide.
How can I acieve it using javascript?
<div class="radiodiv" onclick=selected(this)>one</div>
<div class="radiodiv" onclick=selected(this)>two</div>
<div class="radiodiv" onclick=selected(this)>three</div>
<div class="radiodiv" onclick=selected(this)>four</div>
<div class="radiodiv" onclick=selected(this)>five</div>
<div class="radiodiv" onclick=selected(this)>six</div>
<div class="radiodiv" onclick=selected(this)>seven</div>
<script>
var divItems = document.getElementsByClassName("radiodiv");
function selected(item) {
this.clear();
item.style.backgroundColor = 'red';
}
function clear() {
for(var i=0; i < divItems.length; i++) {
var item = divItems[i];
item.style.backgroundColor = 'white';
}
}
</script>
Put all Your 'divs' into one div which will be container.
Then, by js, loop trough them and set css for non-selected and different for selected.
code :
function sel(id) {
var divs=document.getElementById('container').getElementsByTagName('div'); //get all divs from div called container
for(var i=0;i<divs.length; i++) {
if(divs[i]!=id) { //if not selected div set .items css
divs[i].className='items';
}
}
id.className='selitem'; //set different css for selected one
}
/* css for non-selected div*/
.items
{
display:block;
width:200px;
background-color:white;
color:black;
cursor:pointer;
margin-bottom:5px;
}
.items:hover
{
background-color:blue;
color:white;
}
/* css for selected div*/
.selitem
{
display:block;
width:200px;
background-color:red;
color:yellow;
cursor:pointer;
margin-bottom:5px;
}
<div id="container">
<div class="items" onclick="sel(this)">one</div>
<div class="items" onclick="sel(this)">one</div>
<div class="items" onclick="sel(this)">one</div>
<div class="items" onclick="sel(this)">one</div>
<div class="items" onclick="sel(this)">one</div>
<div class="items" onclick="sel(this)">one</div>
<div class="items" onclick="sel(this)">one</div>
</div>
There is explanation in the code.
Try this:
<div onclick="selected(this)">one</div>
<div onclick="selected(this)">two</div>
<div onclick="selected(this)">three</div>
<div onclick="selected(this)">four</div>
<div onclick="selected(this)">five</div>
<div onclick="selected(this)">six</div>
<div onclick="selected(this)">seven</div>
<script>
function selected(element)
{
var divs=document.getElementsByTagName("div");
divs.forEach(function(i)
{
i.style.backgroundColor="auto";
});
element.style.backgroundColor="red";
}
</script>
FYI, without any loops.
var xxx = null;
function sel(element){
if(xxx != null){
xxx.className = "default";
}
element.className = "selected";
xxx = element;
}
The best way to do that, is called a function in JavaScript, onclick or another. In this function you can create your own code, try to change the CSS properties and you will change the background color.
One example that I created:
function onoverbut(elemento)
{
elemento.style.color= "silver";
elemento.style.fontSize= "25px";
}
name function: onoverbut
attribute: elemento, which is the class or id html, that you need to pass.

Categories

Resources