JS functions to remove two different classes interfering with one another [duplicate] - javascript

This question already has answers here:
How to call multiple JavaScript functions in onclick event?
(14 answers)
Closed 5 years ago.
I have two JS functions:
function myFunctionMenu() {
document.getElementById("main-menu").classList.toggle("shows");
}
and
function expandFunction() {
document.getElementById("menu-button").classList.toggle("expand");
}
Both of which toggle classes. Those classes have styles:
.shows {
margin-right: auto;
margin-left: auto;
display: block;
transition: all 2s ease;
}
and
.expand {
padding: 1% 20%;
background-color: #8c8c8c;
}
I then have two more functions, one for each of those original functions, which removes that class when clicking outside of the button that initiates both functions:
window.onclick = function(event) {
if (!event.target.matches('#menu-button')) {
var dropdowns = document.getElementsByClassName("house-menu");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('shows')) {
openDropdown.classList.remove('shows');
}
}
}
}
and
window.onclick = function(event) {
if (!event.target.matches('#menu-button')) {
var dropdowns = document.getElementsByClassName("dropbtn");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('expand')) {
openDropdown.classList.remove('expand');
}
}
}
}
The HTML follows, just in case:
<!doctype html>
<head>
<title>Site Photos</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="Styles/new-menu.css">
<script type="text/javascript" src="script/menu-scripts.js"></script>
</head>
<body>
<br>
<h1>
Name <br>
</h1>
<h2>
Site Photos
</h2>
<!--Menu-->
<div class="menu-container" div style="margin-left:auto; margin right:auto; margin-top:5%; margin-bottom:auto; width:40%;">
<!-- Main Menu Button -->
<div id="main-button-container" style="text-align:center; margin-top:-8%;">
<button onclick="myFunctionMenu();expandFunction()" class="dropbtn" id="menu-button"> Menu </button>
</div>
<hr>
<!-- Main Menu Container -->
<div id="main-menu" class="house-menu">
Main House <hr>
Car Barn <hr>
Utility Building <hr>
Central Plant <hr>
Exteriors<hr>
</div>
<hr>
</div>
</body>
</html>
The problem I am having is that I can only run one of the two "remove when click outside the button" functions at a time.
Can anyone explain to me why?
Thank you.

Because the first window.onclick will get overridden by the second one. Just like writing var a = 1; and later var a = 2;. You should use document.addEventListener for this purpose:
document.addEventListener("click", function(e){
if (!e.target.matches('#menu-button')) {
var dropdowns = document.getElementsByClassName("house-menu");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('shows')) {
openDropdown.classList.remove('shows');
}
}
}
});
and
document.addEventListener("click", function(e){
if (!e.target.matches('#menu-button')) {
var dropdowns = document.getElementsByClassName("dropbtn");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('expand')) {
openDropdown.classList.remove('expand');
}
}
}
});

Related

onClick event calling function, but not firing

Okay, so I'm getting a weird problem with my onClick elements.
I'm using PHP to echo some code, and here it is:
<div class = \"dropdown\">
<i id = \"elipses_$id\" onClick = \"dropDown_$id()\" style = \"color:#777\" class=\"fas fa-ellipsis-v\"></i>
<div id = \"dropdown_$id\" class = \"dropdown-content\">
[html code here isn't relevant]
</div>
</div>
When I open inspect element, and I click the button, it outputs the function name:
And when I type the function name into the console, the dropdown opens like it should. So why doesn't it do it when I click?
Not sure if it is needed, but here is the script I am using to open/close the dropdown.
function dropDown_$id() {
document.getElementById(\"dropdown_$id\").classList.toggle(\"show\");
}
window.onclick = function(event) {
console.log(event.target);
if (!event.target.matches('#dropdown_$id') && !event.target.matches('#elipses_$id')) {
var dropdown = document.getElementById(\"#dropdowm_$id\");
var c;
if(dropdown != null){
for (c = 0; c < dropdown.length; c++) {
var openDropdowns = dropdown[c];
if (openDropdowns.classList.contains('show')) {
openDropdowns.classList.remove('show');
}
}
}
}
}
EDIT: This is the raw HTML of the dropdown that is spat out after PHP is run:
<div id="dropdown_26" class="dropdown-content">
<div id="names" style="border-bottom: thin solid #BDBDBD;">
<h2 class="dropdown-contenth2">Francois van Kempen</h2>
<p style="color:grey;margin-top:-20px; margin-left: 16px;">#Bork_Bork</p>
</div>
div id="settings" style="border-bottom: thin solid #BDBDBD;">
<a id="a1" class="dropdown-contenta" href="settings.php">Accout Settings</a>
<form id="dark_mode_form" action="nightmode.php" method="POST" style="padding: 10px; display:flex;justify-content:flex-start;align-content:center">
<label style="" class="switch">
<input onchange="this.form.submit()" type="checkbox" name="darkmode" value="checked">
<span class="slider round"></span>
</label>
<p class="dropdown-contentp" style="margin:0;padding:0; margin-left:5px;margin-top:5px;">Night mode</p>
</form>
</div>
<a id="a2" class="dropdown-contenta" href="logout.php">Log out #Bork_Bork</a>
<a id="a3" class="dropdown-contenta" href="reset-password.php">Reset password #Bork_Bork</a>
</div>
EDIT 2: Added the raw script:
<script id="dropdown-settings" type="text/javascript">
function dropDown() {
document.getElementById("dropdown").classList.toggle("show");
}
function dropDown_26() {
document.getElementById("dropdown_26").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
console.log(event.target);
if (!event.target.closest('#dropdown') && !event.target.closest('#navPFP')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
if (!event.target.matches('#dropdown_26') && !event.target.matches('#elipses_26')) {
var dropdown = document.getElementById("#dropdowm_26");
var c;
if(dropdown != null){
for (c = 0; c < dropdown.length; c++) {
var openDropdowns = dropdown[c];
if (openDropdowns.classList.contains('show')) {
openDropdowns.classList.remove('show');
}
}
}
}
}
</script>

How to show emojis on my website?

When the user clicks the drop down menu, I want to show emojis. But the problem is the only way I know how to do that is to input an emoji one by one.
My question is how do I show all the emojis? I want to when the user clicks the drop down menu and when they click the emoji, add it to the text area.
home.php:
<textarea id="textf2" rows="3" maxlength="3000" placeholder="Enter text" cols="35">
</textarea>
<button id="bt6" type="submit" name="search">Post status</button>
<div class="dropdown" id="div1">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
Okay, I think this is what you want:
After looking here and tinkering with the code for an hour, I got this:
emojis = document.getElementById("myDropdown").getElementsByTagName("li")
for (var i = 0; i < emojis.length; i++) {
emojis[i].addEventListener("click", function() {
var smiley = this.innerHTML;
ins2pos(smiley, 'textf2');
});
}
function ins2pos(str, id) {
var TextArea = document.getElementById(id);
var val = TextArea.value;
var before = val.substring(0, TextArea.selectionStart);
var after = val.substring(TextArea.selectionEnd, val.length);
TextArea.value = before + str + after;
setCursor(TextArea, before.length + str.length);
}
function setCursor(elem, pos) {
if (elem.setSelectionRange) {
elem.focus();
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn') && !event.target.matches('#myDropdown li')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
#myDropdown {
display: none
}
#myDropdown.show {
display: block;
}
<textarea id="textf2" rows="3" maxlength="3000" placeholder="Enter text" cols="35">
</textarea>
<button id="bt6" type="submit" name="search">Post status</button>
<div class="dropdown" id="div1">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<ul id="myDropdown" class="dropdown-content">
<li>&#x1F601</li>
<li>&#x1F603</li>
<li>&#x1F605</li>
</ul>
</div>
JSfiddle and more emojis here
Hope that helps!
Update: To include images, you got to use <div id="textf2" contentEditable="true"></div> instead of the text area and use the code noted here
emojis = document.getElementById("myDropdown").getElementsByTagName("li")
for (var i = 0; i < emojis.length; i++) {
emojis[i].addEventListener("click", function() {
var smiley = this.innerHTML;
pasteHtmlAtCaret(smiley + " ");
});
}
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// only relatively recently standardized and is not supported in
// some browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn') && !event.target.matches('#myDropdown img')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
#myDropdown {
display: none
}
#myDropdown.show {
display: block;
}
#text_wrapper {
margin: 40px;
border: 1px solid #ccc;
}
#textf2 {
outline: none;
margin: 10px;
min-height: 100px;
}
img {
width: 50px;
height: auto;
}
<div id="text_wrapper">
<div id="textf2" contentEditable="true">
</div>
</div>
<button id="bt6" type="submit" name="search">Post status</button>
<div class="dropdown" id="div1">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<ul id="myDropdown" class="dropdown-content">
<li><img src="https://upload.wikimedia.org/wikipedia/commons/e/ec/Happy_smiley_face.png" /></li>
<li><img src="http://res.freestockphotos.biz/pictures/15/15550-illustration-of-a-yellow-smiley-face-pv.png" /></li>
<li><img src="http://res.freestockphotos.biz/pictures/15/15564-illustration-of-a-yellow-smiley-face-pv.png" /></li>
</ul>
</div>
EDIT: I misread the question, so I'll add in how I would do it:
I would create an array of Emoji characters. I would then loop over this array of emojis. For each emoji in the array you want to perform a 'map' operation so you get an HTML element. Then you want to append these elements to the dropdown-content element as children.
For example:
var emojis = ['😍','😀','🤑']; // put all emojis in here
emojis.map((character) => {
var a = document.createElement('a');
a.src='#';
a.textContent = character;
a.addEventListener(
'click',
function() { /* append character to the textarea. this will probably something simple like 'textareaElement.value += character */}
);
return a;
});
emojis.forEach((el) => dropDownContentElement.appendChild(el));

How can I update attributes with jQuery?

$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>
You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)
Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`

Apply a JavaScript function to all Array elements except the ith element

In one of my projects I made 3 galleries, I would like to put both of them on the same page in the same position, not at the same time, however. For this to be possible, I chose to create 3 buttons. When I click on the first button for example, the first gallery should appear (both galleries are initially on display:none), then when I click on the second button, the second one should appear and the one shown before should disappear, and so for each of the galleries. I made a simplified copy of the page to make the thinking easier.
In general, my problem is that I don't quite know how to apply a function to all the elements in an Array except for one element.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Galleries</title>
<link rel="stylesheet" type="text/css" href="gs.css">
<style type="text/css">
body{
background-color:royalblue;
}
header{
text-align: center;
}
article{
width:95%;
margin:auto 2.5% auto 2.5%;
height:850px;
background-color:tomato;
display:none;
}
</style>
</head>
<body>
<header>
<button>Third Gallery</button>
<button>Second Gallery</button>
<button>Third Gallery</button>
</header>
<section>
<article>
<h1>This is the first gallery</h1>
</article>
<article>
<h1>This is the second gallery</h1>
</article>
<article>
<h1>This is the third gallery</h1>
</article>
</section>
<script type="text/javascript">
var button=document.getElementsByTagName('button');
var gallery=document.getElementsByTagName('article');
for(var i=0; i<button.length; i++){
(function(index){
button[index].onclick=function(){
gallery[index].style.display="block";
}
}(i));
}
</script>
</body>
</html>
You could iterate over all the elements and compare the index of the button with the index of the current gallery item:
[].forEach.call(gallery, function (el, i) {
el.style.display = i === index ? 'block': 'none';
});
or:
for (var i = 0; i < gallery.length; i++) {
gallery[i].style.display = i === index ? 'block': 'none';
}
This will loop over all the elements and set the display of each element to none except for the on with an index that corresponds to the clicked button.
Example Here
var button = document.getElementsByTagName('button');
var gallery = document.getElementsByTagName('article');
for (var i = 0; i < button.length; i++) {
(function(index) {
button[index].onclick = function() {
[].forEach.call(gallery, function (el, i) {
el.style.display = i === index ? 'block': 'none';
});
}
}(i));
}
What you have done is almost right... Loop through the whole thing and when the particular element comes, do not do that, but I don't understand what's the use of closure here:
var button=document.getElementsByTagName('button');
var gallery=document.getElementsByTagName('article');
for(var i=0; i<button.length; i++){
if (i != 2) // Make sure `i` is not equal to 2.
(function(index){
button[index].onclick=function(){
gallery[index].style.display="block";
}
}(i));
}

Showing/Hiding Divs with Javascript on click

I'm trying to show/hide tabs on click using just Javascript but I'm getting errors ("Uncaught TypeError: Cannot set property 'className' of undefined tabs.(anonymous function).onclick"). Can someone give me an idea of what the issue might be?
<style>
a { text-decoration: none; }
li { list-style: none; }
li.selected { font-weight: bold; }
.panels div { display: none; }
.panels .selected { display: block; }
</style>
<div id="tabs" class="tabs">
<ul>
<li class="selected">One</li>
<li class="">Two</li>
<li class="">Three</li>
</ul>
</div>
<div id="panels" class="panels">
<div class="selected">This is panel one.</div>
<div class="">This is panel two.</div>
<div class="">This is panel three.</div>
</div>
<script>
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < tabs.length; i++) {
new function(i) {
tabs[i].onclick = function() {
tabs[i].className = panels[i].className = "selected";
for (var i = 0; i < panels.length; i++) {
tabs[i].className = panels[i].className = "";
}
}
}(i);
}
</script>
Your inner for loop has an i variable that conflict with the outter variable for loop with the same name.
You should also remove selected class from all elements before setting the clicked element 'selected'.
Try:
<script>
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < tabs.length; i++) {
new function(i) {
tabs[i].onclick = function() {
for (var j = 0; j < panels.length; j++) {
tabs[j].className = panels[j].className = "";
}
tabs[i].className = panels[i].className = "selected";
}
}(i);
}
</script>
You've got a couple of problems:
Multiple i variables
new function(i) {...} isn't the best syntax. I've used a closure below
multiple assignments per line isn't good
I've given your <li> elements values so that we can tell which li element has been clicked
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < panels.length; i++) {
(function(i) {
tabs[i].onclick = function() {
var j;
var panelIndex;
// remove styles from other tabs
for (j = 0; j < tabs.length; j++) {
tabs[j].className = "";
}
// apply style to the current tab: 'this'
this.className = "selected";
// hide other panels
for (j = 0; j < panels.length; j++) {
panels[j].className = "";
}
// show the selected panel
panelIndex = +this.value; // convert value to number
panels[panelIndex-1].className="selected"; // arrays are 0-indexed, so subtract 1
}
})(i);
}
a { text-decoration: none; }
li { list-style: none; }
li.selected { font-weight: bold; }
.panels div { display: none; }
.panels .selected { display: block; }
<div id="tabs" class="tabs">
<ul>
<li value="1" class="selected">One</li>
<li value="2" class="">Two</li>
<li value="3" class="">Three</li>
</ul>
</div>
<div id="panels" class="panels">
<div class="selected">This is panel one.</div>
<div class="">This is panel two.</div>
<div class="">This is panel three.</div>
</div>
Below here will work, as you are expecting. Two issues I found for accessing HTML Element inside for loop, you need to use .item() as its HTMLCollection you are getting instead of an array. Also your inner for loop needs to use different looping index, with one additional if condition to leave clicked one as shown and rest hidden.
<style>
a { text-decoration: none; }
li { list-style: none; }
li.selected { font-weight: bold; }
.panels div { display: none; }
.panels .selected { display: block; }
</style>
<div id="tabs" class="tabs">
<ul>
<li class="selected">One</li>
<li class="">Two</li>
<li class="">Three</li>
</ul>
</div>
<div id="panels" class="panels">
<div class="selected">This is panel one.</div>
<div class="">This is panel two.</div>
<div class="">This is panel three.</div>
</div>
<script>
var tabs = document.getElementById("tabs").getElementsByTagName("li");
var panels = document.getElementById("panels").getElementsByTagName("div");
for (var i = 0; i < tabs.length; i++) {
new function(i) {
tabs[i].onclick = function() {
tabs.item(i).className = panels.item(i).className = "selected";
for (var j = 0; j < panels.length; j++) {
if(i!=j){
tabs.item(j).className = panels.item(j).className = "";
}
}
}
}(i);
}
</script>

Categories

Resources