Toggle visibility of the current element - javascript

I'm trying to write a function toggle_active to show the hidden content on a click, and collapse the content again on one more click. Sadly, it does not work. Could you help me modify it?
function toggle_active(this){
var x = this.nextSibling;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
};
}
.daccord_b{
display:none;
}
<header class="ca_h" onclick="toggle_active(this);">
<i class="i i-plus ca_hi"></i>
Title
</header>
<div class="had daccord_b">Hidden content</div>

Use method nextElementSibling to return the next element. And it is not necessary to use the if {} operator.
Don't use this for arguments in functions.
The more correct way for your task is method toggle(), which your class uses in css .daccord_b.
function toggle_active(el) {
var x = el.nextElementSibling;
x.classList.toggle("daccord_b");
}
.daccord_b {
display: none;
}
<header class="ca_h" onclick="toggle_active(this);">
<i class="i i-plus ca_hi"></i>
Title
</header>
<div class="had daccord_b">Hidden content</div>
Second solution using style.display.
function toggle_active(el) {
var x = el.nextElementSibling;
x.style.display = x.style.display === 'block' ? 'none' : 'block';
}
.daccord_b {
display: none;
}
<header class="ca_h" onclick="toggle_active(this);">
<i class="i i-plus ca_hi"></i>
Title
</header>
<div class="had daccord_b">Hidden content</div>

js:
function toggle_active(id){
var x = document.getElementById(id);
if (x.style.display === "none" || x.style.display === "") {
x.style.display = "block";
} else {
x.style.display = "none";
};
}
html:
<header class="ca_h" onclick="toggle_active('HiddenContent');">
toggle
</header>
<div class="had daccord_b" id='HiddenContent'>Hidden content</div>

You're having some syntax errors in this code. First, I suggest you name the function arguments something other than this because this is a reserved keyword in JavaScript.
Secondly, I recommend consulting with W3School with such simple problems before reaching out, as most of the time, there is a simple solution :)
Here's a link that solves exactly the problem you're describing.
https://www.w3schools.com/howto/howto_js_collapsible.asp
And, here's an example and how you can achieve this:
let content = document.getElementById("content");
function handleClick() {
if (content.classList.contains("hide")) {
content.classList.remove("hide");
} else {
content.classList.add("hide");
}
}
.my-content {
display: block;
}
.my-content.hide {
display: none;
}
<button onclick="handleClick()">Toggle</button>
<div class="my-content" id="content">Hello, some content</div>
EDIT If you decide to introduce jQuery to your project, you can achieve it even with fever lines of code:
$("[data-collapse]").on('click', function () {
let target = $(this).data('collapse');
$(target).toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-collapse="#content">Clicker</button>
<div id="content">
My Content
</div>
This makes it abstract and reusable, even allowing you to do things like separate containers:
$("[data-collapse]").on('click', function () {
let target = $(this).data('collapse');
$(target).toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-collapse="#target1">Collapse #1</button>
<button data-collapse="#target2">Collapse #2</button>
<div id="target1">
<h1>I'm Target #1</h1>
</div>
<div id="target2">
<h1>I'm target #2</h1>
</div>

It is a good practice to use an Event object in you handler function when you can. Please read this post then try fixing your code accordingly: What exactly is the parameter e (event) and why pass it to JavaScript functions?
More about Event.currentTarget here: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
function toggle_active(evt){
var x = evt.currentTarget.nextElementSibling;
x.classList.toggle('daccord_b');
}
.daccord_b {
display: none;
}
<header class="ca_h" onclick="toggle_active(event);">
<i class="i i-plus ca_hi"></i>
Title
</header>
<div class="had daccord_b">Hidden content</div>

Related

How do I create show/hide elements for different buttons?

HTML Code...the buttons interfere with each other. How can I fix this?
<button onclick="myFunction()" style="margin-left:50px;"> Click Here For Help </button> <br> <br>
<div id="help1">
<p> Help </p>
</div>
<button onclick="myFunction()" style="margin-left:50px;"> Click Here For Help </button> <br> <br>
<div id="help2">
<p> Help </p>
</div>
Javascript shown with ids for the different buttons. Onload section to hide the content on page
load.
<script>
function myFunction() {
var x = document.getElementById("help1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
window.onload = function() {
document.getElementById("help1").style.display = 'none';
};
</script>
<script>
function myFunction() {
var x = document.getElementById("help2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
window.onload = function() {
document.getElementById("help2").style.display = 'none';
};
</script>
One was is to simply pass the id of the element as an input to myFunction so the corresponding element can be retrieved from the document and set to display:none. This will save you from needing duplicate functions. Press the blue Run code snippet button below to see the results.
Method 1:
function myFunction(ID) {
var x = document.getElementById(ID);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
window.onload = function() {
document.getElementById("help1").style.display = 'none';
document.getElementById("help2").style.display = 'none';
};
<button onclick="myFunction('help1')" style="margin-left:50px;"> Click Here For Help </button> <br> <br>
<div id="help1">
<p> Help </p>
</div>
<button onclick="myFunction('help2')" style="margin-left:50px;"> Click Here For Help </button> <br> <br>
<div id="help2">
<p> Help </p>
</div>
Alternative Method:
This example reduces the amount of JavaScript but slightly increases the amount of HTML id tags and classes. It also incoporates some additional CSS. As suggested in the comment above this method uses:
• Event listeners
• Toggles a class using classList
function myFunction() {
document.getElementById("help" + String(this.id.split("_")[2])).classList.toggle("Display_It");
}
window.onload = function() {
document.getElementById("Toggle_Button_1").addEventListener("click", myFunction);
document.getElementById("Toggle_Button_2").addEventListener("click", myFunction);
};
#Toggle_Button_1,
#Toggle_Button_2 {
margin-left: 50px;
}
.Help_Panel {
display: none;
}
.Display_It {
display: block;
}
<button id="Toggle_Button_1"> Click Here For Help </button>
<br>
<br>
<div class="Help_Panel" id="help1">
<p>Help</p>
</div>
<button id="Toggle_Button_2"> Click Here For Help</button>
<br>
<br>
<div class="Help_Panel" id="help2">
<p>Help</p>
</div>

Problems with javascript event handler

I'm hoping this doesn't get marked as "duplicate", because I have reviewed several threads and followed the advice I found. I know I'm missing something simple, and need other eyes on this. I'm a newbie, so please bear with me. I am testing a simple button element that I have a click event handler on, but it is not working. It works inline with "onclick", but I am trying to avoid that. The simple html:
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
And the javascript:
<script>
document.getElementById("handler").addEventListener("click", display, true);
function display() {
if (document.getElementById("stringText").style.display === "block") {
document.getElementById("stringText").style.display = "none";
} else {
document.getElementById("stringText").style.display = "block";
}
};
</script>
I have the css that initially sets the "stringText" display as "none". I appreciate any assistance.
Probably your problem is related to the execution of that script while the document is being loaded.
Add this condition stringText.style.display === "" to show/hide the elements correctly.
An alternative is using the event DOMContentLoaded
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
document.getElementById("handler").addEventListener("click", display, true);
function display() {
var stringText = document.getElementById("stringText");
if (stringText.style.display === "block" || stringText.style.display === "") {
stringText.style.display = "none";
} else {
stringText.style.display = "block";
}
};
});
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
Please allow some delay to load the pages using window.onload events
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>
<script>
window.onload = function(){
document.getElementById("handler").addEventListener("click", display, true);
};
function display() {
if (document.getElementById("stringText").style.display === "block") {
document.getElementById("stringText").style.display = "none";
} else {
document.getElementById("stringText").style.display = "block";
}
};
</script>
If you make sure and set the initial display property to block it works fine. As an alternative, you could also try using jQuery, as I have in the snippet.
//with jquery
$(document).ready(function() {
$('#handler').on('click', function() {
$('#stringText').toggleClass('hide');
})
})
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id='handler'>Event</button>
</div>
<div id='stringText'>
<h4>Some Description</h4>
<p>
Some more information
</p>
</div>

Button click works on second click only

I have a button and a div under it, the button must show this div onclick, i wrote the function and everything is fine, but it works only on second click and i can't figure out why, here is my code:
function showDiv() {
var x = document.getElementById('myDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
<button type="button" class="btn btn-default" onclick="showDiv()">Show div</button>
<div id="myDiv">
test
test
test
test
test
test
</div>
To get the value that you apply via a stylesheet (or block) you need to use getComputedStyle(). document.getElementById('myDiv').style.display can only read inline styles.
function showDiv() {
var x = document.getElementById('myDiv');
if ( window.getComputedStyle(x, null).getPropertyValue("display") === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
<button type="button" class="btn btn-default" onclick="showDiv()">Show div</button>
<div id="myDiv">
test
test
test
test
test
test
</div>
You have set the style in css.So the value of x.style.display is not none initially.it wolud be empty.So set that style initially. or use getComputedStyle to get the CSS rule
function showDiv() {
var x = document.getElementById('myDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
<button type="button" class="btn btn-default" onclick="showDiv()">Show div</button>
<div id="myDiv" style="display:none;">
test
test
test
test
test
test
</div>
if the element's display is being inherited or being specified by a CSS rule, compute the style using getComputedStyle
function showDiv() {
var x = document.getElementById('myDiv');
if (getComputedStyle(x, null).display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
<button type="button" class="btn btn-default" onclick="showDiv()">Show div</button>
<div id="myDiv">
test
test
test
test
test
test
</div>
Setting CSS style does not pervade to x.style.display so when you click the first time x.style.display actually equals "", so it hits your else block and sets the style.display to none, 2nd time and it hits the first branch of the conditional and shows your div.
Either use computedStyle to grab the actual style, or, this would be a little easier using classes.
JS:
function show () {
var x = document.querySelector('#myDiv')
x.classList.toggle('show')
}
CSS:
.show {
display: 'block';
}
Classlist is supported for all modern browsers but some really old ones will struggle with it, although good polyfills exist.
Because div doesn't have display in style. You can add it manually:
function showDiv() {
var x = document.getElementById('myDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
<button type="button" class="btn btn-default" onclick="showDiv()">Show div</button>
<div id="myDiv" style='display:none'>
test
test
test
test
test
test
</div>
The problem with your code is that x.style.display corresponds with the display property attached inline to your element. It ignores your CSS selector, which means that x.style.display === 'none' is false the first time you run your function.
Inlining display:none would fix your problem :
<div id="myDiv">...</div> → → → <div id="myDiv" style="display:none;">...</div>
However, that's not the recommended approach here. A better way to achieve the desired result, would be to toggle a class :
document.getElementById('myButton').addEventListener('click', function() {
document.getElementById("myDiv").classList.toggle('hidden');
});
.hidden {
display: none;
}
<button id="myButton" type="button" class="btn btn-default">Show div</button>
<div id="myDiv" class="hidden">test test test test test test</div>

Multiple toggle links

I'm working with HTML and JavaScript and I need to make two instances of a toggle link. Here is my code for a single one:
<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "link1";
}
else {
ele.style.display = "block";
text.innerHTML = "link1";
}
}
</script>
<body> <a id="displayText" href="javascript:toggle()" style="font-size:160%;">link1</a>
<div id="toggleText" style="display: none; font-size:160%;"><p>paragraph1</p></div><br></body>
I need the two toggle links to independently show/hide different paragraphs of text when each one is clicked. How can I add a second instance below the first?
Add an event handler and a data-toggle-id attribute to each link. In your event handler, get the value of the data-toggle-id and use that to find the paragraph that you would like to show. Then use the toggle method of the element's classList to add/remove a class that shows the paragraph.
var links = document.querySelectorAll('[data-toggle-id]');
for (var ix = 0; ix < links.length; ix++) {
links.item(ix).addEventListener('click', function() {
document.getElementById(this.dataset.toggleId).classList.toggle('show');
});
}
.toggleText {
display: none;
}
.show {
display: block;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
<a data-toggle-id="paragraph1">link1</a>
<div class="toggleText" id="paragraph1">
<p>paragraph1</p>
</div>
</div>
<div class="container">
<a data-toggle-id="paragraph2">link2</a>
<div class="toggleText" id="paragraph2">
<p>paragraph2</p>
</div>
</div>
<div class="container">
<a data-toggle-id="paragraph3">link3</a>
<div class="toggleText" id="paragraph3">
<p>paragraph3</p>
</div>
</div>
If you hate for loops, you can use Nick's suggestion and convert the NodeList to and array and use the forEach method:
Array.prototype.slice.call(document.querySelectorAll('[data-toggle-id]')).forEach(function(element) {
element.addEventListener('click', function(){
document.getElementById(this.dataset.toggleId).classList.toggle('show');
});
});

In Javascript, is it possible to give tab an active style when it only unhides a div, instead of loading a new page?

I have Javascript tabs which show/hide divs instead of loading new pages. The tabs have a style which gives a hover effect. I now want to add an active style to match up with the curently visible div.
THE JAVASCRIPT, which does not work as it is from a version which loads pages:
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i < aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href) >= 0) {
aObj[i].className='active';
}
}
}
function showdiv(id){
document.getElementById(id).style.display = "block";
}
function hidediv(id){
document.getElementById(id).style.display = "none";
}
THE STYLE:
#pageAdmin { display:block; }
#userAdmin { display:none; }
THE HTML:
<ul id="nav">
<li><a onclick="showdiv('pageAdmin'); hidediv('userAdmin')"
href="#">Page Admin</a></li>
<li><a onclick="showdiv('userAdmin'); hidediv('pageAdmin')"
href="#">User Admin</a></li>
</ul>
<div id="pageAdmin">
<h1>Page admin</h1>
</div>
<div id="userAdmin">
<h1>User admin</h1>
</div>
This is my first question on SO, so I hope it is appropriate - please accept my apologies in advance if it is not!
Your setActive function isn't very helpful. And using location, href and hash it will be hard doing what you want.
You may change your script to
function showdiv(id){
var el = document.getElementById(id);
el.style.display = "block";
el.className = "active";
}
function hidediv(id){
var el = document.getElementById(id);
el.style.display = "none";
el.className = "";
}
Now it should do what you want.
However, you should take a look on jQuery.
Using jQuery you do eliminate the use of getElementById and you can much simpler attach an eventhandler for onclick's, as by using vanilla js. It is considered as bad practice to setup handlers in html attributes.
jQuery also handles you the splitting and joining the space separated className string, if you want to use multiple styles.
Using jQuery it looks like:
$("a", "#nav").click(function () {
var $navA = $(this);
var tabName = $navA.attr("data-tabName");
$(".tab").each(function () {
var $tab = $(this);
if ($tab.attr("id") === tabName) {
$tab.css({ display: 'block' }); // you may move this into active style
$tab.addClass("active");
$tab.removeClass("inactive");
}
else {
$tab.css({ display: 'none' }); // you may move this into inactive style
$tab.removeClass("active");
$tab.addClass("inactive");
}
});
});
The HTML for the jQuery example
<ul id="nav">
<li><a data-tabName="pageAdmin" href="#">Page Admin</a></li>
<li><a data-tabName="userAdmin" href="#">User Admin</a></li>
</ul>
<div class="tab" id="pageAdmin">
<h1>Page admin</h1>
</div>
<div class="tab" id="userAdmin">
<h1>User admin</h1>
</div>

Categories

Resources