Skip to content
Advertisement

How to apply hover effect on images?

I have used spotlight package and customized it,i want the hover effect in div, when i hover it, the search button appears, when i remove my cursor,the button disappears.

For this i am using mouseover and mouseout event in addEventListener.

Html:

<div class="container">
    <div class="row">
        <div class="col-md-4 column-container">

            <a href="https://www.google.com">

                <img src="demo/gallery/brooklyn-bridge-1791001-thumb.jpg" alt="">

            </a>

            <button type='button' onclick="showGallery(1)" class="main-search-btn" data-bs-toggle="tooltip"
                data-bs-placement="bottom" title="bottom">
                <i class="fa fa-search" aria-hidden="true"></i>

            </button>


        </div>
        <div class="col-md-4 column-container">

            <a href="https://www.google.com">


                <img class="img-fluid" src="https://source.unsplash.com/random" alt="">

            </a>

            <button type='button' onclick="showGallery(4)" class="main-search-btn" data-bs-toggle="tooltip"
                data-bs-placement="bottom" title="bottom">
                <i class="fa fa-search" aria-hidden="true"></i>

            </button>


        </div>



    </div>
</div>

Following is the js code which i am using to build this logic for every element through loop.

document.querySelectorAll(".column-container").forEach((item, index) => {
  console.log(item);
  search = document.querySelectorAll(".main-search-btn")[index];
  console.log(search);

  item.addEventListener("mouseover", () => {
    search.style.display = "initial";
  });
});
document.querySelectorAll(".column-container").forEach((item, index) => {
  search = document.querySelectorAll(".main-search-btn")[index];
  console.log(search);

  item.addEventListener("mouseout", () => {
    search.style.display = "none";
  });
});

The problem is that the above js code is only working for last div element rather applying this hover effect on all the elements.

style.css

.fa-search {
  color: white !important;
}
div.column-container {
  position: relative;
  /* border: 2px solid blue; */
}
div.column-container a img {
  width: 100% !important;
  border: 2px solid blue;
}

.main-search-btn {
  /* border: 2px solid blue; */
  display: none;
  background-color: #000 !important;
  top: -3px;
  right: 10px;
  border-radius: 0px;
  z-index: 10000;
  position: absolute;
}

So, how can i run it for all the div elements through loop?

Advertisement

Answer

Rather than making things complex with javascript you can try using css to achieve the same result. I have given an example where with a simple one line of css you can do what it took more than 18 lines of javascript code

.column-container:hover .main-search-button {
    display: initial;
}
Advertisement