Home > Net >  hide / show div with a button not in the same div
hide / show div with a button not in the same div

Time:10-22

I'm using elementor for my wordpress site and I wish to have a button in a first div (section) that control if a second and separate div (section) is display or not. I've tried to use the checkbox hack but it's working only if the checkbox is in the div as the content https://css-tricks.com/the-checkbox-hack/

Is there a solution to use CSS or even javascript ? If you advice to me to use javascript I'll put in my function.php file and as I'm begginer in javascript can you please write all the function I have to implement into my function.php file.

Basically it means :

<div>button</div> <div>content to show and hide on click on the button</div>

Best regards, Clément

CodePudding user response:

You can use Jquery:

1-Put an id to your DIV

<div id = "btn_show"> button </div> <div id = "show"> content to show and hide on click on the button </div>

2-Call jquery to display it

$("#btn_show").click(function(){
 $("#show").show();
  //or
 $("#show").hide();
});

And jquery you can call it with CDN

<script src="https://code.jquery.com/jquery-3.6.0.js"</script>

CodePudding user response:

In javascript without any library this could be very easy but you need to put an id on your divand your button.

<div id="myButton">button</div> 
<div id="myDiv">
  content to show and hide on click on the button
</div>

Then you just add a script section like this : (it just need to be after your div and your button in the DOM)

<script>
var myDiv = document.getElementById('myDiv');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', e => {
  myDiv.classList.toggle('visible'):
});
</script>

And at last, you need a css like this:

.visible {
  display: none;

}
  • Related