Home > Software design >  Hide/Show div on click and scroll
Hide/Show div on click and scroll

Time:12-25

I want to create a search form which is hidden and when we click the search icon that form appears and when user click away or scrolls the search form hides.

CodePudding user response:

You have to use .onclick event in js and change display and visibility property in a function. For example:

document.getElementById("searchIcon").onclick = searchFunction
function searchFunction(){
   const search = document.getElementById("searchForm");
   search.style.display = "block";
   search.style.visibility = "visible";
}

Of course, by default it should be hidden. But display: none is not nesseccary, depends on your website.

CodePudding user response:

Try this: Whenever you click on the image, "This is part of the div" appears in Red. Basically, you use Javascript to set/remove the hidden Attribute every time the user clicks the <img> item. Additionally, you change the <img>'s onclick Attribute to the opposite function(show_div()==>hide_div();hide_div()==>show_div()):

//see html on where to put this
show_div=function(){//Executed when the div ISN'T shown and the user clicks on the <img> tag
document.getElementById("search_div").removeAttribute("hidden");
document.getElementById("search_icon").setAttribute("onclick","hide_div()");}
hide_div=function(){//Executed when the div ISN'T shown and the user clicks on the <img> tag
document.getElementById("search_div").setAttribute("hidden","true");
document.getElementById("search_icon").setAttribute("onclick","show_div()");}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example Page</title>
</head>
<body>
<img height="32" width="32" src="https://cdn-icons-png.flaticon.com/512/3917/3917754.png" onclick="show_div()" id="search_icon">
<div id="search_div" hidden="true">
<font size=7 color="Red">This is part of the div</font>
</div>
<script type="text/javascript">//put the Javascript part here when copy-pasting this code
</script>
</body>
</html>

You might want to take a look at the "hidden" attribute and the "click" event.

  • Related