Hide/Show div on click and scroll - javascript

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.

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.

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.

i am using addEventListener to get if any click is happened you can use any section of the on the place of document to make it work for that particular section. i.e: header
and then i am using classList.toggle to add and remove a particular class from the search input box.
you can add CSS as per your need.
var searchbox=document.querySelector("#search-bar");
var searchIcon=document.querySelector(".search-icon");
document.addEventListener("click",searchBar);
function searchBar(){
searchbox.classList.toggle("search-bar");
}
.search-bar{
display:none;
}
<div>
<input class="search-bar" id="search-bar" type="text" placeholder="search...">
<i class="search-icon">🔍 </i></div>

This jquery function worked for me
'
$(document).ready(function(){
$(window).scroll(function(){
$("#search").fadeOut();
});
$("body").click(function(){
$("#search").fadeOut();
});
$("#btn").click(function(event){
event.stopPropagation();
$("#search").fadeToggle();
});
}); '
with this function when user scrolls the page the search bar will hide
below is a javascript version
document.addEventListener("DOMContentLoaded", function() {
window.addEventListener("scroll", function() {
document.getElementById("search").style.display = "none";
});
document.body.addEventListener("click", function() {
document.getElementById("search").style.display = "none";
});
document.getElementById("btn").addEventListener("click", function(event) {
event.stopPropagation();
var search = document.getElementById("search");
if (search.style.display === "none") {
search.style.display = "block";
} else {
search.style.display = "none";
}
});
});

Related

Code to click outside of element not firing

This is my code:
<div class="titfx">
<div class="clk1">CLICKME</div>
</div>
<div class="here" style="display:none;">info for here</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('.clk1').on("click", function(event) {
//first code
var here = $(this).parent(".titfx").next(".here");
here.toggle();
//second code
if (!here.is(event.target) && here.has(event.target).length === 0) {
here.hide();
}
});
});
</script>
What the first part of javascript code does: When the word "CLICKME" is clicked, then the hidden div with text "info for here" shows.
What the second part of javascript code should do: When any part of the screen that is not class="here" is clicked on, then the text "info for here" should hide. The second part of my code is unable to achieve that. I'm not sure what I'm doing wrong. Please help me fix this issue.
you need to bind two event listeners to achieve this, one for the "clk1" element, and one for the whole page.
when fires document click event, just hide the text,
when fires ".clk1" click element, you need to stop propagation first and then write the toggle behaviour.
this is my solution
$(document).ready(function() {
$('.clk1').on("click", function(event) {
//first code
event.stopPropagation();
$(".here").toggle();
});
//second code
$(document).on("click", function(event){
$(".here").hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titfx">
<div class="clk1">CLICKME</div>
</div>
<div class="here" style="display:none;">info for here</div>
Here is a potential solution. The first click binding works for the toggle logic. However, for your second scenario, you said you want it to close them if they click any where on the page, other than the two areas. In that regard, you are concerned with the click events for the body, not just the two areas.
The second logic binds to the body, and checks to see if the clicked element is a child of the .clk1 or the .here. If it is not a child of either one, it will hide the .here.
The css was added to force the page size to be larger than just the html provided so you could actually click on something not them, :)
$(document).ready(function() {
$('.clk1').on("click", function(event) {
var here = $(this).parent(".titfx").next(".here");
here.toggle();
});
$(document.body).on('click', function(event){
var clickedElement = $(event.target);
if (!clickedElement.closest('.clk1').length
&& !clickedElement.closest('.here').length) {
$('.here').hide();
}
});
});
body {
min-width: 800px;
min-height: 600px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titfx">
<div class="clk1">CLICKME</div>
</div>
<div class="here" style="display:none;">info for here</div>

How can I fix this jQuery glitch so the div doesn't try to disappear when using .hover()?

What I'm trying to accomplish is make a div visible when hovering over another using the .hover() method, addClass and removeClass. But what happens is that when I hover over the added div, it reads that I'm no longer hovering over the div specified (or at least that's what I assume) in the .hover() method. This causes the div to flash on and off the screen repeatedly. How can I fix this so this problem doesn't happen? Here is the code:
JS
$(document).ready(function(){
$('.building').hover(
function(){
var my_id = $(this).attr('id');
var my_balloon ="#" + my_id + '_balloon';
//console.log(my_balloon);
$(my_balloon).addClass('active');
},
function(){
var my_id = $(this).attr('id');
var my_balloon ="#" + my_id + '_balloon';
//console.log(my_balloon);
$(my_balloon).removeClass('active');
}
);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function abc() {
document.getElementById("Div2").style.display="";
}
</script>
</head>
<body>
<div onmouseover="abc()">Div1</div>
<div id="Div2" style="display:none">Div2</div>
</body>
</html>
If the balloon overlaps the Div, it captures the event “onmouseover”.
If you don’t have to deal with it, you could use css rule to prevent any action
.balloon {
pointer-events: none;
}
This rule allows the event to pass through the balloon, as if it didn’t exist.

Events was not working properly in Javascript

I created a simple event script, which changes the image when clicked on the button. But unfortunately not changing, please help.
Error: I am not getting any error message also , just it was not changing the image.
<html>
<head>
<title>Events Practise</title>
<style>
#imtest{
width:100px;
height:150px;
}
</style>
</head>
<body>
<h4> This a practise page of Events and event handlers </h4>
<p> Hi this the practise page that changes the Html and Css contents in the page by Using the JavaScript </p>
<img id="imtest" src="marni.jpg" alt="Image corrupted">
<button onclick="eventtest()">Change Image</button>
<script>
function eventtest()
{
var imt = document.getElementById("imtest");
imt.onclick = change;
}
function change()
{
var imtchng = document.getElementById("imtest");
imtchng.src = "marni1.png";
}
</script>
</body>
I created a simple event script , which changes the image when clicked
on the button
No you've created a script which set's a click handler on the image when the button is clicked and after that when the image is changed it will change.
If you want to change the image directly by clicking just set the click handler on it.
In the imt.onclick = change line you are forgetting the parentheses after the change. Replace it with change()
<script>
function eventtest()
{
change();
}
function change()
{
var imtchng = document.getElementById("imtest");
imtchng.src = "marni1.png";
}
</script>
or
<button onclick="change()">Change Image</button>

Show link which is inside a hidden div

Let's say I have this inner link which is positioned inside a hidden div (display:none) - the div toggles when a button is clicked:
<a name="here">Show me!</a>
How can I make the element visible when somebody enters the url: mypageurl#here, without clicking the toggle button (make it visible by default when this specific link is entered)?
$().ready(function () {
var hash = $.trim(window.location.hash);
if (hash != '') {
var prt = $('[name="' + hash.substr(1) + '"]').parent();
prt.show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display:none;"><a name="here">Show me!</a></div>
Full code!
You could use the CSS "visibility:hidden", then use JavaScript to change that to "visibility:visible" when someone enters a certain phrase.
Alternatively, you could just use display: ""; or display:block on the "display:none" div when the same action occurs, again using some JavaScript.
You can use the below script.
<script>
$(document).ready(function(){
var loc = document.location.hash;
if(loc == "#test")
{
$('#test').show();
}
});
</script>
Here is the source code of a simple page that I made:
<html>
<script src="http://code.jquery.com/jquery-latest.min.js "></script>
<body>
<div id="hide" style="display:none">
<a name="here">Show me!</a>
</div>
</body>
<script>
$(document).ready(function(){
if(document.location.href.search("#hide")>0){
$("#hide").toggle();
}
});
</script>
</html>
It will show the div with the id hide if the page has the text "#hide", else it remains hidden.

Print HTML-page with div that has been clicked on and hide the rest

I have a HTML-page with a lot of different DIVs in it and I want to print out the the DIV that the user has clicked in and hide all the rest.
Can someone tell me how to do this in Javascript please?
<html>
<head>
<title>Print Demo</title>
<script type="text/javascript">
<!-- MY JAVASCRIPT FUNCITON -->
</script>
</head>
<body>
<div id="div1">
Print the page with this div
</div>
<div id="div2">
Print the page with this div
</div>
<div id="div3">
Print the page with this div
</div>
</body>
</html>
This is just to extend pimvdb's answer.
jQuery:
$("a").on("click", function(){
$("div").hide();
$(this).parent().show();
});
Or as suggested:
$("a").on("click", function(){
$("div").hide();
$(this).closest("div").show();
});
Hiding an element means setting it's style.display property to "none". Showing means setting it to "block" for a div element.
In combination with getElementsByTagName, you could accomplish this: http://jsfiddle.net/b9cgM/.
function show(elem) {
// hide all divs initially
var allDivs = document.getElementsByTagName("div");
for(var i = 0; i < allDivs.length; i++) {
allDivs[i].style.display = "none";
}
// show the appropriate div
elem.parentNode.style.display = "block"; // parent of the <a> is the <div> to show
}
You could bind the event like <a href="#" onclick="show(this); return false;">. The element (this) is then passed to show.
As a side note, libraries such as jQuery make this even easier; you might want to check that out (though I don't recommend including it if the only use case would be this).
sorry, there is only window.print() for printing in js, which means you can only print the entire window. if you want some to be able to print your document, make it printable using CSS.
for instance, maybe you want your navigation to disappear for printing, but leave the title of your page there and the name of your web site and maybe a page URL (sometimes browsers like firefox cut those off if they are too long). and sometimes some sites take away the browser controls and make the mistake of leaving you with no print button - and it's an online purchasing site... it's happened before.
<style type="text/css">
#media print {
.boxGreen {
padding:10px;
border-color:green;
border-style:dashed;
border-width:thin;
}
}
#media screen {
.boxGreen {
padding:10px;
border-color:green;
border-style:dashed;
border-width:thin;
}
}
</style>
you CAN do an onclick="switchtodiv('someid')" and then after the divs do this:
<div onclick="switchtodiv('span1')">ClickMe<span id="span1">some content</span></div>
<div onclick="switchtodiv('span2')">ClickMe<span id="span2">some content</span></div>
<div onclick="switchtodiv('span3')">ClickMe<span id="span3">some content</span></div>
<!--you can generate these divs using a for statement...-->
<script type="text/javascript">
//switchdiv allows only 1 div tobe
function switchdiv(id) {
var ids=new Array('span1','span2','span3');
var i;
for (i=0; i < ids.length; i++) {
if (ids[i] == id) {
document.getElementById(ids[i]).style.visibility='visible';
document.getElementById(ids[i]).style.display='block';
} else {
document.getElementById(ids[i]).style.visibility='hidden';
document.getElementById(ids[i]).style.display='none';
}
}
}
</script>
You could use a javascript function like document.getElementById(id) to hide the two other divs
So in your function you could just use
function hide1() {
document.getElementById(div2).style.display = "none";
document.getElementById(div3).style.display = "none";
}

Categories

Resources