Show/hide div with javascript - javascript

I have a menu which should show the sub-elements organised in a div when clicked.
I provide below the structure of the html
function showOrHide() {
if (window.innerWidth < 800) {
var div = document.getElementById("links");
if (div.style.display == "block") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
}
<li>
<div id="image" onclick="showOrHide()">
<span>Test1</span>
</div>
<div id="links">
<span>Test2</span>
</div>
</li>
<li>
<div id="image" onclick=" showOrHide()">
<span>Test3</span>
</div>
<div id="links">
<span>Test4</span>
</div>
</li>
I would like the div id="links" to be shown or hidden when I click on div id="image". I have the following javascript.
The problem that I face is that onclick javascript is showing all the divs id=links in the menu and I would like only the div links next to the div image to be shown. Example when I click on Test1 only Test2 should be shown.

Element IDs should be unique within the entire document.
You must try creating unique id per div.
function showOrHide(rowNum)
{ if (window.innerWidth < 800) {
var div = document.getElementById("links_"+ rowNum);
if (div.style.display == "block")
{
div.style.display = "none";
}
else
{
div.style.display = "block";
}
}
}
<li>
<div id="image_1" onclick="showOrHide(1)">
<span>Test1
</span></div>
<div id="links_1">
<span >Test2</span>
</div></li>
<li>
<div id="image_2" onclick=" showOrHide(2)">
<span>Test3
</span></div>
<div id="links_2">
<span >Test4</span>
</div></li>

Change id and structure accordingly.
<li>
<div id="image_1" onclick="showOrHide(1)">
<span>Test1
</span>
</div>
<div id="links_1">
<span >Test2</span>
</div>
</li>
<li>
<div id="image_2" onclick=" showOrHide(2)">
<span>Test3
</span>
</div>
<div id="links_2">
<span >Test4</span>
</div>
</li>
JavaScript:
function showOrHide(rowNumber)
{ if (window.innerWidth < 800) {
var div = document.getElementById("links_"+ rowNumber);
if (div.style.display == "block")
{
div.style.display = "none";
}
else
{
div.style.display = "block";
}
}
}

Just provide a parameter to your showOrHide function which will be the selector for your div and do the toggling to that selector. See the implementation below
<li>
<div id="image" onclick="showOrHide('#links_1')">
<span>Test1</span>
</div>
<div id="links_1">
<span >Test2</span>
</div>
</li>
<li>
<div id="image" onclick=" showOrHide('#links_2')">
<span>Test3</span>
</div>
<div id="links_2">
<span >Test4</span>
</div>
</li>
And the JS:
function showOrHide(divSelector)
{
var div = document.querySelector(divSelector);
if (div.style.display == "none")
{
div.style.display = "block";
}
else
{
div.style.display = "none";
}
}

var elems = document.getElementsByClassName("links");
Array.from(elems).forEach(v => v.addEventListener('click', function() {
this.parentElement.getElementsByClassName('links')[0].classList.toggle('hidden');
}));
.hidden {
display: none;
}
<li>
<div class="links">
<span>Test1 </span>
</div>
<div class="links">
<span>Test2</span>
</div>
</li>
<li>
<div class="links">
<span>Test3
</span></div>
<div class="links">
<span>Test4</span>
</div>
</li>

Your main issue here is that an element's id must be unique to that element. Other elements cannot have the same id. Instead, you can pass through the element into your showOrHide() method using this, and then get the next element using nextElementSibling. This will work provided your HTML structure is consistent:
function showOrHide(elem) {
if (window.innerWidth < 800) {
const div = elem.nextElementSibling;
if (!div.style.display || div.style.display == "block") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
}
<li>
<div id="image" onclick="showOrHide(this)">
<span>Test1</span>
</div>
<div class="links">
<span>Test2</span>
</div>
</li>
<li>
<div id="image" onclick=" showOrHide(this)">
<span>Test3</span>
</div>
<div class="links">
<span>Test4</span>
</div>
</li>

You can not use the same id lots of time on same HTML. Id attribute is unique, but you can use class.
You can use this code maybe it will help you.
<li>
<div class="image" onclick="showOrHide(this)">
<span>Test1
</span></div>
<div class="links">
<span >Test2</span>
</div></li>
<li>
<div class="image" onclick=" showOrHide(this)">
<span>Test3
</span></div>
<div class="links">
<span >Test4</span>
</div></li>
function showOrHide(element) {
if (window.innerWidth < 800) {
var div = element.closet(".links");
if (div.style.display == "block") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
}

Related

Javascript onclick show/hide for multiple rows (Dynamic content)

I'm having a list of users where the admin can approve/decline.For these two action i'm using show/hide oncllick the code works.But in multiple rows for any action button onclick it shows/hide the content.I want paticular row's action button 'ld show/hide the content,on click of that button.How can I solve this?
Here is My view code laravel blade,
<script>
function showhide() {
var div = document.getElementById("collapse1");
if (div.style.display !== "none")
div.style.display = "none";
else
div.style.display = "block";
}
</script>
Content:
<div>
<button href="#collapse1" class="btn btn-success nav-toggle" onclick="showhide()">Action</button>
</div>
#if($user->approved == 0)
<div id="collapse1" style="display:none">
<span>
<a href="{!! route('approve', ['id' => $user->id]) !!}"><img alt="" src="http://www.clker.com/cliparts/l/n/a/E/b/t/check-mark-button-hi.png"
style="height: 48px; width: 48px" /></a>
</span><br/>
#else
<span>
<a href="{!! route('decline', ['id' => $user->id]) !!}">
<img alt="" src="https://images.onlinelabels.com/images/clip-art/TzeenieWheenie/TzeenieWheenie_red_green_OK_not_OK_Icons_1.png"
style="height: 48px; width: 48px"/>
</a>
</span>
</div>
#endif
Script
#pushonce('custom-scripts')
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
#endpushonce
It conflict id
You need change id:
id="collapse1" => id="collapse{$user->id}"
js and html function like https://jsfiddle.net/ft9xprnb/3/ .You can see result by click link and content function edited: elem.getAttribute("href")
function showhide(elem)
{
console.log(elem.getAttribute("href"));
var div = document.getElementById(elem.getAttribute("href").replace("#", ""));
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
You can pass this in html
<button href="#collapse1" class="btn btn-success nav-toggle" onclick="showhide(this)">Action</button>
And then in JS
function showhide(elem)
{
var div = document.getElementById(elem.href.replace("#", ""));
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
This way the elem you will be passing to click will be the clicked element.
Try changing content to this
<div>
<button href="#collapse1" class="btn btn-success nav-toggle" onclick="showhide()">Action</button>
</div>
<div id="collapse1" style="display:none">
#if($user->approved == 0)
<span>
<a href="{!! route('approve', ['id' => $user->id]) !!}">
<img alt="" src="http://www.clker.com/cliparts/l/n/a/E/b/t/check-mark-button-hi.png" style="height: 48px; width: 48px"/>
</a>
</span>
<br/>
#else
<span>
<a href="{!! route('decline', ['id' => $user->id]) !!}">
<img alt="" src="https://images.onlinelabels.com/images/clip-art/TzeenieWheenie/TzeenieWheenie_red_green_OK_not_OK_Icons_1.png" style="height: 48px; width: 48px"/>
</a>
</span>
#endif
</div>

Show and hide hidden div with parent onclick event

I am trying to create a list of newsletter thumbnails that will show and hide with an onclick event of it's parent header. The function is called properly to show the list, but won't hide it again on a second click. I'm sure it's something simple I'm missing, but I am at a loss.
function showBabList() {
if (document.getElementById('bablist').style.display = "none") {
document.getElementById('bablist').style.display = "block";
} else {
document.getElementById('bablist').style.display = "none";
}
}
<h2 onclick="showBabList()">BITSandBYTES Newsletters</h2>
<div id="bablist" style="display: none;">
<ul>
<img src="images/thumbs/BITSandBYTES2017-07_thumb.png" class="babthumb" height="100px" width="75px">
<img src="images/thumbs/BITSandBYTES2017-08_thumb.png" class="babthumb" height="100px" width="75px">
</ul>
</div>
function showBabList() {
if (document.getElementById('bablist').style.display == "none") {
document.getElementById('bablist').style.display = "block";
} else {
document.getElementById('bablist').style.display = "none";
}
}
<h2 onclick="showBabList()">BITSandBYTES Newsletters</h2>
<div id="bablist" style="display: none;">
<ul>
<img src="images/thumbs/BITSandBYTES2017-07_thumb.png" class="babthumb" height="100px" width="75px">
<img src="images/thumbs/BITSandBYTES2017-08_thumb.png" class="babthumb" height="100px" width="75px">
</ul>
</div>
WRONG
if (document.getElementById('bablist').style.display = "none")
CORRECT
if (document.getElementById('bablist').style.display == "none")

Error with expanding divs

I have encountered a problem with expandable divs. Here is my code:
HTML:
<div>more...</div>
<div class="expand" style="display:none">
YO DAWgGG
</div>
JS:
<script type="text/javascript" charset="utf-8">
function showHide(elementid){
if (document.getElementsByClassName("expand").style.display == 'none'){
document.getElementsByClassName("expand").style.display = '';
} else {
document.getElementsByClassName("expand").style.display = 'none';
}
}
</script>
It says that expand is undefined. But I don't see why. What am I doing wrong? Same code works if i use an ID but i need this for more than one div.
Thanks!
You need to do document.getElementsByClassName("expand")[0] as getElementsByClassName returns an array of object.
function showHide(el){
if (document.getElementsByClassName(el)[0].style.display == 'none'){
document.getElementsByClassName(el)[0].style.display = '';
} else {
document.getElementsByClassName(el)[0].style.display = 'none';
}
}
<div>more...</div>
<div class="expand" style="display:none">
YO DAWgGG
</div>
Based on the existing markup. I recommend to use document.querySelectorAll, and instead of setting an elements style, toggle its class.
var links = document.querySelectorAll('.link');
for (var i=0; i<links.length; i++) {
links[i].addEventListener('click', function(e){
e.target.parentElement.nextElementSibling.classList.toggle('show');
})
}
.expand {
display: none;
}
.expand.show {
display: block;
}
<div><a class="link" href="#">more...</a></div>
<div class="expand">
YO DAWgGG 1111
</div>
<div><a class="link" href="#">more...</a></div>
<div class="expand">
YO DAWgGG 222
</div>
<div><a class="link" href="#">more...</a></div>
<div class="expand">
YO DAWgGG 333
</div>
document.getElementsByClassName returns you a HTMLCollection and not a HTMLElement and hence you cant use .style on the collection.
So, if you need to apply some styling on all elements of the collection, you need to iterate over and apply.
Here is what you could do.
document.addEventListener('DOMContentLoaded', function() {
let anchors = document.querySelectorAll(".more");
[].forEach.call(anchors, (anchor) => {
anchor.addEventListener("click", (event) => {
event.preventDefault();
let parent = event.target.parentNode;
let ele = parent.querySelector(".expand");
if (ele.style.display == 'none') {
ele.style.display = '';
} else {
ele.style.display = 'none';
}
})
})
});
<div><a class="more" href="#">more...</a>
<div class="expand" style="display:none">
YO DAWgGG
</div>
</div>
<div><a class="more" href="#">more-2-...</a>
<div class="expand" style="display:none">
YO DAWgGG-2
</div>
</div>

javascript How to get two toggles on a page to work independently

Hi i currently have two toggles, one is on the sidebar and one is in the main body. They currently work together which is annoying, even though i am using to different scripts. The scripts i am using at the moment for the toggles are almost identical, however, even when using completely different scripts they still work together.
what i mean by work together is when i click the toggle on the main body the side bar toggle reacts.
They are toggles which collapse on oclick.
<script>
var divs = ["Menu", "Add"];
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";
}
}
}
</script>
<script>
$(document).ready(function () {
// set up the click event
$('.body > a').on('click', function(){
$(this).next('div').siblings('div:not(#Menu)').hide("1");
});
// trigger orders which has id francc, not orders // .show("1") goes between $(this).next('div') + .siblings
// if i want a transition
$('#Menu').trigger('click');
// options include >>>, but it's slower // $('a[name="account"]').trigger('click');
});
</script>
<!-- sidebar toggle-->
<script>
var divs = ["Order", "Rest", "Franc"];
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";
}
}
}
</script>
<!-- Change color on click-->
<script>
$(document).ready(function() {
$('.sidebar h3').on('click', function() {
$('.sidebar h3').css('color', 'black');
$(this).css('color', 'red');
});
$('h3#open').trigger('click'); //Your account red on page load
});
</script>
<!--Your account toggle open on load -->
<script>
$(document).ready(function () {
// set up the click event
$('.sidebar > a').on('click', function(){
$(this).next('div').siblings('div:not(#Franc)').hide("1");
});
// trigger orders which has id francc, not orders // .show("1") goes between $(this).next('div') + .siblings
// if i want a transition
$('#francc').trigger('click');
// options include >>>, but it's slower // $('a[name="account"]').trigger('click');
});
</script>
<div class="sidebar">
<!-- Orders toggle-->
<a id="order" class="header" href="#" onclick="toggleVisibility('Order');"><h3 id="orderr">Orders</h3></a>
<div id="Order" style="display: none;">
<div>
<ul class="tabs">
<li id="order" class="Red">Overview</li>
</ul>
</div>
</div>
<!--Restaurant toggle-->
<a id="restt" class ="header"href="#" onclick="toggleVisibility('Rest');"><h3>Your Restaurants</h3></a>
<div id="Rest" style="display: none;"><div>
<ul class="tabs">
<!-- <li id="order" class="rred">restaurant</li>-->
<li id="order" class="rgreen">New restaurant</li>
</ul>
</div>
</div>
<!-- Account toggle-->
<a id="francc" name="account" class ="header" href="#" onclick="toggleVisibility('Franc');"><h3 id="open">Your Account</h3></a>
<div id="Franc" style="display: none;">
<div>
<ul class="tabs">
<li id="order" class="Blue" >Order History</li>
</ul>
</div>
</div>
</div>
<div id=body>
<!-- Menu toggle -->
<div class="container_head"> <!-- red header top of container-->
<a id="Menu" class="header" href="#" onclick="toggleVisibility('Menu');"><h3>Menu Section</h3></a>
</div>
<div id="Menu_form" style="display: none;">
<form id="MenuForm" action ="javascript:void(0);" method="POST">
<!-- <div class="field">-->
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Steaks pattern="[a-zA-Z]"
required tabindex="1">
<br>
<label for="Description">Description</label>
<input type="text" name="Description" id="Description" placeholder="Fresh USDA Choice steaks, seasoned with hickory-smoked sea salt." tabindex="2">
<br>
<div class="field">
<input type="submit" value="Save">
</div>
</form>
</div>
<a id="add_prod" class="header" href="#" onclick="toggleVisibility('Add');"><h3>Orders</h3></a>
<div id="add" style="display: none;">
</div>
Bringing together #j08691 and Leo Farmer's comments, you need to have unique IDs and function names. When you call toggleVisibility(...), it's going to call the second declaration of that method. Also, when you call document.getElementById(...) on something like "order", it's going to stop at the first instance it finds (In your case, the a tag).
Give your functions unique names, give your items unique IDs (if you want them to all do the same thing, you can look at using the same class for each item), and you should be in a better spot.

Show and hide images with next previous button using Javascript

I have four divs, each div contain images and contents. one next and previous button. at a time only div will show. on click of next the second div have to be shown and first will hide. same upto fourth div. Need to use pure Javascript. No jquery or javascript plugins is allowed.... :(. Can anyone help me to do this?.
Thanks!
My html Code:
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="container">
<div id="theProduct">
<div id="slides"> <img src="img/prev.jpg" width="29" height="29" alt="Arrow Prev"> <img src="img/next.jpg" width="29" height="29" alt="Arrow Next">
<!-- Show/hide Div strating here -->
<div class="slides_container">
<div class="div1">
<div class="img1">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
<div class="div2">
<div class="img2">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
<div class="div3">
<div class="img3">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
<div class="div4">
<div class="img4">
<div class="price">
<ul>
<li class="strike">Rs. 1300</li>
<li class="offer">Rs. 1050</li>
</ul>
<div class="buy">Buy Now</div>
</div>
</div>
</div>
</div>
<!-- Show/Hide Div ending here -->
</div>
<img src="img/example-frame.png" width="739" height="341" alt="Example Frame" id="frame"> </div>
</div>
</body>
</html>
Practical with this below
<style type="text/css" media="screen">
#container{position:relative;width:120px;height:120px;}
#container div{position:absolute;width:120px;height:120px;}
#box-red{background:red;}
#box-yellow{background:yellow;display:none;}
#box-green{background:green;display:none;}
#box-maroon{background:maroon;display:none;}
</style>
Javascipt
<script type="text/javascript">
var $c =0;
function next(){
var boxes = document.getElementsByClassName("box");
$c +=1;
if($c >= boxes.length) $c = 0;
for (var $i=0;$i<boxes.length;$i++){
boxes[$i].style.display = "none";
}
boxes[$c].style.display = "block";
return false;
}
function prev(){
var boxes = document.getElementsByClassName("box");
$c -=1;
if($c < 0) $c = (boxes.length-1);
for (var $i=0;$i<boxes.length;$i++){
boxes[$i].style.display = "none";
}
boxes[$c].style.display = "block";
return false;
}
</script>
HTML
<div id="container">
<div id="box-red" class="box">DIV1</div>
<div id="box-yellow" class="box">DIV2</div>
<div id="box-green" class="box">DIV3</div>
<div id="box-maroon" class="box">DIV4</div>
</div>
previous next
I think this is what you are loking for:
http://girlswhogeek.com/tutorials/2007/show-and-hide-elements-with-javascript
But you could put that in one function:
<script language="JavaScript">
function ShowHide(divId){
if(document.getElementById(divId).style.display == 'none')
{
document.getElementById(divId).style.display='block';
}
else
{
document.getElementById(divId).style.display = 'none';
}
}
</script>
function toggleImage(forwrad){
var imageConainer = document.getElementByID(Your Parent div id);
var images = imageContainer.childNodes;
var showIndex = '';
for(var i=0; i<images.length;i++){
if(images[i].style.display == 'block'){
images[i].style.display == 'none';
if(forwrad){
showIndex = 1+1;
}
else{
showIndex = 1-1;
}
}
}
images[showIndex].style.display = true;
}
technically it's possible with pure CSS as well. with the :target pseudo class. but that would pollute your url with # tags. But you may actually want that.
Also Selectivizr is a good polyfill for old browsers

Categories