Toggling div visibility for a graph - javascript

I'm creating a flow graph using HTML, CSS and JS.
This is the fiddle:
http://jsfiddle.net/Newtt/HRedA/3/
This is my JS:
var flag = false;
function showdiv(id) {
var div = document.getElementById(id);
div.style.display = flag ? 'none' : 'block';
flag = !flag;
}
It shows the root node of the graph and has to be clicked on to increase the levels.
As you can see there are some issues regarding the number of clicks required to show the divs that are hidden. I would like some help to fix two things:
Number of clicks required
When I open stage two and stage three, clicking on stage one should collapse all the open stages. However, with the current code, that doesnt seems to be working.

By setting the display-flag on the actual element you will avoid toggling a global state:
function showdiv(id) {
var div = document.getElementById(id);
var divFlag = div.expandedFlag == true
div.style.display = divFlag ? 'none' : 'block';
div.expandedFlag = !divFlag;
}
Or even simpler by using the elements display-state to decide if show/hide:
function showdiv(id) {
var div = document.getElementById(id);
div.style.display = (div.style.display == 'block') ? 'none' : 'block';
}
Including Part 2:
For part two. Including a structure containing children nodes for recursive hiding:
function showdiv(id) {
var div = document.getElementById(id);
var hideFlag = (div.style.display == 'block');
div.style.display = (hideFlag ? 'none' : 'block');
if(hideFlag){hideChildren(id)}
}
var children = {
'two' : ['three-one','three-two']
};
function hideChildren(parent) {
if(children[parent] !== undefined){
for(var i = 0; i<children[parent].length; i++){
var id = children[parent][i]
document.getElementById(id).style.display = 'none';
hideChildren(id)
}
}
}

For part 2 I would again use the DOM to your advantage. I agree that if you intend to generate these dynamically it's going to take some rework of the DOM structure and code.
For this example however, I created the following JSFiddle
http://jsfiddle.net/HRedA/15/
<div class="wrapper">
<div class="stage-one">
<div class="box node-one"></div>
<div class="stage-two" id="two" style='display:none'>
<div class="box node-two">
<div class="stage-three-one" id="three-one" style="display:none;">
<div class="box node-four"></div>
<div class="box node-five"></div>
</div>
</div>
<div class="box node-three">
<div class="stage-three-two" id="three-two" style="display:none;">
<div class="box node-six"></div>
</div>
</div>
</div>
</div>
</div>
So the html above is reduced so it's not cluttering the page, but you'll notice that instead of all the elements being at the same level the nodes are structured inside of one another just like the flow diagram is structured. This means that when you hide a parent it will also hide it's children. This has the side-effect/feature of also remembering what you had expanded. For example if you hide the root and then show it again all your previous expansions will remain.
The reason this won't work dynamically is that all the lines and boxes are positioned by hand. I even had to move some around when they became children of other nodes.
Hope this helps.

Related

(Amateur issue) Need to create a function to reduce repetative code

Good evening folks!
I wrote a script that makes it possible to switch between "" pages by clicking on tabs (see image for example)
Problem: The code I've written is very repetative and noob-ish
I have tried writing switch and if/else loops to reduce redundancy, but I'm not good enough to make it.
Could someone help me out?
Thank you very much in advance!
//Getting HTML elements and adding eventListener to trigger function on-click
document.getElementById("archiveBtnOne").addEventListener("click", showFirstTask);
document.getElementById("archiveBtnTwo").addEventListener("click", showSecondTask);
document.getElementById("archiveBtnThree").addEventListener("click", showThirdTask);
document.getElementById("archiveBtnFour").addEventListener("click", showFourthTask);
let firstContent = document.getElementById("aOverviewOne");
let secondContent = document.getElementById("aOverviewTwo");
let thirdContent = document.getElementById("aOverviewThree");
let fourthContent = document.getElementById("aOverviewFour");
//Functions to show current object, and hide other stacked objects
function showFirstTask(){
document.getElementById("aOverviewOne").style.display = "block";
document.getElementById("aOverviewTwo").style.display = "none";
document.getElementById("aOverviewThree").style.display = "none";
document.getElementById("aOverviewFour").style.display = "none";
}
function showSecondTask(){
document.getElementById("aOverviewOne").style.display = "none";
document.getElementById("aOverviewTwo").style.display = "block";
document.getElementById("aOverviewThree").style.display = "none";
document.getElementById("aOverviewFour").style.display = "none";
}
function showThirdTask(){
document.getElementById("aOverviewOne").style.display = "none";
document.getElementById("aOverviewTwo").style.display = "none";
document.getElementById("aOverviewThree").style.display = "block";
document.getElementById("aOverviewFour").style.display = "none";
}
function showFourthTask(){
document.getElementById("aOverviewOne").style.display = "none";
document.getElementById("aOverviewTwo").style.display = "none";
document.getElementById("aOverviewThree").style.display = "none";
document.getElementById("aOverviewFour").style.display = "block";
}
archiveBtnOne represents 'jobb' with its matching colored div - and so on..
Each button is connected to a div with a matching background color
https://i.stack.imgur.com/5BRi9.jpg
Instead of working with id use a common class attribute on similar elements. This way you can easily select them as a collection and apply whatever action needed in a forEach loop.
//get all elements
const items = document.querySelectorAll('.clickable');
//apply event listener to all elements
items.forEach(item => item.addEventListener('click', func));
function func(event) {
//reset all elements
items.forEach(item => {
item.style.color = "black";
});
//apply change to clicked element
event.target.style.color = "blue";
}
<div class="clickable">one</div>
<div class="clickable">two</div>
<div class="clickable">three</div>
There are two main problems with your approach.
By using individual IDs for each element, you have to select them by hand one by one, which gets really verbose really quickly. Hiding each one of them individually requires n*n lines of code, which will get monstruously big really fast as the number of elements increase.
Each time you execute document.getElementById, then you ask Javascript to go all over the hole DOM and search for the designated element. This is very CPU intensive. You should do it once and reuse it, by storing it in a constant : const $elem1 = document.getElementById("elem1") and then reuse $elem1.
Better yet, instead of giving each element an individual name, give them all the same class name and work with that.
const $elems = Array.from(document.getElementsByClassName("elem"));
console.log("elems = ", $elems)
const clickHandler = event => {
$elems.forEach($e => $e.style.display = "none");
event.target.style.display = "block";
};
$elems.forEach($elem => $elem.addEventListener("click", clickHandler));
.elem{
cursor: pointer;
}
<div class="elem">Elem 1</div>
<div class="elem">Elem 2</div>
<div class="elem">Elem 3</div>
<div class="elem">Elem 4</div>
<div class="elem">Elem 5</div>
If including jQuery is an option, it gets even simpler :
const $allElems = $(".elem");
$allElems.click(function() {
$allElems.hide();
$(this).show();
})
.elem {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="elem">Elem 1</div>
<div class="elem">Elem 2</div>
<div class="elem">Elem 3</div>
<div class="elem">Elem 4</div>
<div class="elem">Elem 5</div>

Hide all elements within a class that don't match the ID of a variable

I have a site with tiles much like the Windows 10 Start menu.
I need these tiles to have fullwidth drop downs once clicked, I'll need the dropdown to close if the same tile is clicked again and I need one dropdown to close others if a different tile is clicked.
These tiles will have all sorts of names so I was hoping to create some javascript that would be dictated by the ID of the tile clicked.
Here's what I have so far:
<div id="gaming" class="box one-one blue" onclick="showSection(this);">
<div id="gaming-section" class="section">
<div id="marketing" class="box one-one blue" onclick="showSection(this);">
<div id="marketing-section" class="section">
function showSection(obj) {
var tileName =obj.getAttribute('id');
var sectionName =(tileName+'-section');
document.getElementById(sectionName).style.display = "block";
}
Any help would be much appreciated
exchange document.getElementById(sectionName).style.display = "block"; for this:
const elemStyle = document.getElementById(sectionName);
if (elem.style.display !== 'block') {
elem.style.display = 'block';
else {
const elements = document.getElementsByClassName('section');
elements.forEach(elem => {
elem.style.display = 'none';
}
}

Toggle icon flips no matter what section is opened

I am new to all of this so please excuse any misuse of terms.
I have added a toggle to my wordpress site to hide long sections of text and it seems to work just fine.
I wanted to add an arrow that flips depending on whether the section is open or not. My problem is the arrow flips back and forth no matter what section is toggled and I don't know how to fix that.
JS:
function toggle(id) {
var element = document.getElementById(id);
var text = document.getElementById("arrow");
if (element) {
var display = element.style.display;
if (display == "none") {
element.style.display = "block";
text.innerHTML = "▲";
} else {
element.style.display = "none";
text.innerHTML = "▼";
}
}
}
HTML:
<h4>Procedure</h4>
<h4 onclick="toggle('telnetPrint')">Telnet<a id="arrow">▼</a></h4>
<div id="telnetPrint" style="display: none;">
<ol>
<li>fjkldsaj;lkf</li>
</ol>
<h4 onclick="toggle('telnetPrint')">Hide -</h4>
</div>
<p> </p>
<h4 onclick="toggle('linuxPrint')">Linux Computer▼</h4>
<div id="linuxPrint" style="display: none">
<ol>
<li>fjkldsjfklsa</li>
</ol>
<h4 onclick="toggle('linuxPrint')">Hide -</h4>
</div>
If anyone can help, I'd greatly appreciate it.
p.s. no jQuery please
It looks like you are calling the same "arrow". You only have arrow set for Telnet. You can add an arrow as well to linuxPrint. I would ID them as :
<a id="arrowtelnetPrint"></a>
and
<a id="arrowlinuxPrint"></a>
That way you can use the "id" to change the correct one. Here is the jsfiddle:
https://jsfiddle.net/ezdrhLtr/2/
This will have the full code, with minor adjustments, that toggle both arrows.
var text = document.getElementById("arrow");
you are referencing an element with id 'arrow'. Everytime the toggle function is executed, you will flip the element with id 'arrow'. What you can do is pass a boolean value to know if its to be flipped or not
<h4 onclick="toggle('telnetPrint',true)">Telnet<a id="arrow">▼</a></h4>
and in your script
function toggle(id, flipOrNot) {
var element = document.getElementById(id);
var text = document.getElementById("arrow");
if (element) {
var display = element.style.display;
if (display == "none") {
element.style.display = "block";
if(flipOrNot){
text.innerHTML = "▲";
}
} else {
element.style.display = "none";
if(flipOrNot){
text.innerHTML = "▼";
}
}
}
}
for other elements, you can do
<h4 onclick="toggle('linuxPrint',false)">Hide -</h4>
to prevent flip

Changing Text in div without toggling Div Visiblity

In my Div (Code Below) there is an onClick function that triggers the visibility of a second div, and there is also a content edible in the div as well. When I click to change the text it also triggers the visibility of the second div. How would I change the code so that I can click the text without changing the second div's visibility?
<div class="div1" id ="div1" onclick="onStepClicked()" style ="text-align:center"><p contenteditable="true" >Step 1</p></div>
Function:
function onStepClicked() {
var elem = document.getElementById('div2');
if (Visible === true) {
elem.style.display = 'none';
Visible = false;
}
else {
if (Visible === false) {
elem.style.display = 'block';
Visible = true;
}
}
}
You may trigger the click on the Parent div only and exclude the click on child in jQuery like this:
$("#div1").click(function(){
$("#div2").css('visibility','hidden');
}).children().click(function(e) {
return false;
});
If you are not OK with jQuery and are after a JavaScript - only solution, please leave a comment and let me know.
UPDATE
If you are after a JavaScript solution, here U R:
HTML
<div id ="div1" onclick="onStepClicked()" >
<p id="editable" contenteditable="true">Step 1</p>
</div>
JS
function onStepClicked(){
document.getElementById('div1').onclick = function(e) {
if(e.target != document.getElementById('editable')) {
document.getElementById('div2').style.visibility = 'hidden';
}
}
}
Try using the element>element selector in your script. It will only affect the first child element and then stop from affecting sub-child elements.
Tutorial:
(http://www.w3schools.com/cssref/sel_element_gt.asp)

JavaScript onclick requires two clicks

My problem is that when onclicktriggers the toggleNew function it's not executing but when I click the div a second time it's executing just as it should...
HTML:
<div id="aside_main">
<div onclick="toggleNew();">click</div>
content
</div>
<div id="aside_new">
content
</div>
JS:
function toggleNew() {
var e = document.getElementById('aside_main');
var se = document.getElementById('aside_new');
if(e.style.display == 'block') {
e.style.display = 'none';
se.style.display = 'block';
} else {
e.style.display = 'block';
se.style.display = 'none';
}
}
CSS:
#aside_main {
display: block;
}
#aside_new {
display: none;
}
What is happening here and how can I make the function work the first time a user clicks the div?
This will not work properly because you are using following line inside 'div#aside_main' which is going to be hidden.
<div onclick="toggleNew();">click</div>
Try keeping it outside like this-
<div onclick="toggleNew();">click</div>
<div id="aside_main">
content
</div>
<div id="aside_new">
content2
</div>
Also in javascript it is not checking for 'e.style.display' first time in if condition.
Try using
if(e.offsetWidth > 0 || e.offsetHeight > 0){
e.style.display = 'none';
se.style.display = 'block';
}
else
{
e.style.display = 'block';
se.style.display = 'none';
}
You need to call the function like onclick="toggleNew();" in the div onclick. I just added your code in fiddle.
May not be the best answer, but the fix was to use inline css by style attribute.
Like this:
<div id="aside_main" style="display: block; border: 2px solid green;">
<div onclick="toggleNew();">click</div>
content
</div>
<div id="aside_new" style="display: none; border: 2px solid red;">
content
</div>
e.style.display represents the style of the element defined by the style attribute, it does not give you the computed style. to get the computed style use
if (window.getComputedStyle(e,null).getPropertyValue("display") == 'block){
I had the same double click required issue. I was using an internal style sheet which was correctly setting the display like this.
When loading the HTML file #YourID was not visible as expected.
#YourID {
display: none;
}
When clicking the button tied to the function I noticed that the first click set the inline display to style="display: none;". The second click set the inline style="display: block;" and of course then it displayed as expected.
I found that I needed to set the element directly inline with style="display: none;" and just removed the intern style sheet entry (Above "#YourID").
I'm doubtful that this is 100% the correct answer in every scenario but it would seem the underlying issue is caused by the element not being set in the appropriate initial state for the function to act on it properly.
https://jsfiddle.net/em05a1kf
<div id="YourID" style="display: none;">
<b>Super Hidden Content</b>
</div>
<button onclick="ToggleID('YourID');">Do Foo</button>
<script type="text/javascript">
function ToggleID(idname) {
var x = document.getElementById(idname);
(x.style.display === "none") ? (x.style.display = "block") : (x.style.display = "none");
return false;
}
</script>
In your condition : Use onclick="toggleNew();" // calling
This is the way to call a function.
And if you want to Pass the function then you use only toggleNew //passing
They are two different activities.
Here is another way of doing that. You just need to add two lines to your javascript code-
document.getElementById('aside_main').style.display='block';
document.getElementById('aside_new').style.display='none';
set initial display property in javascript. This will work fine.
One way (for me the simplest way) to solve this is by counting clicks.
For this purpose you set the new intiger variable click to 0 outside of your function toggleNew() and everytime you call your function you increase variable click for 1 like this:
<script> var click = 0;
function toggleNew() {
click = click +1;
var e = document.getElementById('aside_main');
var se = document.getElementById('aside_new');
if (click > 1) {
if(e.style.display == 'block') {
e.style.display = 'none';
se.style.display = 'block';
} else {
e.style.display = 'block';
se.style.display = 'none';
}
} else {
e.style.display = 'none';
se.style.display = 'block';
}
}
</script>

Categories

Resources