Show div and then hide when clicking outside - javascript

I have this code:
$(function() {
$('#toggle4').click(function() {
$('.toggle4').slideToggle('fast');
return false;
});
});
Which works great and shows the '.toggle4' div but I want to hide it again when clicking outside/away from it.
So I added this:
$(document).click(function() {
$(".toggle4").hide();
});
Which works but it hides the div even when I click inside of the '.toggle4' div (it's an input box for a search form).
Any ideas? Thanks.

That's because when you click inside of .toggle4 that click event bubbles up the DOM and triggers the event you bound to the document. You should be able to fix that with something like:
$('.toggle4').click(function(e){
e.stopPropagation()
})

One possibility is to prevent the click event from bubbling up to the document if it took place inside the toggle.
$(function() {
$('#searchField').click(function() {
$('#toggle').slideToggle('fast');
return false;
});
});
$(document).click(function() {
$("#toggle").hide();
});
$("#toggle").click(function(e) {
e.stopPropagation();
});
#toggle {
width: 100px;
height: 100px;
background: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchField">
<div id="toggle" class="toggle4"></div>

Related

jQuery hide dropdown menu

I have a dropdown menu that shows with the following jQuery script:
jQuery(document).ready(function($) {
$('#block-mln-main-menu li').click(function(){
$(this).find('.test').toggle();
});
});
What I want to achieve is when the user clicks anywhere else on the page, it slides up or hides. I am literally at a loss on how to achieve this.
Any help is greatly appreciated.
added a fiddle : http://jsfiddle.net/aL7Xe/999/
Yoy can try stop propagation event.
CSS:
.showup{width:100px;height:100px; background:red; display:none;}
.click{cursor:pointer;}
HTML
<div class="click">click me</div>
<div class="showup">Click somewhere else!</div>
JQUERY
$(document).ready(function(){
$('.click').click(function(event){
event.stopPropagation();
$(".showup").slideToggle("fast");
});
$(".showup").on("click", function (event) {
event.stopPropagation();
});
});
$(document).on("click", function () {
$(".showup").hide();
});
Toggle will only work it user click on the same object it you want to hide it when click elsewhere try
jQuery(document).ready(function($) {
$(this).not('#block-mln-main-menu li').click(function(){
$(this).find('.test').hide();
});
});
What I understand is that you want to show dropdown menu when an user clicks on it. If the user again clicks on it or anywhere on the page it should close.
CSS
.hide {
display: none;
}
JS
$('.menu-label').on('click', function() {
$('.drop-down-menu').toggleClass('hide');
});
To hide the menu when user click anywhere on page
$('body').on('click', function() {
$('.drop-down-menu').addClass('hide');
});

Stop eventPropagation after jQuery trigger event

Here's the situation. There is button and there is hidden div. After user clicks the button, hidden div appears and in the same time I'm adding event listener on body using on() to check if user clicked out of this hidden div. After that div should be hidden again and click event detached.
Everything works fine but only when user clicks the button. If I trigger click using trigger() function then on() function is called immediately and hidden div is not appearing.
Here is the code:
$('button').click(function(e){
e.stopPropagation();
$('div').toggleClass('active');
if($('div').hasClass('active')){
$('body').on('click.div', function(e){
console.log('body clicked')
if(! $(e.target).closest('div').length){
$('div').removeClass('active');
$('body').off('.div');
}
});
}else{
$('body').off('.div');
}
});
$('input').click(function(){
$('button').trigger('click');
});
div{
display: none;
}
div.active{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<div>This is hidden</div>
<input type="button" value="Trigger">
I found also solution how to solve this problem, but I still dont know why using trigger() and stopPropagation() does not work.
Here is fixed code with using setTimeout():
$('button').click(function(e) {
e.stopPropagation();
$('div').toggleClass('active');
if ($('div').hasClass('active')) {
setTimeout(function() {
$('body').on('click.div', function(e) {
console.log('body clicked')
if (!$(e.target).closest('div').length) {
$('div').removeClass('active');
$('body').off('.div');
}
});
}, 0);
} else {
$('body').off('.div');
}
});
$('input').click(function() {
$('button').trigger('click');
});
div {
display: none;
}
div.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<div>This is hidden</div>
<input type="button" value="Trigger">
The reason is that the click on the input that you responded to by calling trigger propagates to body, and so it gets handled by the body handler you add. That is, the click that triggers this event handler:
$('input').click(function(){
$('button').trigger('click');
});
...gets processed; and then of course you're sending another one later.
To fix it, just stop that click from propagating:
$('input').click(function(e){
e.stopPropagation();
$('button').trigger('click');
});
$('button').click(function(e){
e.stopPropagation();
$('div').toggleClass('active');
if($('div').hasClass('active')){
$('body').on('click.div', function(e){
console.log('body clicked')
if(! $(e.target).closest('div').length){
$('div').removeClass('active');
$('body').off('.div');
}
});
}else{
$('body').off('.div');
}
});
$('input').click(function(e){
e.stopPropagation();
$('button').trigger('click');
});
div{
display: none;
}
div.active{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<div>This is hidden</div>
<input type="button" value="Trigger">
The reason your setTimeout version worked is that you were delaying hooking up your body click handler until after the click on the input had reached body, so it didn't get triggered by the click on the input.

how to hide parent when click anywhere outside the child element

I have this code
<style>
.Parent {width:500px;height:500px;background:#000}
.Parent .Child {width:250px;height:250px;background:#F00}
</style>
<div class="Parent">
<div class="child"></div>
</div>
<script>
$(document).ready(function() {
$('.Parent').click(function () {
$(this).hide()
});
/*
But if i click on <div class="Child"></div> ,
<div class="Parent"></div> won't get hidden .
*/
});
</script>
I want my code to hide'.parent',
When I click on areas in .Parent witch doesn't include .Child elementand if the areas I click was included in '.child' area , it don't do anything .
so what would u guys suggest ?
Simply make of event.stopPropagation(); to stop event of child from propagating to parent.
So script becomes:
$('.Parent').click(function () {
$(this).hide();
});
$('.child').click(function (e) {
e.stopPropagation();
});
See the fiddle: "http://jsfiddle.net/sftknxeo/1/"
just do this:
$('.Parent, .child').click(function(e) {
if ($(this).hasClass('child')) {
return false;
}
$(this).hide();
});
$('.Parent, .child').click(function(e) {
if ($(this).hasClass('child')) {
return false;
}
$(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='Parent' style='width:auto; padding:50px; border:red solid 1px;'>
<div class='child' style='width:200px; height:200px;border:green solid 1px;'>
child
</div>
</div>
You can use the event's target to determine what you have clicked on. This way you can also assign an event to happen if you have clicked on the child. (If need be.)
$('.Parent').click(function(e){
if(e.target == this){
$(this).hide()
}
});
DEMO
Quick and dirty version would be simply to add another event handler. Add a click handler to child that hides parent. Then if you click on parent, it hides itself, and if you click on child, it hides parent.
$('.child').click(function (e) {
$('.parent').hide();
});
Not the most elegant solution, sure, but it's quick and easy and should get the job done.
$('.Parent').click(function () {
$(this).css("visibility", "hidden");
$(".Parent" ).children().css("visibility", "visible");
});
If you just want to hide parent then it will do the needful.
Check for the clicked element by looking at the target property of the event object. Here is something you might want to do:
$(function () {
$('.Parent').click(function (e) {
if ($(e.target).hasClass("child")) {
return false;
}
$(this).hide();
});
});
$('.parent').click(function(e) {
if ($(this).hasClass('child')) {
return false;
}
$(this).hide();
});

Make onclick only affect the element, not it's children as well

I am making a personal website. I want to make it so that cliking the background changes the theme from dark to light and vice/versa. It works, but I dont want it to switch the theme if the user clicks on text, only the background of the webpage For example, if I click the text at the bottom it changes the css, but it should only do that if you click the white background.
Here is my code (Mainly checkout js/main.js, the switchTheme function and the index.html) and the website itself.
You are targeting your container class. Anytime that div (or anything in it) gets clicked, that event will fire. Try stopping the event propagation on your click event if $('this').selector === 'p' or whatever class you're using.
Also - not bad for 13 boss!
$( document ).click(function( event ) {
// if statement here
event.stopPropagation();
// else the regular behavior
});
Thanks everyone for your help! I'd almost given up and wanted to use a button to toggle it instead. The more you know!
And since this is an answer to my question: e.stopPropogation()
You can also do something like this:
document.querySelector('div').addEventListener('click', (e) => console.log("Heeeeyyy! Hoooo!"))
<div style="position: fixed; background-color: lightcoral; width: 500px; height: 180px;">
</div>
<div style="position: fixed; background-color: lightblue; width: 300px; height: 100px;">
<p>You can not click through me!</p>
</div>
Don't put the elements inside the "parent".
Move them together only by style.
How about
$("#container").on("click", "div", function(event){
event.stopPropagation();
switchTheme();
});
Add a test to see if the ID of the clicked element was actually the container.
function switchTheme( event ) {
if ( event.target.id === 'container' ) { //the container was clicked, and not a text node
if (dark) {
$("#container").css("background-color", "rgba(255,255,255,0.7);");
$("#container").css("color", "black");
dark = false;
} else {
$("#container").css("background-color", "rgba(0,0,0,0.7);");
$("#container").css("color", "white");
dark = true;
}
}
}
Try setting the following:
$("#container").on("click", "div", function(e){
e.stopPropagation();
});

Onclick change div style + onclick outside div remove style change

I would like to change the style on a div with an onclick... and remove the style when clicking somewhere outside of the div.
I have the following code setup... can someone help me to remove the style on the divs if you click anywhere else on the page?
<head>
<style type="text/css">
.account{
width: 100px;
height: 100px;
border: 1px solid #000;
}
.selected{
border: 2px solid #F00;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".account").click(function(){
$(".selected").removeClass("selected");
$(this).addClass("selected");
});
});
</script>
</head>
<body>
<h1>the test</h1>
<div class="account">test 1</div>
<div class="account">test 2</div>
</body>
Thank you very much for any help you can give me!!!
The following should do it:
$(document).on('click', function(e) {
if($(e.target).hasClass('account')) {
// do style change
}
else {
// undo style change
}
});
It binds the event handler to the entire document, so you'd have problems with any event handlers on more specific elements that call e.stopPropagation().
Try this.
$(document).ready(function(){
$(".account").click(function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
//This event handler will take care of removing the class if you click anywhere else
$(document).click(function(){
$(".selected").removeClass("selected");
});
});
Working demo - http://jsfiddle.net/yLhsC/
Note that you can use on or delegate to handle click event on account elements if there are many on the page.
Something like this.
Using on if using jQuery 1.7+
$('parentElementContainingAllAccounts').on('click', '.account', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
Using delegate
$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
You can achieve this behavior with attaching click listener on body element e.g.:
$("body").click(function(){
});
Try this:
$(document).ready(function() {
$('.account').click(function(e) {
e.stopPropagation();
$(this).addClass("selected");
});
$(document).click(function(){
$('.selected').removeClass('selected');
});
});

Categories

Resources