最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hide div when other div is showing - Stack Overflow

programmeradmin1浏览0评论

I am building a page with 3 buttons, each opening a different div-element. What I want, is to show just one div at the time. So when one div is opened, the other div should close.

I managed to create the buttons each opening a different div-element. But I cannot figure out a way to automatically close the div when other div is opened.

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");
var content1 = document.getElementById("content1");
var content2 = document.getElementById("content2");
var content3 = document.getElementById("content3");
content1.style.display = "none";
content2.style.display = "none";
content3.style.display = "none";
button1.addEventListener("click", showContent1);
button2.addEventListener("click", showContent2);
button3.addEventListener("click", showContent3);

function showContent1() {
  if (content1.style.display !== "none") {
    content1.style.display = "none"
  } else {
    content1.style.display = "block";
  }
}

function showContent2() {
  if (content2.style.display !== "none") {
    content2.style.display = "none"
  } else {
    content2.style.display = "block";
  }
}

function showContent3() {
  if (content3.style.display !== "none") {
    content3.style.display = "none"
  } else {
    content3.style.display = "block";
  }
}
#button1,
#button2,
#button3 {
  width: 50px;
  height: 50px;
  background: lightblue;
  margin: 5px;
  cursor: pointer;
}

#content1,
#content2,
#content3 {
  width: 100px;
  height: 50px;
  background: blue;
  color: white;
  margin: 5px;
}
<div id="button1">button 1</div>
<div id="button2">button 2</div>
<div id="button3">button 3</div>
<div id="content1">content 1</div>
<div id="content2">content 2</div>
<div id="content3">content 3</div>

I am building a page with 3 buttons, each opening a different div-element. What I want, is to show just one div at the time. So when one div is opened, the other div should close.

I managed to create the buttons each opening a different div-element. But I cannot figure out a way to automatically close the div when other div is opened.

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");
var content1 = document.getElementById("content1");
var content2 = document.getElementById("content2");
var content3 = document.getElementById("content3");
content1.style.display = "none";
content2.style.display = "none";
content3.style.display = "none";
button1.addEventListener("click", showContent1);
button2.addEventListener("click", showContent2);
button3.addEventListener("click", showContent3);

function showContent1() {
  if (content1.style.display !== "none") {
    content1.style.display = "none"
  } else {
    content1.style.display = "block";
  }
}

function showContent2() {
  if (content2.style.display !== "none") {
    content2.style.display = "none"
  } else {
    content2.style.display = "block";
  }
}

function showContent3() {
  if (content3.style.display !== "none") {
    content3.style.display = "none"
  } else {
    content3.style.display = "block";
  }
}
#button1,
#button2,
#button3 {
  width: 50px;
  height: 50px;
  background: lightblue;
  margin: 5px;
  cursor: pointer;
}

#content1,
#content2,
#content3 {
  width: 100px;
  height: 50px;
  background: blue;
  color: white;
  margin: 5px;
}
<div id="button1">button 1</div>
<div id="button2">button 2</div>
<div id="button3">button 3</div>
<div id="content1">content 1</div>
<div id="content2">content 2</div>
<div id="content3">content 3</div>

Share Improve this question edited Jul 30, 2019 at 8:56 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jul 30, 2019 at 8:36 TaneTane 4912 gold badges11 silver badges22 bronze badges 3
  • Does the jQuery tag imply that you would accept a jQuery solution? If not, then it should be removed. – Rory McCrossan Commented Jul 30, 2019 at 8:41
  • 1 Taken at face value, all you need to do is after you do content1.style.display = "block"; call content2.style.display = "none"; and the same for content3. It's that simple. Having said that, using ids with running numbers and thus having to create duplicate code like this is bad practice. – user5734311 Commented Jul 30, 2019 at 8:42
  • Here's a jQuery solution: jsfiddle/khrismuc/8prgjoea – user5734311 Commented Jul 30, 2019 at 8:54
Add a ment  | 

5 Answers 5

Reset to default 6

You can cut down your code to something like this:

$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "")
  $("#content" + id).toggle();
});

The code below will only allow 1 div to show at the time.

$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "");
  $("[id^=content]").hide()
  $("#content" + id).show();
});

Here we are using the ^ to say that we want all element starting with button to trigger the click event.

Demo

$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "")
  $("#content" + id).toggle();
});
#button1,
#button2,
#button3 {
  width: 50px;
  height: 50px;
  background: lightblue;
  margin: 5px;
  cursor: pointer;
}

#content1,
#content2,
#content3 {
  width: 100px;
  height: 50px;
  background: blue;
  color: white;
  margin: 5px;
  display: none;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="button1">button 1</div>
<div id="button2">button 2</div>
<div id="button3">button 3</div>
<div id="content1">content 1</div>
<div id="content2">content 2</div>
<div id="content3">content 3</div>

Here is a canonical way to do this.

Please study and look at where I delegate and have added classes

Use toggle() in the jQuery example to open AND close on click

jQuery:

$(".button").on("click", function(e) {
  $(".content").hide(); 
  $("#" + $(this).data("id")).show(); // or .toggle()
});
.button {
  width: 50px;
  height: 50px;
  background: lightblue;
  margin: 5px;
  cursor: pointer;
}

.content {
  width: 100px;
  height: 50px;
  background: blue;
  color: white;
  margin: 5px;
  display: none;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button" data-id="content1">button 1</div>
<div class="button" data-id="content2">button 2</div>
<div class="button" data-id="content3">button 3</div>
<div class="content" id="content1">content 1</div>
<div class="content" id="content2">content 2</div>
<div class="content" id="content3">content 3</div>

Vanilla JS

document.getElementById("nav").addEventListener("click", function(e) {
  var tgt = e.target;
  if (tgt.matches(".button")) {
    document.querySelectorAll(".content").forEach(function(div) { // a simple for loop is needed for older IE
      div.style.display = "none";
    });
    // Here I just show. If you want to toggle, you could use classList.toggle
    document.getElementById(tgt.getAttribute("data-id")).style.display = "block";
  }
});
.button {
  width: 50px;
  height: 50px;
  background: lightblue;
  margin: 5px;
  cursor: pointer;
}

.content {
  width: 100px;
  height: 50px;
  background: blue;
  color: white;
  margin: 5px;
  display: none;
}
<div id="nav">
  <div class="button" data-id="content1">button 1</div>
  <div class="button" data-id="content2">button 2</div>
  <div class="button" data-id="content3">button 3</div>
</div>
<div class="content" id="content1">content 1</div>
<div class="content" id="content2">content 2</div>
<div class="content" id="content3">content 3</div>

You can even create a tab system without any javascript at all, using the radio button css trick.

If a radio button is checked, then the next div is displayed, using the sibling selector: ~.

input{
  display: none;
}

label{
  display: inline-block;
  padding: 3px;
  border: 1px solid #aaa;
}

label:hover{
  cursor: pointer;
}

.display{
  display: none;
}

[type=radio]:checked ~ .display{
  display: block;
}
<section>
  <label for="div1">Show div 1</label>
  <label for="div2">Show div 2</label>
  <label for="div3">Show div 3</label>
</section>

<section>
  <input type="radio" id="div1" name="tab-nav" checked />
  <div class="display">
    Text from div 1.
  </div>
</section>

<section>
  <input type="radio" id="div2" name="tab-nav" />
  <div class="display">
    Text from div 2. It's cool.
  </div>
</section>

<section>
  <input type="radio" id="div3" name="tab-nav" />
  <div class="display">
    Text from div 3. Definitely a cool css trick.
  </div>
</section>

Here's another src and it's demo.

//find all buttons
document.querySelectorAll("button[data-target]").forEach(el => {
  //put a click event on each button
  el.addEventListener("click", ev => {
    //when clicked, hide all divs
    let divs = document.getElementsByClassName("my-div");
    for (let div of divs) { 
      div.style = "display: none;"; 
    }
    
    //then show the div that this button should be showing
    //by grabbing it's id from the data-target attribute and setting it's style
    document.getElementById(el.getAttribute("data-target")).style = "display: block;";
  });
});
.my-div {
  display: none;
}
<button data-target="div1">div1</button>
<button data-target="div2">div2</button>
<button data-target="div3">div3</button>

<div class="my-div" id="div1">content 1</div>
<div class="my-div" id="div2">content 2</div>
<div class="my-div" id="div3">content 3</div>

Please refer to Accordion, if that is what you are ultimately trying to achieve.

Remove the condition in the button's click event if you do not want to hide the same content on second click.

SOLUTION:

button1.addEventListener("click", () => activeDiv = (activeDiv === "content1") ? "": "content1");
button2.addEventListener("click", () => activeDiv = (activeDiv === "content2") ? "": "content2");
button3.addEventListener("click", () => activeDiv = (activeDiv === "content3") ? "": "content3");
button1.addEventListener("click", openDivGroup);
button2.addEventListener("click", openDivGroup);
button3.addEventListener("click", openDivGroup);

var activeDiv = '';
function openDivGroup ($event) {
    var contentIdArray = jQuery ("[id^=content]");
    for (var i = 0; i < contentIdArray.length; i++) {
        if (activeDiv === contentIdArray[i].id) contentIdArray[i].style.display = 'block';
        else contentIdArray[i].style.display = 'none';
    }
}

CODE SNIPPET:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis./ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<style>
	#button1,
	#button2,
	#button3 {
	  width: 50px;
	  height: 50px;
	  background: lightblue;
	  margin: 5px;
	  cursor: pointer;
	}

	#content1,
	#content2,
	#content3 {
	  width: 100px;
	  height: 50px;
	  background: blue;
	  color: white;
	  margin: 5px;
	}
</style>
</head>
<body>

<div id="button1">button 1</div>
<div id="button2">button 2</div>
<div id="button3">button 3</div>
<div id="content1">content 1</div>
<div id="content2">content 2</div>
<div id="content3">content 3</div>

<script>
	var button1 = document.getElementById("button1");
	var button2 = document.getElementById("button2");
	var button3 = document.getElementById("button3");
	var content1 = document.getElementById("content1");
	var content2 = document.getElementById("content2");
	var content3 = document.getElementById("content3");
	content1.style.display = "none";
	content2.style.display = "none";
	content3.style.display = "none";
	button1.addEventListener("click", () => activeDiv = (activeDiv === "content1") ? "": "content1");
	button2.addEventListener("click", () => activeDiv = (activeDiv === "content2") ? "": "content2");
	button3.addEventListener("click", () => activeDiv = (activeDiv === "content3") ? "": "content3");
	button1.addEventListener("click", openDivGroup);
	button2.addEventListener("click", openDivGroup);
	button3.addEventListener("click", openDivGroup);

	var activeDiv = '';
	function openDivGroup ($event) {
		var contentIdArray = jQuery ("[id^=content]");
		for (var i = 0; i < contentIdArray.length; i++) {
			if (activeDiv === contentIdArray[i].id) contentIdArray[i].style.display = 'block';
			else contentIdArray[i].style.display = 'none';
		}
	}
	</script>
</body>
</html>

发布评论

评论列表(0)

  1. 暂无评论