Home > other >  How to hide and display when ever onclick function happen by using javascript?
How to hide and display when ever onclick function happen by using javascript?

Time:11-04

I am designing one html page inside that I am using javascript also , what my requirement is when ever the page is loading the first div should be displayed when ever I click on that icon it should hide and it displays the second div content,for that please help me to fix the issue..

<div class="first">
<i class="fa fa-heart" onclick="toggle()" ></i>
</div>
<div class="second">
<b> I am from second div</b>
<div>

<script>
flag=true;
here I am not getting how to write the function to acheive my task
</script>

CodePudding user response:

Your toggle function could be like this:

function toggle() {
  var x = document.getElementsByClassName('second');
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

I would suggest using and id on the element instead of a class as it is explained here: https://www.w3schools.com/howto/howto_js_toggle_hide_show.asp

CodePudding user response:

There are multiple ways you can do it. The 2 I normally use are:

  1. Wrapping the icon into label and adding <input type="checkbox" />. This allows to achieve it without using any javascript at all, but it has a bit of complex css to it. You can check out this https://css-tricks.com/the-checkbox-hack/ for reference.
  2. This is easy to do. You need to define .active { display: block } class in your css and in javascript you can write something like
function toggle() {
  var element = document.querySelector(".second");
  element.classList.toggle("active");
}

but before you need to make .second { display: none }

I am sure that there're more ways of doing this, but these are the 2 I use the most depending on the situation.

  • Related