Search code examples
javascripthtmlonclickhide

How to hide a div after click on another div


I want to hide my div after click on a search icon, it isn't a button so I don't really know how to do it. I want to hide this text "

Simply click on the … and type the name of where you would like to visit

" by clicking on the div class="search-icon".

<div id="intro"> 
            <p>Simply click on the &nbsp;<i class="fas fa-search"></i>&nbsp; and type the name of where you would like
                to visit</p>
            <div class="search-box">
                <input id="searchBox" type="text" placeholder="Search your location">
                <div class="search-icon">
                    <i class="fas fa-search"></i>
                </div>
                <div class="cancel-icon">
                    <i class="fas fa-times"></i>
                </div>
                <div class="search-data"></div>
            </div>
        </div>

It looks like that

I've tried few js code but because it isn't a button I am not sure hot it should work.


Solution

  • First you need to give <p> and second search icon a clear classes, so you can select them in the dom:

    <div id="intro">
      <p class="text">Simply click on the &nbsp;<i class="fas fa-search"></i>&nbsp; and type the name of where you would like to visit</p>
      <div class="search-box">
        <input id="searchBox" type="text" placeholder="Search your location">
        <div class="search-icon">
          <i class="fas fa-search search-icon"></i>
        </div>
        <div class="cancel-icon">
          <i class="fas fa-times"></i>
        </div>
        <div class="search-data"></div>
      </div>
    </div>

    then for the JS part first you need to select that paragraph and the second search icon:

    const searchIcon = document.querySelector(".search-icon");
    const text = document.querySelector(".text");
    
    searchIcon.addEventListener("click", function () {
      if (window.innerWidth <= 768) {
        text.classList.add("hide-text");
      }
    });

    and for actually hiding the text you need to add a css class:

    .hide-text {
      display: none;
    }