just wondering why when i click inside the container the alert popups despite the if statement for it to not show on click.
Also how would I test for the children inside?
https://jsfiddle.net/w8fd3m67/
$(window).on("click", function(event) {
var container = $("#container");
if ((event.target) !== container) {
alert("clicked outside");
}
});
body {
height: 600px;
}
#container {
padding: 2rem;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
Cheers
You should use .is()
if($(event.target).is(container))
Compare the id. Here $("#container") is a jquery object
$(window).on("click", function(event) {
if ((event.target.id) !== 'container') {
alert("clicked outside");
}
});
body {
height: 600px;
}
#container {
padding: 2rem;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
Use the .is() function to compare the event target to your JQuery element :
$(window).on("click", function(event) {
var container = $("#container");
if ($(event.target).is(container)) {
alert("clicked outside");
}
});
body {
height: 600px;
}
#container {
padding: 2rem;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
You're comparing a DOM element to a jQuery object which will never match. Create a jQuery object out of the target and check if it is a descendant of #container. This also works if you have child elements under #container.
Updated fiddle
$(window).on("click", function(event) {
if ($(event.target).closest('#container').length == 0){
alert("clicked outside");
}
});
try this:
$(window).on("click", function(event) {
var container = $("#container");
if ((event.target) !== container[0]) {
alert("clicked outside");
}});
Related
I have a menu that open a sub-menu section onclick (let's name the container: "sub-menu").
I would like "sub-menu" to disapear if the user click outside of it / on the rest of the page.
It seems to be solved on How do I detect a click outside an element?
But I can't get how to use the code snipet from the second most popular answer:
export function hideOnClickOutside(selector) {
const outsideClickListener = (event) => {
const $target = $(event.target);
if (!$target.closest(selector).length && $(selector).is(':visible')) {
$(selector).hide();
removeClickListener();
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
Could you please guide me on how to use it?
I edited, and included a basic example. -> I want sub menu to also close when clicking on the "white" space. But not on the parent "main menu" element.
document.getElementById("main-menu").addEventListener("click", function() {bouttonexpand('sub-menu-class')});
function bouttonexpand(id) {
var elemeacacher = document.getElementsByClassName(id);
if (elemeacacher[0].style.display != "none"){
for(var y=0;y<elemeacacher.length;y++)
elemeacacher[y].style.display = "none";
}
else {
for(var y=0;y<elemeacacher.length;y++)
elemeacacher[y].style.display = "block";
}
}
#main-menu {
display:inline-block;
height:20px;
width:100px;
background: blue;
padding: 5%;
}
#sub-menu {
display:inline-block;
height:50px;
width:50px;
background: red;
display: none;
}
<div><div id="main-menu">Main menu</div></div>
<div><div id="sub-menu" class="sub-menu-class">Sub menu</div></div>
Thanks
By using jQuery, you can bind to the document click event and hides the div container when the clicked element isn’t the container itself or descendant of the div element.
var container = $("#sub-menu");
if (!container.is(event.target) && !container.has(event.target).length) {
container.hide();
}
If you want to hide that container without being tested the container itself or descendant of the div element just remove the condition and simply use container.hide();.
Also, rather than setting display: none; on sub-menu in the CSS, set it manually so that you can toggle the sub-menu from the very first click.
Have a look at the snippet below:
var x = document.getElementById("sub-menu");
x.style.display = "none";
$(document).click(function (evt) {
if ($(evt.target).is('#main-menu')) { // control click event if it's main-menu
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
else {
var container = $("#sub-menu");
if (!container.is(event.target) && !container.has(event.target).length) { // if you don't want that remove the condition and write container.hide(); only
container.hide();
}
}
});
#main-menu {
display: inline-block;
height: 20px;
width: 100px;
background: blue;
padding: 5%;
}
#sub-menu {
display: inline-block;
height: 50px;
width: 50px;
background: red;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<div id="main-menu">Main menu</div>
<div id="sub-menu" class="sub-menu-class">Sub menu</div>
I have this div which shows/hides with display:none/block by clicking on an id #cart. The div opens and closes by clicking on element with the id but I want to close the div on body click too. How can I do it please?
Code I am using is below:
jQuery("#cart").on("click", function() {
jQuery(".shopping-cart").fadeToggle( "fast");
});
jQuery("#cart, body").on("click", function() {
jQuery(".shopping-cart").fadeToggle("fast");
});
What you can do is add a listener to the entire window and check for clicks. When there is a click, we check which element has been clicked and check on whether it's the element. We repeat this for the parent element as well.
<!DOCTYPE html>
<html>
<head>
<script>
function checkClickOutsiteElement(clickedElement, elementToCheck){
var iterator = clickedElement;
while(true){
// The click was in the element.
if( iterator === elementToCheck )
return;
// Go to the parent.
if( !iterator.parentElement ){
alert('outside menu');
return;
}
iterator = iterator.parentElement;
}
}
window.addEventListener('click', function(event){
checkClickOutsiteElement(event.target, document.getElementById('menu'));
});
</script>
</head>
<body>
<div class="wrapper">
<div id="menu" style="width: 100px; height: 100px; background-color: red;"></div>
</div>
<div class="wrapper">
<div id="not_menu" style="width: 100px; height: 100px; background-color: green;"></div>
</div>
</body>
</html>
You probably want two separate functions, since your cart button should toggle both ways, but the body click handler should only toggle out.
Protip: on() isn't doing anything for you that click() wouldn't, the way you're using it. The latter is a bit cleaner.
jQuery("#cart").click(function() {
jQuery(".shopping-cart").fadeToggle("fast");
});
jQuery("body").click(function() {
jQuery(".shopping-cart").fadeOut("fast");
});
Protip 2: Easily and safely alias jQuery to $ like so:
jQuery(function($) { // document ready with dollar alias
$("#cart").click(function() {
...
});
I have this div which shows/hides with display:none/block by clicking
on an id #cart. The div opens and closes by clicking on element with
the id but I want to close the div on body click too.
In vanilla javascript, you can:
write a function to show / hide the div
add a click event listener to #cart
add a click event listener to body
Working Example:
// Grab #cart
const cart = document.getElementById('cart');
// Grab .myDiv
const myDiv = document.getElementsByClassName('div')[0];
// Function to toggle .myDiv
const toggleMyDiv = (e) => {
if (e.target === e.currentTarget) {
myDiv.dataset.display = (myDiv.dataset.display === 'show') ? 'hide' : 'show';
}
}
// Add Click Event Listener to #cart
cart.addEventListener('click', toggleMyDiv, false);
document.body.addEventListener('click', toggleMyDiv, false);
body,
#cart {
cursor: pointer;
}
div {
display: inline-block;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
font-weight: bold;
}
#cart {
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
}
.div {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
}
.div[data-display="show"] {
opacity: 1;
}
.div[data-display="hide"] {
opacity: 0;
}
<div id="cart">Cart</div>
<div class="div show" data-display="show">myDiv</div>
how to hide a "cube-2" by click on "click-me" that its included by "cube-2"?
I made an event but it deleted all of my cube-2, I want to hide cube-2 one by one. Anyone can solve this? please help me.
$('.cube-1').click(function name(params) {
$('.cube-1').append('<div class="cube-2"><div class="click-me">click me to hide this cube</div></div>');
// how to add event click on "click-me" to hide "cube-2"??
})
.cube-1 {
width: 100px;
height: 100px;
float: left;
background: blue;
}
.cube-2 {
margin-left: 100px;
width: 100px;
height: 100px;
float: left;
background: red;
}
.click-me {
width: 100%;
height: 50px;
background: white;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
</head>
<div class="cube-1"></div>
</html>
You can add an id to your cube-2 div and it's corresponding click-me anchor tag and remove only the div with that Id.
You may also want to check Template string
$('.cube-1').click(function name(e) {
var cubeCounter = 1;
if (e.target.className == "cube-1") {
$('.cube-1').append(`<div class=cube-2 id=cube-${cubeCounter}><div class=click-me id=${cubeCounter}>click me to hide this cube</div></div>`);
cubeCounter++;
}
})
$(document).on('click', '.click-me', function name(e) {
var cubeId = e.target.id;
$(`#cube-${cubeId}`).remove();
})
you need to handle dyanamic click event of second cube and prevent click event of parent control, when child cube is clicked
$('.cube-1').click(function name(e) {
if(e.target.className == "cube-1")
{
$('.cube-1').append('<div class="cube-2"><div class="click-me">click me to
hide this cube</div></div>');
}
});
$(document).on('click','.cube-2',function name(e)
{
$(this).remove();
// how to add event click on "click-me" to hide "cube-2"??
})
Please check working demo [Link]
https://jsfiddle.net/2L3k5hcb/
You just need to bind your click on div while you appending your cube-2.
Add your script as below-
$('.cube-1').on('click',function(event){
$('.cube-1').append('click me to hide this cube');
})
function myFunction(param) {
event.stopPropagation();
$(param).remove();
}
you can use below method for dynamicly generated elements.
$(document).on('click', '.click-me', function (e) {
$(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this
$(document.body).on('click', '.cube-2', function (event) {
$(this).hide();
});
$('.cube-1').click(function(event) {
if(event.target.className =='cube-1')
$('.cube-1').append('<div class="cube-2"><div class="click-me">click me to hide this cube</div></div>');
// how to add event click on "click-me" to hide "cube-2"??
})
.cube-1 {
width: 100px;
height: 100px;
float: left;
background: blue;
}
.cube-2 {
margin-left: 100px;
width: 100px;
height: 100px;
float: left;
background: red;
}
.click-me {
width: 100%;
height: 50px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cube-1"></div>
I have created several div-elements under class name "image-part" and am trying to animate them using this script:
$(document).ready(function() {
$('.image-part').each(function() {
var id = setInterval(frame, 3000);
function frame() {
if ($(this).css("visibility") === "hidden") {
$(this).css("visibility", "visible");
} else {
$(this).css("visibility", "hidden");
}
}
});
});
.image-part {
width: 33.33%;
height: 60px;
background-color: black;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="image-part" style="visibility:hidden"></div>
<div class="image-part"></div>
<div class="image-part"></div>
<div class="image-part"></div>
Nothing is happening, is there anyone that can help?
Thanks!
The issue is because the scope of this within the setInterval() handler will not be a reference to any of the .image-part elements.
To fix this you can re-arrange the logic so that you execute the each() loop within the interval, like this:
$(document).ready(function() {
setInterval(function() {
$('.image-part').css('visibility', function(i, v) {
return v == 'visible' ? 'hidden' : 'visible';
});
}, 3000);
});
.image-part {
width: 33.33%;
height: 60px;
background-color: black;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="image-part" style="visibility:hidden"></div>
<div class="image-part"></div>
<div class="image-part"></div>
<div class="image-part"></div>
Note that I changed the logic to be more succinct by using a single call to css() with a function provided. The outcome is identical to your original intention, though.
I need switches between 2 icons (in this example colors) by css class on element if i click on it. I have this code (which is not working):
$( ".play" ).on('click', function(event) {
event.preventDefault();
$(this).removeClass('play');
$(this).addClass('stop');
console.log('play');
});
$( ".stop" ).on('click', function(event) {
event.preventDefault();
alert();
$(this).removeClass('stop');
$(this).addClass('play');
console.log('stop');
});
.play {
background-color: black;
}
.stop {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You appear to be using Event Delegation with jQuery, but I think you might have it a little wrong:
$("body")
.on("click", ".play", function(event) {
// change "play" to "stop"
})
.on("click", ".stop", function(event) {
// change "stop" to "play"
});
You want to attach the click handler to the <body> tag, and then provide jQuery with the event name, CSS selector, and event handler.
Reference: http://api.jquery.com/on/
$( "a" ).on('click', function(event) {
event.preventDefault();
var anchor = $(this);
if(anchor.hasClass('play'))
{
$(this).removeClass('play');
$(this).addClass('stop');
console.log('play');
}
else
{
alert();
$(this).removeClass('stop');
$(this).addClass('play');
}
});
.play {
background-color: black;
}
.stop {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Don't bind the event handlers to a class, bind it to the id of your element. Then you can just see what class the element has and switch between them.
Here is a working codepen
HTML:
CSS: Doesn't change
JS:
$( "#clickable" ).on('click', function(event) {
if($(this).hasClass('play')) {
$(this).removeClass('play');
$(this).addClass('stop');
} else {
$(this).removeClass('stop');
$(this).addClass('play');
}
});
As easy as.....
$( "a" ).on('click', function(event) {
event.preventDefault();
$(this).toggleClass('stop');
$(this).toggleClass('play');
});
.play {
background-color: black;
}
.stop {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Or you can also do this:-
css:
.play {
background-color: black;
}
.stop {
background-color: green;
}
JS:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".play").on('click', function(event) {
if ($('a').hasClass('stop')) {
$(".play").addClass("play").removeClass("stop");
} else {
$(".play").addClass("stop");
}
console.log('play');
});
});
</script>
html and css remain the same.