How to toggle off an element when another element is activated? - javascript

I have two elements.
if 1 is already toggled on, then when I toggle on 2, 1 should toggle off.
I am still new to javascript, so if someone wuold help please thanks. Right now, when I try to click, nothing happens, if I remove the while loop, then it works. Maybe I have some error in there that I am unsure off, but it looks right base on the logic.
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.newClassName {
width: 400px;
height: 100px;
background-color: lightblue;
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to toggle between two classes.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try it 2</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<div id="myDIV2" class="mystyle">
I am a DIV element2
</div>
<script>
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
function myFunction() {
x.classList.toggle("newClassName");
}
function myFunction2() {
y.classList.toggle("newClassName");
}
while (x.classList.contains("newClassName")) {
if (y.classList.contains("newClassName") = true) {
x.classList.toggle("newClassName");
}
}
</script>
</body>

You mixed up plain JavaScript and jQuery. I rewrote the script. I think this is what you wanted ...
var x = $("#myDIV");
var y = $("#myDIV2");
function myFunction() {
x.toggleClass("newClassName");
if( x.hasClass("newClassName") ) {
y.removeClass("newClassName");
}
}
function myFunction2() {
y.toggleClass("newClassName");
if( y.hasClass("newClassName") ) {
x.removeClass("newClassName");
}
}
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.newClassName {
width: 400px;
height: 100px;
background-color: lightblue;
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click the button to toggle between two classes.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try it 2</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<div id="myDIV2" class="mystyle">
I am a DIV element2
</div>

You don't need the while loop
You mixed plain JS with jQuery.
the code is commented
Working fiddle
EDIT
As pointed out in the comment, my answer should include code so here it is:
Javascript
$(function() { // This part was proposed by eisbehr
var div1 = $('#myDIV');
var div2 = $('#myDIV2');
$('#btn1').click(function() {
div1.toggleClass('newClassName');
if (div2.hasClass('newClassName')) {
div2.removeClass('newClassName');
}
});
$('#btn2').click(function() {
div2.toggleClass('newClassName');
if (div1.hasClass('newClassName')) {
div1.removeClass('newClassName');
}
});
});
HTML
<p>Click the button to toggle between two classes.</p>
<button id="btn1">Try it</button>
<button id="btn2">Try it 2</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<div id="myDIV2" class="mystyle">
I am a DIV element2
</div>

You may reduce all to only one function because, from MDN:
toggle ( String [, force] )
When only one argument is present: Toggle class value; i.e., if class exists then remove it and return false, if not, then add it and return true.
When a second argument is present: If the second argument is true, add specified class value, and if it is false, remove it.
So the code is:
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
function myFunction() {
var result = x.classList.toggle("newClassName");
y.classList.toggle("newClassName", !result);
}
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
.newClassName {
width: 400px;
height: 100px;
background-color: lightblue;
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
<p>Click the button to toggle between two classes.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction()">Try it 2</button>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<div id="myDIV2" class="mystyle">
I am a DIV element2
</div>

Related

How can I remove class when click the same button

Please see code below:
const sectionIcon = document.querySelectorAll(".nk-section-icons")
const sectionContainer = document.querySelectorAll(".nk-sec-container")
const sectionIconHover = document.querySelectorAll(".nk-section-icons")
sectionIcon.forEach((sectionBtn)=> {
sectionBtn.addEventListener("click", (btns)=> {
// console.log(sectionIconHover)
const containerTarget = btns.currentTarget.parentElement.children[1]
const containerHoverTarget = btns.currentTarget.parentElement.children[0]
sectionContainer.forEach(items => {
if(items !== containerTarget) {
items.classList.remove("show")
// itemHover.classList.remove("rb")
}
})
sectionIconHover.forEach(itemHover => {
if(itemHover !== containerHoverTarget) {
itemHover.classList.remove("rb")
}
})
containerTarget.classList.toggle("show")
containerHoverTarget.classList.add("rb")
})
})
.nk-section-icons {
height: 30px;
min-width: 30px;
width: 30px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 3px;
background: yellow;
margin-bottom: 5px;
}
.nk-section-icons.rb {
background: black;
}
.nk-sec-container {
width: 300px;
min-width: 300px;
height: 100%;
background: red;
position: absolute;
z-index: 11;
box-shadow: rgba(17, 17, 26, 0.1) 0px 0px 16px;
border-radius: 6px;
left: 70px;
top: 0px;
}
.nk-sec-container.show {
background: green;
}
.nk-section-icons-container {
position: relative;
}
<div class="nk-section-l-icons">
<div class="nk-section-icons-container">
<div class="nk-section-icons fav" data-title="Favorites">btn</div>
<div class="nk-sec-container nk-sec-fav-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons recent" data-title="Recent">btn</div>
<div class="nk-sec-container nk-sec-recent-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons notifs" data-title="Notifications">btn</div>
<div class="nk-sec-container nk-sec-notif-c">
</div>
</div>
</div>
Hello guys, can you please see my code? Currently, it's working fine when I click the button it's working the classes are moved when I click any of the buttons. However, if I tried clicking the same button again the class rb is not removed but the show class is removed. Can you please help me with how can I fix this? Thanks
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if($("p").hasClass("main"))
{
$("p").toggleClass("main1");
}
else
{
$("p").toggleClass("main");
}
});
});
</script>
<style>
.main {
font-size: 120%;
color: red;
}
.main1 {
font-size: 120%;
color: green;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><b>Note:</b> Click the button more than once to see the toggle effect.</p>
</body>
</html>
Use toggling: Toggle between adding and removing the "main" class name for all elements
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

Show the content of the function in the div

How do I show myFunction content in myDiv div? So show "Example"?
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div class="myDiv">
<p id="demo"></p>
</div>
This code:
<div class="myDiv">
<p> id="demo"</p>
</div>
Should be this:
<div class="myDiv">
<p id="demo"></p>
</div>
With the id tag inside <p>
And this:
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
Should also get called since it is a function and not just the document.getElementById("demo").innerHTML = "Example!";
Example 1:
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
myFunction();
function myFunction() {
document.getElementById("demo").innerHTML = "Example!";
}
myFunction();
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div class="myDiv">
<p id="demo"></p>
</div>
Example 2:
document.getElementById("demo").innerHTML = "Example!";
document.getElementById("demo").innerHTML = "Example!";
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div class="myDiv">
<p id="demo"></p>
</div>
You can solve this just by using the getElementById no need for a function.
document.getElementById("demo").innerHTML = "Example!";
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
<div class="myDiv">
<p id="demo"><p>
</div>
I think you are not clear about the concept of html,CSS and js.myDiv is a CSS class.You can beatify the class in it.Whatever html tag uses that class will integrate the proper of .myDiv class. myFunction() is a js function if you use the demo id in your html tag and it will act according to your function defination.

Hide & show content with javaScript

So, on my example I have 2 div-buttons (named btn1 and btn2) and 2 div elements (named content1 and content2).
What I would want, is that when you click the btn1, content1 shows. If you click btn2, content2 should show.
Content1 and content2 elements are currently placed in the same position, and by default, none of the content elements shouldn't be open before you have clicked anything. I would like to achieve this with pure javaSript.
Here is the example code:
var btn1 = document.getElementById("btn1");
var content1 = document.getElementById("content1");
content1.style.opacity = "0";
btn1.addEventListener("mouseover", showContent1);
function showContent1(){
if(content1.style.opacity === "0") {
content1.style.opacity = "1";
} else {content1.style.opacity = "0";}
}
var btn2 = document.getElementById("btn2");
var content2 = document.getElementById("content2");
content2.style.opacity = "0";
btn2.addEventListener("mouseover", showContent2);
function showContent2(){
if(content2.style.opacity === "0") {
content2.style.opacity = "1";
} else {content2.style.opacity = "0";}
}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
You can add click event to the buttons and based on the button clicked you can show or hide the respective div.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<style>
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;
height:200px;
border: 2px solid black;
}
#content1, #content2 {
width: 200px;
height:200px;
position:absolute;
background:lightblue;
display:none;
}
</style>
</head>
<body>
<script>
function showDiv(div){
if(div == 'btn1'){
document.getElementById('content1').style.display = 'block';
document.getElementById('content2').style.display = 'none';
}else{
document.getElementById('content1').style.display = 'none';
document.getElementById('content2').style.display = 'block';
}
}
</script>
<div id="btn1" onclick="showDiv('btn1')">show1</div>
<div id="btn2" onclick="showDiv('btn2')">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
</body>
Plunker For the same: https://plnkr.co/edit/brxoF2ClW2TeJOVMxn8d?p=preview
Check this, i've made it dynamic so you can create unlimited buttons and contents.
function toogleContent(id){
var toogleContent = document.getElementsByClassName('toogleContent');
var i = toogleContent.length;
while (i--) toogleContent[i].style.display = "none";
document.getElementById(id).style.display = "block";
}
#btn1, #btn2 {
width:100px;
height:20px;
text-align:center;
background:grey;
cursor:pointer;
margin:10px 0px;
}
#contents {
width: 200px;
height:200px;
border: 2px solid black;
}
#content1, #content2 {
width: 200px;
height:200px;
position:absolute;
background:lightblue;
display:none;
}
<div id="btn1" class="toogleBtn" onclick="toogleContent('content1')">show1</div>
<div id="btn2" class="toogleBtn" onclick="toogleContent('content2')">show2</div>
<div id="contents">
<div id="content1" class="toogleContent">content 1</div>
<div id="content2" class="toogleContent">content 2</div>
</div>
Whilst the above answers are all correct insofar as they will get you from A to B (based on the code you have provided), there are also a few 'best practice' changes you should use in your code, to avoid common pitfalls (and allow better maintainability and code reuse).
Firstly, you should avoid using IDs for styling. Whilst using an ID to apply styles is perfectly valid to do (and won't break anything) it is discouraged. An ID for a page must always be unique within a document, so using it to style potentially multiple similar elements means that you will very quickly have either broken HTML (by reusing an ID) or unwieldy and non-maintainable stylesheets (by having multiple identical selectors). You should prefer using classes to add styles to elements, as you can reuse classes, and even extend or use multiple classes per element.
In my snippet, I have also used a dataset with a number in it to help identify which element is being 'selected'. Datasets are intended to store custom data, and are extremely useful for storing and retrieving data in JavaScript. By using a dataset to store an ID that is independent of the ID or class of an element, you can infinitely add/remove tabs without having to change your CSS or JavaScript to fit. After all, I can add in a dataset for an ID of 3 (e.g. <div class="button" data-id="3">) and the button styling won't be affected.
Other good practices include using separate class names or selectors for JavaScript compared to those used to style an element (again so that you can change the name of a JavaScript selector without affecting the look of an element - you can also prepend a JavaScript selector with js- as I have done, so that it is more obvious that the selector is used by JavaScript, and not used to style an element).
I have also used a BEM styleguide to name my classes (though this is a preference thing - in short though, it is good practice to pick and then use some sort of naming convention or style guide for naming/styling elements).
A final recommendation (not shown) <button> element instead of a <div> for buttons. This will improve your disability access for a website, as screen reader technology can then distinguish between what is a button and what is merely a block of content (after all, a screen reader might not pick up that the <div> has a click event handler added, and so a disabled user might not be aware they can click on the 'button' to switch tabs).
// Select all buttons using querySelectorAll
let buttons = document.querySelectorAll('.js-toggle');
// Loop through each button and add an event listener
Array.from(buttons).forEach(button => {
// Click event listener
button.addEventListener('click', function() {
// Select all elements to hide/show
let tab_contents = document.querySelectorAll('.js-content');
// Hide all elements
hideElems(tab_contents);
// Get ID of button
let id = this.dataset.id;
// Select relevant tab using the ID above
document.querySelector(`.js-content-${id}`).style.display = 'block';
});
});
// Function for hiding all elements
let hideElems = (elems) => {
Array.from(elems).forEach(elem => elem.style.display = 'none');
}
.button {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0;
}
.tabs {
width: 200px;
height: 200px;
border: 2px solid black;
}
.tabs__content {
width: 200px;
height: 200px;
background: lightblue;
display: none;
}
<div class="button js-toggle" data-id="1">show1</div>
<div class="button js-toggle" data-id="2">show2</div>
<div class="tabs">
<div class="tabs__content js-content js-content-1">content 1</div>
<div class="tabs__content js-content js-content-2">content 2</div>
</div>
document.getElementById('btn1').addEventListener('click', ()=>{
document.getElementById('content2').style.display = "none";
document.getElementById('content1').style.display = "block";
});
document.getElementById('btn2').addEventListener('click', ()=>{
document.getElementById('content1').style.display = "none";
document.getElementById('content2').style.display = "block";
});
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;display:none;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
You need onClick event and 2 conditions. Please check this,
function showContent(content_id) {
if (content_id == 'content1') {
document.getElementById('content1').style.display = 'block';
document.getElementById('content2').style.display = 'none';
} else if (content_id == 'content2') {
document.getElementById('content1').style.display = 'none';
document.getElementById('content2').style.display = 'block';
}
}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue; display:none;
}
<div id="btn1" onClick='showContent("content1")'>show1</div>
<div id="btn2" onClick='showContent("content2")'>show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
This is a simple way to do it with vanilla javascript, just add a method that hides/shows the element based on which button you click
function toogle(showelem, hideelem) {
document.getElementById(showelem).style.display = "block";
document.getElementById(hideelem).style.display = "none";
}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;
}
<div id="btn1" onClick="toogle('content1','content2');">show1</div>
<div id="btn2" onClick="toogle('content2','content1');">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.remove("displayblock");
}
function myFunctionShow(){
var element = document.getElementById("myDIV");
element.classList.add("displayblock");
}
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
display:none;
}
.displayblock{
display:block;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Click the "Try it" button to remove the "mystyle" class from the DIV element:</p>
<button onclick="myFunction()">Hide</button>
<button onclick="myFunctionShow()">Show</button>
<div id="myDIV" class="mystyle displayblock">
This is a DIV element.
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#btn1,
#btn2 {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0px;
}
#contents {
width: 200px;
height: 200px;
border: 2px solid black;
}
#content1,
#content2 {
width: 200px;
height: 200px;
position: absolute;
background: lightblue;
}
</style>
</head>
<body>
<div id="btn1" onclick="showdiv1()">show1</div>
<div id="btn2" onclick="showdiv2()">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
</body>
<script>
function showdiv1(){
console.log( document.getElementById('content1'))
document.getElementById('content1').style.display='block';
document.getElementById('content2').style.display='none';
}
function showdiv2(){
document.getElementById('content1').style.display='none';
document.getElementById('content2').style.display='block';
}
</script>
</html>
Here We Go
You can you this for any element to hide and show
element.style.display = 'none'; // Hide
element.style.display = 'block'; // Show
element.style.display = 'inline'; // Show
element.style.display = 'inline-block'; // Show
If I understand you right, you should set "display: none" by default and then handle click on button to toggle "open" class. See example below.
const btn1 = document.getElementById("btn1"),
btn2 = document.getElementById("btn2"),
content1 = document.getElementById("content1"),
content2 = document.getElementById("content2");
const map = new Map()
.set(btn1, content1)
.set(btn2, content2);
const closeMapContent = _ =>
map.forEach((value, key) => value.classList.remove("open"));
map.forEach((value, key) => {
key.addEventListener("click", event => {
closeMapContent();
value.classList.add("open");
})
});
#btn1, #btn2 {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0px;
}
#contents {
width: 200px;
height: 200px;
border: 2px solid black;
}
#content1, #content2 {
width: 200px;
height: 200px;
position: absolute;
background: lightblue;
display: none;
}
.open {
display: block !important;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
function show() {
const h = document.getElementById('hidden1');
h.style.display = 'block' ;
const s =document.getElementById('showed');
s.style.display = 'none';
}
function hide() {
const h = document.getElementById('hidden1');
h.style.display = 'none' ;
const s =document.getElementById('showed');
s.style.display = 'block';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div >
<button id="showed" onclick="show()" >click to show</button>
<div id="hidden1" style="display: none">
<button onclick="hide()" >click to close</button>
<h1 >Content1</h1>
</div>
</div>
</body>
</html>
see with snippet
Another way to approach this is to use data-* attribute with little bit of styling. You can change the attribute of the parent div then the changes are reflected on children using CSS.
Also, you don't need to loops through elements if know the number of children elements.
See this example:
function toogleContent(target) {
document.querySelector("#contents").setAttribute("data-show", target);
}
#btn1,
#btn2 {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0px;
}
#contents {
width: 200px;
height: 200px;
border: 2px solid black;
}
#content1,
#content2 {
width: 200px;
height: 200px;
position: absolute;
background: lightblue;
opacity: 0;
}
#contents[data-show='1']>#content1 {
opacity: 1;
}
#contents[data-show='2']>#content2 {
opacity: 1;
}
<div id="btn1" onclick="toogleContent(1)">show1</div>
<div id="btn2" onclick="toogleContent(2)">show2</div>
<div id="contents" data-show=''>
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
(function() {
const buttons = document.querySelectorAll('.button');
const content = document.querySelector('.content__wrapper');
hideAll();
setUpClickHandlers();
function hide(element) {
element.classList.add('hide');
}
function show(element) {
element.classList.remove('hide')
}
function hideAll() {
Array.from(content.children).forEach(hide);
}
function toggle(element) {
hideAll();
show(element)
}
function onClick(content) {
return () => toggle(content)
}
function setUpClickHandlers() {
const handler = element => {
const show = content.querySelector(`.${element.dataset.for}`);
element.addEventListener('click', onClick(show));
};
Array.from(buttons).forEach(handler);
}
})()
.hide {
display: none
}
.button {
height: 30px;
line-height: 30px;
border-radius: 5px;
border: 1px solid grey;
padding: 0 10px;
display: inline-block;
margin: 10px 0;
cursor: pointer;
}
.content__wrapper {
background-color: aqua;
padding: 16px;
}
<button class="button" data-for="content_1">content 1</button>
<button class="button" data-for="content_2">content 2</button>
<button class="button" data-for="content_3">content 3</button>
<button class="button" data-for="content_4">content 4</button>
<div class="content__wrapper">
<div class="content content_1">Content 1</div>
<div class="content content_2">Content 2</div>
<div class="content content_3">Content 3</div>
<div class="content content_4">Content 4</div>
</div>

only one element at time can be "toggleClass"-ed in jQuery

How I am able to toggleClass on elements, but only one can be "toggled" at time.
There is solution (by adding another for loop to disable effect), but in pureJS and I need help to get this work in jQuery.
var elements = document.querySelectorAll("#box");
for ( var i = 0; i < elements.length; i++ ) (function(i){
elements[i].onclick = function() {
for (var j = 0; j < elements.length; j++) {
elements[j].style.border = '';
elements[j].innerHTML = '';
}
elements[i].style.border = "10px solid red";
elements[i].innerHTML = "selected";
};
})(i);
body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}
<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</body>
And here is jQuery function. In-short, I need that only one box can be red at time and when another is clicked it disable selected one. Exactly like one above in javascript.
$("div#box").click(function(){
$(this).toggleClass("red");
});
body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</body>
The usual way to do this is to remove the class on all of the other possible 'toggles' before applying the class to the newly selected one, like this:
var boxes = $('div.box');
boxes.click(function(){
boxes.removeClass('red');
$(this).addClass('red');
});
(You should use a class, not an ID any time you have more than one element to apply it to (so I've used .box, not #box).
Another important point is to select the boxes only once, and store them in a variable outside of the click handler. That way, you're not always re-selecting them on every click.
the this, refers to the current clicked element.
you will need to apply it to all the nav items such as below.
var
$boxes = $("div#box").click(function(){
$boxes.removeClass("red");
$(this).addClass("red");
});
body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</body>
Like previously said use a class instead of an ID. You can use the .not() jQuery method to achieve this.
Note: The difference between Beejamin's answer and mine is that in this one you can toggle the red class clicking the same square again while also removing siblings selection.
var box = $(".box");
box.click(function() {
$(this).toggleClass("red");
box.not(this).removeClass("red");
});
body {
background-color: black;
}
.box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Toggle visibility of 2 divs with 2 buttons

I am having issues with my code
I am trying to show 1 div (show_1) by default and then hide it and show a second div (show_2) when button 2 is clicked. And then when button 1 is clicked hide show_2 and show show_1 again
https://jsfiddle.net/mgzurjgL/4/
It is not working though, nothing happens when I click either buttons.
function switch_div(show_1, show_2) {
var a = document.getElementById(show_1);
var a2 = document.getElementById(show_2);
if (a.style.display == 'block') {
a.style.display = 'block';
a2.style.display = 'none';
} else {
a.style.display = 'none';
a2.style.display = 'block';
}
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div('show_1', 'show_2');">
1
</div>
<div class="button" onclick="switch_div('show_1', 'show_2');">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
You had your settings wrong in JSFiddle, you need to run the script in the head not onload. Also you passed in the same parameters twice. Also why dont you try something simpler like this.
https://jsfiddle.net/mgzurjgL/5/
function switch_div(show) {
document.getElementById("show_"+show).style.display = "block";
document.getElementById("show_"+((show==1)?2:1)).style.display = "none";
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div(1);">
1
</div>
<div class="button" onclick="switch_div(2);">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
Two items: script placement and a typo. Working version at JSFiddle, tested in Google Chrome.
The script has to run before the divs. In the JSFiddle Javascript settings, I changed "Load Type" to "No wrap - in <head>." This way the switch_div function exists when the divs are loaded.
There was a typo:
if (a.style.display == 'block')
should be
if (a.style.display == 'none')
Otherwise you are setting block display on an element that's already block :) .
Edit: This code still doesn't do what you appear to want, because the function you have written toggles the div visibility regardless of which button is pressed. What you really want is in this fiddle:
<div class="button" onclick="switch_div('show_1', 'show_2', true);">
and
<div class="button" onclick="switch_div('show_1', 'show_2', false);">
together with
function switch_div(show_1, show_2, should_show_1) {
var a = document.getElementById(show_1);
var a2 = document.getElementById(show_2);
if(should_show_1) {
a.style.display = 'block';
a2.style.display = 'none';
}
else {
a.style.display = 'none';
a2.style.display = 'block';
}
}
That way you get only the div you want.
You need to switch the statements in if-else or change the condition in the if to "if (a.style.display !== 'block') "
When a.style.display is 'block' then you have to set it to 'none' to hide it.
function switch_div(show_1, show_2) {
var a = document.getElementById(show_1);
var a2 = document.getElementById(show_2);
if (a.style.display !== 'block') {
a.style.display = 'block';
a2.style.display = 'none';
} else {
a.style.display = 'none';
a2.style.display = 'block';
}
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div('show_1', 'show_2');">
1
</div>
<div class="button" onclick="switch_div('show_1', 'show_2');">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
I changed the js function and the "call" for buttons.
function switch_div(show_1, show_2) {
var a = document.getElementById(show_2);
var a2 = document.getElementById(show_1);
a.style.display = 'none';
a2.style.display = 'block';
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div('show_1', 'show_2');">
1
</div>
<div class="button" onclick="switch_div('show_2', 'show_1');">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
This also works with:
<div class="button" onclick="switch_div(1,2);">
1
</div>
<div class="button" onclick="switch_div(2,1);">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
<script>
function switch_div(n1,n2) {
document.getElementById("show_"+n1).style.display = 'block';
document.getElementById("show_"+n2).style.display = 'none';
}
</script>

Categories