0

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 achieve my task
</script>
2

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

On click of the icon it should be hidden but if I use this function it won't be hidden
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.