Confused getting a classname to hide a link - javascript

I had this code, that works ok to show/hide a second element by clicking the first one:
<script>
var acc = document.getElementsByClassName("movs-header");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
var x = this.nextElementSibling;
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
}
</script>
And this is the structure (they are repeating elements in a php system):
<div id="frm_container_[id]" class="movs-box">
<div class="movs-header">
some content here, clickable to show-hide the next sibling div
</div>
<div class="movs-body">
this content will show and hide
</div>
</div>
Now, I need to add this link inside a div with a class="movs-editlink", which has to be outside the movs-box div to refer the id "frm_container", in order to work.
Then the structure will be:
<div id="frm_container_[id]" class="movs-box">
<div class="movs-header">
some content here, clickable to show-hide the next sibling div
</div>
<div class="movs-body">
this content will show and hide
</div>
</div>
<div class="movs-editlink">[editlink label="edit" prefix="frm_container_"]</div> <!-- this div to show and hide along -->
(please don't mind the shortcode, it works fine)
What I need is to show/hide the last div with the same javascript code (when I click the "movs-header" div, but I fail to refer to "this.className", my guess was:
<script>
var acc = document.getElementsByClassName("movs-header");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
var x = this.nextElementSibling;
var xedit = this.getElementsByClassName("movs-editlink").classname;
if (x.style.display === "block") {
x.style.display = "none";
xedit.style.display = "none";
} else {
x.style.display = "block";
xedit.style.display = "block";
}
}
}
</script>
I believe this is not working because the last div is outside the scope of "this", then I think I need to find the NEXT div in the structure with the class "movs-link" to be included in the display toggle, am I right? But I can't find how. Please help.

Based on your markup, rather than getElementsByClassName from this, do it with this.parentNode.nextElementSibling
var xedit = this.parentNode.nextElementSibling;
Or with jquery's nextUntil
var xedit = $(this).parent().nextUntil( "movs-editlink" );

Related

Collapsible not Working [JSFiddle demo Included]

I am trying to get this collapsible to function normally and show the first set of information when the page is loaded, make it disappear when the user presses "read more", and show new information.
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function () {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
function display() {
var x = document.getElementById("cover");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
You are attaching the onclick=display() to all of your list elements. GetElementById is going to return the first element with the given id, in this case it's always targeting your first cover (if you're triggering that elsewhere in your script). So since every 'read more' list element has the onclick function calling display(), it is always hitting your first element (because it's the first element with the respective id). What you could do instead pass in the event then use 'closest' and pass in the id there (if your intention is to hide the image as well). If not you can remove the display() on the onclick there.
The other elements are working as expected but you don't see it because your css on the enclosing container is hiding it (if you check your inspector you will notice the css being set as expected). You might want to add an overflow scroll to scroll within the container limits to see your expanded data, or use something like css flex with minimum height in order to expand the container to see your read more data

Javascript - get class of another element with onclick

I want to individually toggle to different divs using the same function. Each of these divs has a common class and a different id. The function toggle is called using an onclick parameter on two separate <a> elements:
<a class="btn" id="btnOne" onclick="toggler();">Show/hide divOne</a>
<div class="box" id="divOne">
<a class="btn" id="btnTwo" onclick="toggler();">Show/hide divTwo</a>
<div class="box" id="divTwo">
I first tried to get these divs with getElementsByClassName but, as it returns an HTMLCollection, the script can't target each div individually.
So I tried to select the <a> tags ids (btnOne and btnTwo), but couldn't figure out how to retrieve the divs class using these ids (as we're talking about two different elements here).
In the end, I came back to the getElementById method, as I couldn't figure out how to select them based on their class:
function toggler() {
var id = document.getElementById("divId");
if (id.style.display === "none") {
id.style.display = "block";
} else {
id.style.display = "none";
}
};
This leaves me with two functions instead of just one. Any suggestion on how to target the two divs individually?
You can access the next sibling using nextElementSibling presuming the box will always be right after the hyperlink.
// Put the buttons into an array
const buttons = [...document.getElementsByClassName("btn")];
// Assing an event listener for every button
buttons.map(button => button.addEventListener("click", function(e) {
// Find the next sibling
const box = e.target.nextElementSibling;
// Toggle the display value
if (box.style.display === "none") {
box.style.display = "block";
} else {
box.style.display = "none";
}
}));
a {
display: block;
}
.box {
width: 5rem;
height: 2rem;
background-color: blue;
}
<a class="btn">Show/hide divOne</a>
<div class="box"></div>
<a class="btn">Show/hide divTwo</a>
<div class="box"></div>
There is a simple way to select the divs with their class name and you already used it.
The answer is getElementsByClassName. But in vanilla JS things are a little bit (over)complicated.
It will not target both divs individually. Instead, if you want to select the first div with this class you would do it like this:
getElementsByClassName('classname')[0]
If you want to select the second div you would use:
getElementsByClassName('classname')[1]
and so on. But there is a way of course.
You want to use loops:
var x = document.getElementsByClassName("classname");
for (var i = 0; i < x.length; i++) {
if (x[i].style.display === "none") {
x[i].style.display = "block";
} else {
x[i].style.display = "none";
}
}
In this way, you will target ALL divs with this class.
I'd dynamically add the events on the switches, using their classes. I added the class showHideDivBtn to them. To make sure you know which div you have to toggle, I used a data-id.
With addEventListener, I can use the event variable I named e. With this one, I have access to properties, such as the data-id I wrote.
let buttons = document.getElementsByClassName("showHideDivBtn");
for (let i = 0; i < buttons.length; ++i)
{
buttons[i].addEventListener('click', function(e)
{
let divToToggle = document.getElementById(e.srcElement.dataset.id);
if (divToToggle.style.display === "none")
divToToggle.style.display = "block";
else
divToToggle.style.display = "none";
});
}
<a class="btn showHideDivBtn" data-id="divOne" id="btnOne">Show/hide divOne</a>
<div class="box" id="divOne">One</div>
<br />
<a class="btn showHideDivBtn" data-id="divTwo" id="btnTwo">Show/hide divTwo</a>
<div class="box" id="divTwo">Two</div>
Use substr to get the word after extracting 'btn' from anchor id which will result in One or Two then while defining the if use "div"+word this will get the div by it is related a tag
function toggler() {
var word=this.id.substr(3);
var id = document.getElementById("div"+word);
if (id.style.display === "none") {
id.style.display = "block";
} else {
id.style.display = "none";
}
};

Javascript function for showing/hiding content of div on button click not working

Javascript newbie here. This is basically what I'm working with.
The function below is intended to hide everything enclosed in the newsDisplay class, but nothing happens when clicking the button that calls it.
function showHide() {
var x = document.getElementsByClassName('newsDisplay');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
.newsDisplay {
display: block;
}
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
Manually changing display: block; to display: none; behaves exactly as expected, so either the syntax or logic of the function is incorrect, or something is preventing the function from executing when clicking the button.
Could really use some help, thank you!
Try the first element of this class as follows
var x = document.getElementsByClassName('newsDisplay')[0];
Document document.single getElementsByClassName() will return an array of elements with the same class. It is different from document.getElementById() in so far as the latter returns a DOM object rather than an array of DOM objects.
As stated from it's name getElementsByClassName get elements (and not single element), so result of this function call is a collection of elements.
To access to first element of collection you can:
x = document.getElementsByClassName('newsDisplay')[0];
// or
X = document.getElementsByClassName('newsDisplay').item(0);
You can try a loop if you want multiple of the page. The key is you're grabbing a list of elements with the class, since classes aren't unique identifiers. You can either use my code below or switch it to an id and grab it by document.getElementById. Notice the s in document.getElementsByClassName
var x = document.getElementsByClassName('newsDisplay');
function showHide() {
for (var i = 0; i < x.length; i++){
x[i].style.display === 'none'
? x[i].style.display = 'block'
: x[i].style.display = 'none';
}
}
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
Try the code below.
Use this
var x = document.getElementsByClassName('newsDisplay')[0];
function showHide() {
var x = document.getElementsByClassName('newsDisplay')[0];
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
.newsDisplay {
display: block;
}
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
If you hit F12, navigate to the sources tab (on google chrome) you can set a breakpoint on your javascript function, your code is running, but you are getting a
Uncaught TypeError: Cannot read property 'display' of undefined
The reason for this is getElementsByClassName is returning a list of elements with that class selector, not just the one. If you want to just do this to the first element you can simply do:
function showHide() {
var x = document.getElementsByClassName('newsDisplay')[0];
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}

Button to show/hide div has to be pressed twice

My Goal: to have my div hidden on page load and show/hide the div with a button using only HTML/CSS/JavaScript.
I have set up a button in HTML and JavaScript to show/hide my div which works great when the div is visible on page load and not hidden using CSS. When I hide the div using CSS display: none; the div is hidden on page load but the button has to be clicked twice before the div becomes visible.
HTML:
<button class="btn btn-link" id="btnLink" onclick="hideLink()">Hide
Content</button> <br><br>
<div id="myLink">
<h1>Div content here</h1>
</div>
CSS:
#myLink {display: none;}
JavaScript:
function hideLink() {
var x = document.getElementById('myLink');
var b = document.getElementById('btnLink');
if (x.style.display === 'none') {
x.style.display = 'block';
b.childNodes[0].nodeValue="Hide Content";
} else {
x.style.display = 'none';
b.childNodes[0].nodeValue="Show Content";
}
}
You should check for !== 'block' rather than === 'none'
The value x.style.display is set to blank when we use none in the css as the css selector is what gets the none attribute than the element ( at lease that is what I understand ). So the check === none actually compares it will blank and return false ( x.style.display = '').
Now once we have set the value to block using JS the element's style.display property has a value which we can compare.
function hideLink() {
var x = document.getElementById('myLink');
var b = document.getElementById('btnLink');
if (x.style.display !== 'block') {
x.style.display = 'block';
b.childNodes[0].nodeValue = "Hide Content";
} else {
x.style.display = 'none';
b.childNodes[0].nodeValue = "Show Content";
}
}
#myLink {
display: none;
}
<button class="btn btn-link" id="btnLink" onclick="hideLink()">
Show Content
</button>
<br><br>
<div id="myLink">
<h1>Div content here</h1>
</div>
The first time the button is clicked, the element itself does not specifically have the style for display set. After your first if/then, then it does.
See here:
http://plnkr.co/edit/4peCJS1vhJskexqdLdKL?p=preview
var t = document.getElementById('output').innerText;
document.getElementById('output').innerText = JSON.stringify(x.outerHTML);
corrected it with another if...
function hideLink() {
var x = document.getElementById('myLink');
var b = document.getElementById('btnLink');
if (x.style.display === ''){
x.style.display = 'none';
}
if (x.style.display === 'none') {
x.style.display = 'block';
b.childNodes[0].nodeValue="Hide Sitemap Section";
} else {
x.style.display = 'none';
b.childNodes[0].nodeValue="Show Sitemap Section";
}
}

Nest jQuery Inside Javascript Function To Fade In Div From Display:None

I have a solution for revealing div's based on their ID, but I would like it to fade in.
Due to the complexity of the page and the fact that it is inside of WordPress I want to modify this DOM function to include a .show("slow") to make the fade in work vs. reengineering the entire page.
Here is the code:
CSS Block
<style>
.biobox { display:none;}
</style>
JavaScript That I Want To Insert jQuery Into To FadeIn
var divs = ["one", "two"];
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";
//the above line I want to swap with a jquery instance that includes .show("slow"), such as this code that does not work for me $(document).ready(function(){ $(div).show("slow"); });
} else {
div.style.display = "none";
}
}
}
</script>
DIV's That Are Hidden By Default
<div class="biobox" id="one">
<img src="http://deliveringhappiness.com/wp-content/uploads/2013/08/thought-leadership1.jpg" width="346" height="346" border="0" />
</div>
<div class="biobox" id="two">
<img src="http://www.traianbadulescu.ro/wp-content/uploads/2012/10/leaders.jpg" width="402" height="317" />
</div>
Code To Toggle DIV Visibility Of biobox
Close
Close
So how come $(document).ready(function(){ $(div).show("slow"); }); doesn't work in lieu of div.style.display = "block";? BTW I am inserting the jQuery onto the page prior to this code.
You'll need a different way of hiding your invisible div because you can't fade from display: none to another value for display, be it block, inline or inline-block.
You could transition the opacity or do something in combination with opacity, z-index or left/right offscreen hiding.

Categories

Resources