Hide Multiple Elements in html using javascript - javascript

I'd like to show/hide multiple ID of elements.
I have a problem with the javascript in my HTML file.
Here's the javascript:
<Script type="text/javascript" language="JavaScript"><!--
function HideContent(d){
document.getElementById(d).style.display = "none";
}
function ShowContent(d){
document.getElementById(d).style.display = "block";
}
//--></script>
And my HTML:
<div class = "left" id="colsxmenu">
<ul>
<li> ENGLISH
<li>FRENCH
Actually, if I select ENGLISH it works good hiding the colsxmenu, but what I need is if I select FRENCH it should hide more than only 1 elements.
I tried to add ('colsxmenu';'colsxmenu2'), but that didn't works.

You can pass an array of elements to your function
<div id="first">first</div>
<div id="second">second</div>
ENGLISH
<script>
function HideContent(obj) {
for (var i = 0; i < obj.length; i++) {
document.getElementById([obj[i]]).style.display = 'none';
}
}
</script>

Define your HideContent function to accept variable number of argument. It should be some thing like below to hide multiple elements.
<script>
function HideContent() {
if (arguments.length > 0){
for(var i=0; i < arguments.length; i++{
document.getElementById(arguments[i]).style.display = "none";
}
}
}
</script>
After that you can call it like
HideContent('colsxmenu');
HideContent('colsxmenu', 'uniqename');

Related

addEventListener is just running the function, not saving the function

So I am trying to set up a function that will hide and show certain parts of the page, without the use of any outside libraries with Javascript. My problem seems to be that addEventListener is not attaching the event listener to the DOM=object but just running it.
The parts on the site I am using are:
<a class="tab" href="#index" id="index">Weapons</a>
<a class="tab" href="#armor" id="armor">Armor</a>
<a class="tab" href="#items" id="items">Items</a>
<div id="index_content" class="tab_content">
This is the content to display in weapons
</div>
<div id="armor_content" class="tab_content">
Welcome to armor!
</div>
<div id="items_content" class="tab_content">
Items are probably the best of the tabs.
</div>
My Javascript is:
function clear(key){
"use strict";
key = String(key);
//hides all content in items
for (var i = 0; i < itemArray.length; i++) {
document.getElementById(itemArray[i]+"_content").style.display = "none";
}
//shows current item
document.getElementById(key).style.display = "block";
return;
}
function tabsInit(){
"use strict";
for(var i = 0; i < itemArray.length; i++){
document.getElementById(itemArray[i]).addEventListener("click",clear(itemArray[i]));
}
}
window.onload = function(){
"use strict";
tabArray = document.getElementsByClassName("tab");
//add Items into item array
for(var i = 0; i < tabArray.length; i++){
itemArray[i] = tabArray[i].id;
}
tabsInit();
}
You're assuming you need the ID to get to the bound element. You don't. Assign clear as the event handler, and use this inside the function, though I think you were setting the wrong item to "block".
Also, I'm not sure why you're creating an array of IDs. You can just use the list of elements directly, and create a similar list of the _content elements if needed.
Here's a rewrite of your code.
document.addEventListener("DOMContentLoaded", function() {
"use strict";
const tabArray = document.querySelectorAll(".tab");
const contentArray = document.querySelectorAll(".tab_content");
tabsInit();
function tabsInit() {
for (var i = 0; i < tabArray.length; i++) {
tabArray[i].addEventListener("click", clear);
}
}
function clear() {
//hides all content in items
for (var i = 0; i < contentArray.length; i++) {
contentArray[i].style.display = "none";
}
//shows current item
document.querySelector("#" + this.id + "_content").style.display = "block";
}
});
div[id$=_content]:not(:first-of-type) {
display: none;
}
<a class="tab" href="#index" id="index">Weapons</a>
<a class="tab" href="#armor" id="armor">Armor</a>
<a class="tab" href="#items" id="items">Items</a>
<div id="index_content" class="tab_content">
This is the content to display in weapons
</div>
<div id="armor_content" class="tab_content">
Welcome to armor!
</div>
<div id="items_content" class="tab_content">
Items are probably the best of the tabs.
</div>
use let to keep the variable i in the correct scope and use an anonymous function to call clear on it..
function tabsInit(){
"use strict";
for(let i = 0; i < itemArray.length; i++){
document.getElementById(itemArray[i])
.addEventListener("click",()=>clear(itemArray[i]));
}
}
You're assigning the function result as a event listener.
You should use a function instead:
.addEventListener("click", function() { clear(itemArray[i]); })
Now that will be called every time the event fires.
var demo = document.getElementById("demo")
demo.addEventListener("click",function(){
//code here
}
)
<button id="demo"></button>

getElementsByClassName doesn't work

I try to hide some HTML elements onload and then show and manipulate them. The code works fine when I use element's individual IDs with getElementById() method. But when I try to do it more efficiently using the classes, it doesn't work. Here is the code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body onload="HideModals()">
<p id="p1" class="MyModal99">1. I will disappear or not.</p>
<p id="p2" class="MyModal99">2. I will disappear or not.</p>
<button id="toggle">Toggle</button>
<button id="hide">Hide</button>
<script>
$(document).ready(function(){
$("#toggle").click(function(){
$("#p1").toggle();
});
$("#hide").click(function(){
$("#p2").hide();
});
});
</script>
<script>
function HideModals() {
//document.getElementById("p1").style.display = 'none';
//document.getElementById("p2").style.display = 'none';
document.getElementsByClassName("MyModal99").style.display = 'none';
}
</script>
</body>
</html>
You cannot apply properties in bulk like that. This is why using jQuery is preferred for things like this:
$('.MyModal99').css('display', 'none');
If you want to do this without jQuery:
var nodes = document.getElementsByClassName("MyModal99");
for(var i = 0; i < nodes.length; i++) {
nodes[i].style.display = 'none';
}
It's because getElementsByClassName() returns an array-like object of elements. You need to access a specific element in order to change the style object.
You could iterate over the elements:
var elements = document.getElementsByClassName("MyModal99");
Array.prototype.forEach.call(elements, function (el) {
el.style.display = 'none';
});
or:
var elements = document.getElementsByClassName("MyModal99");
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
document.getElementsByClassName returns an array, which doesn't have a "style" property. You need to iterate over the array:
function HideModals() {
//document.getElementById("p1").style.display = 'none';
//document.getElementById("p2").style.display = 'none';
var modals = document.getElementsByClassName("MyModal99");
for (var i=0; i < modals.length; i++) {
modals[i].style.display = 'none';
}
}
The issue here is that document.getElementsByClassName("MyModal99") returns a list of items, so you'd have to loop through them and apply your properties one at a time. Something like this:
var elements = document.getElementsByClassName("MyModal99");
for ( var e in elements ) {
e.style.display = "none";
}
If you need to support older browsers, do it the old fashioned way without a for..in loop:
var elements = document.getElementsByClassName("MyModal99");
for ( var i = 0 ; i < elements.length ; ++i ) {
elements[i].style.display = "none";
}
Thats because document.getElementsByClassName returns an array of nodes. You need to iterate each of the returned nodes to set their styles individually.
var eleArray = document.getElementsByClassName('MyModal99');
for(var i = 0; i < eleArray.length; i++) {
eleArray[i].style.display = 'none';
}
You can use a for loop to cycle through all of the elements in the collection returned by getElementsByClassName like this:
var results = document.getElementsByClassName("MyModal99");
for (var i = 0; i < results.length; i++) {
results[i].style.display = 'none';
}
working demo: http://jsfiddle.net/gratiafide/3qg308bq/2/
I had difficulties with this code because I didn't know how to name jQuery functions. Now i know. Here is the corrected code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
</head>
<body onload="HideModals()">
<p id="p1" class="MyModal99">1. I will disappear or not.</p>
<p id="p2" class="MyModal99">2. I will disappear or not.</p>
<button id="toggle">Toggle</button>
<button id="hide">Hide</button>
<script>
$(document).ready(function(){
$("#toggle").click(function(){
$("#p1").toggle(100);
});
$("#hide").click(function(){
$("#p2").hide(100);
});
});
function HideModals() {
$('.MyModal99').css('display', 'none');
}
</script>

Showing hidden div if checkbox is checked

I have two checkboxes. The checkBoxValidate function triggered by "onclick" assures that the two checkboxes cannot be both selected at the same time. The showMe function, also triggered by "onclick", displays a hidden div when check box is clicked. Everything just fine.
The problem:
When clicking on checkbox1 and then on checkbox2, the div triggered by checkbox1 is not automatically hidden. The idea is than when a checkbox is not selected the div triggered by it should not be visible... Please look at the demo.
Thank you!
DEMO:
http://jsbin.com/iNuPAREq/1/edit?html,js,output
HTML:
<form action="whatever" name="comanda11" method="post" onsubmit="return validate(this)">
<input type="checkbox" name="c1" onclick="showMe('content1'); checkBoxValidate(0);">
<input type="checkbox" name="c1" onclick=" showMe('content2'); checkBoxValidate(1);">
<div id="content1" style="display:none">
Content 1
</div>
<div id="content2" style="display:none">
Content 2
</div>
</form>
JS:
function showMe(box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
for (var i = 0; i < chboxs.length; i++) {
if (chboxs[i].checked) {
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
function checkBoxValidate(cb) {
for (j = 0; j < 8; j++) {
if (eval("document.comanda11.c1[" + j + "].checked") == true) {
document.comanda11.c1[j].checked = false;
if (j == cb) {
document.comanda11.c1[j].checked = true;
}
}
}
}
change the markup to use radio buttons, and remove the inline javascript:
<form action="whatever" name="comanda11" method="post">
<input type="radio" name="c1" data-rel="content1" />
<input type="radio" name="c1" data-rel="content2" />
<div id="content1" style="display:none">Content 1</div>
<div id="content2" style="display:none">Content 2</div>
</form>
then do
var elems = document.getElementsByName('c1');
for (var i=elems.length; i--;) {
if (elems[i].addEventListener) {
elems[i].addEventListener ('change',fn,false);
}else if (elems[i].attachEvent) {
elems[i].attachEvent ('onchange',fn);
}
}
function fn() {
var rel = this.getAttribute('data-rel');
document.getElementById(rel=='content1'?'content2':'content1').style.display = 'none';
document.getElementById(rel).style.display = 'block';
}
FIDDLE
If you just have to use checkboxes, here's a working solution:
var elems = document.getElementsByName('c1');
for (var i=elems.length; i--;) {
if (elems[i].addEventListener) {
elems[i].addEventListener ('change',fn,false);
}else if (elems[i].attachEvent) {
elems[i].attachEvent ('onchange',fn);
}
}
function fn() {
var rel = this.getAttribute('data-rel');
for (var i=elems.length; i--;) {
if (elems[i] != this) elems[i].checked = false;
var id = elems[i].getAttribute('data-rel');
document.getElementById(id).style.display = elems[i].checked ? 'block' : 'none';
}
}
FIDDLE
Not an elegant solution but it works for your situation
function showMe (box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
document.getElementById("content1").style.display = "none";
document.getElementById("content2").style.display = "none";
for(var i=0;i<chboxs.length;i++)
{
if(chboxs[i].checked)
{
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
The simplest way to get this to behave correctly is to set all divs to hidden before setting the div selected to block.
var divs = [document.getElementsByName("content1"),document.getElementsByName("content2")];
for(var i=0; i < divs.length; i++_ {
divs[i].style.display = 'none'
}
The above code should go above
document.getElementById(box).style.display = vis;
Note that There are much better ways to work with DOM elements. I would recommend looking into jQuery as a much simpler way of doing this. Also, manually building an array of two div elements is not the best way to do this, but I don't want to risk grabbing other divs that might be in your document.
In this situation, I set a global variable to the div being displayed at the time it is "unhidden". lets call it "lastdiv" as an example.
var lastdiv=false;
function showme(){
if(lastdiv){lastdiv.style.display='none';}
lastdiv=?????? // your code to find the div to unhide
lastdiv.style.display='block';
}
You have lots of other issues in your code to work out including the use of eval in a situation where it is clearly not warranted. There are better ways to do it without using eval.

drop down menu will not work

I have a drop down menu that is supposed to work with four different menu choices, each given the same class. But my code is not working. I want it to work with both chrome and IE. The situation where it crashes is in my init method. The console complains as following: Object # has no method 'getElementsByTagName'. Any solution ?
function hideorShowField(list) {
var nodes = list.getElementsByTagName("li");
for (i = 1; i < nodes.length; i++) {
if (nodes[i].style.display == 'none') {
nodes[i].style.display = 'block';
}
else {
nodes[i].style.display = 'none';
}
}
}
function init() {
var list = document.getElementsByClassName("undermeny");
list1.getElementsByTagName("li")[0].onclick = function () {
hideorShowField(list);
};
}
window.onload = init;
My html code:
<ul class="undermeny" >
<li>Opinion</li>
<li>Ledare</li>
<li>Aktuella frågor</li>
<li>Per T Ohlsson</li>
<li>Magda Forsberg</li>
</ul>
<ul class="undermeny" >
<li>Lokalt/Globalt</li>
<li>Malmö</li>
<li>Lund</li>
<li>Limhamn</li>
<li>Burlöv</li>
<li>Eslöv</li>
<li>Höör</li>
<li>Kävlinge</li>
<li>Lomma</li>
<li>Svedala</li>
<li>Staffanstorp</li>
<li>Trelleborg</li>
<li>Vellinge</li>
<li>Sverige</li>
<li>Öresund</li>
<li>Världen</li>
<li>Väder</li>
</ul>
<ul class="undermeny" >
<li>Ekonomi</li>
<li>Nyheter</li>
<li>Privata pengar</li>
<li>Börs</li>
<li>Fonder</li>
</ul>
<ul class="undermeny">
<li>Sport</li>
<li>Fotboll</li>
<li>Ishockey</li>
<li>Handboll</li>
<li>Fridrott</li>
</ul>
getElementsByClassName() returns a nodeList as well as getElementsByTagName(). So you probably need this:
list[0].getElementsByTagName("li")[0].onclick = function () {...};
Or you've to iterate over the listto attach eventhandlers to all 1st lielements within uls with class undermeny. That'll be something like this:
for (var n = 0; n < list.length; n++) {
list[n].getElementsByTagName("li")[0].onclick = function () {...};
}
list1 has not been initialized (although list has). Fix the typo, and then you can iterate over the items in list, calling getElementsByTagName() on each.

Show / hide several div

I use this script :
<script language="javascript">
function toggle() {
var ele = document.getElementById("mydiv");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
Called by :
echo '<a id="displayText" href="javascript:toggle();">show</a>';
i want to show / hide several div (not in a list or a form)
i try :
var ele = document.getElementById("mydiv", "mydiv2");
but it's showing and hidding only the first div
Description
This is not jQuery. You should use the jQuery functions to guarantee cross browser compatibilty.
Check out my sample and this jsFiddle
Sample
<div id="mydiv">test</div>
<div id="displayText">test2</div>
$(function() {
$("#displayText").click(function() {
$("#mydiv").toggle();
});
});
More Information
jsFiddle
jQuery.toggle()
jQuery.click()
The getElementById() function accepts a single argument, so you cannot pass it a list of ids. There are a number of options, I suggest two of them:
Use an array of divs and iterate through it, e.g.
var divs = [ 'mydiv1', 'mydiv2', ... ];
for ( var i = 0; i < divs.length; i++ ) {
var div = document.getElementById( divs[ i ] );
...
}
Use a library such as jQuery that lets you operate on lists of items easily. In that case you could mark all your divs with an appropriate class, e.g. myclass, and use something like:
$(".myclass").hide()
If you can use include jQuery in your page then use jQuery instead of pure javascript to make your life simpler. Try this
function toggle() {
var ele = $("#mydiv");
var text = $("#displayText");
if(ele.is(':visible')) {
ele.hide();
text.html("show");
}
else {
ele.show();
text.html("hide");
}
}
If you want to select multiple element in jQuyer then you can pass multiple selectors seperated by a comma.
var elems = $("#mydiv, #mydiv1, #mydiv2");
elems.show();//Will show all the selected elements
elems.hide();//Will hide all the selected elements
If you want to do it in plain javascript, you could try something like this:
<script type="text/javascript">
var elements = [ 'mydiv', 'mydiv2' ]
foreach ( elem in elements )
{
var e = document.getElementById(elem);
// show/hide here
}
</script>

Categories