This question already has answers here:
How do I prevent a parent's onclick event from firing when a child anchor is clicked?
(25 answers)
Closed 5 years ago.
In this example I want the alert to be triggered when the black outer div is clicked but not when anything inside the inner div is clicked.
Currently when I click the inner button it triggers the alert.
$("#outer").click(function() {
alert("triggered");
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
I want inside the inner div nothing to trigger the alert. How do i do this?
(for some reason inner button isn't showing in snippet, here is codepen link: https://codepen.io/GuerrillaCoder/pen/Pmvmqx)
You just need to check for id of element, as inner is child element, it will always propagate the event to parent element (outer).
$("#outer").click(function(event) {
if(event.target.id=="outer"){
alert("triggered");
}
});
You can use event.stopPropagation(); when clicking the inner div:
$("#outer").click(function() {
alert("triggered");
});
$('#inner').click(function (evt) {
evt.stopPropagation();
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
In the click function check event target equal to outer
$("#outer").click(function(e) {
if (e.target.id === "outer"){
alert("triggered");
}
});
I think event.stopPropagation() method would be most useful solution.you only need to call it on the children of outer div:
$("#outer").on('click', function () {
alert("triggered");
}).children().on('click', function (e) {
e.stopPropagation();
});
Also check this Solution.
Pure javascript solution, if anyone cares -))
var inner = document.getElementById("inner");
var btn = inner.querySelector("button");
document.getElementById("outer").addEventListener("click", function(e) {
(e.target == btn) || (e.target == inner) ? console.log("click triggered from"+ e.target+". so we do not alert anything") : alert("something");
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
Another way to do this:
$("#outer").click(function() {
alert("triggered");
});
$("#inner").click(function(e) {
e.stopPropagation()
});
#outer{
position: absolute;
width: 100%;
height: 100%;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
}
#inner{
background-color: #fff;
width: 300px;
height: 300px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
<div id="inner">
<button>inner button</button>
</div>
</div>
You can use event.target to check event if is triggered by parent or by its children:
$("#outer").click(function(e) {
if( e.target !== this ) {
return;
} else {
alert("triggered");
}
});
Try this
$("#outer").click(function(e) {
e.target.id=='outer'?alert('triggered'):void(0);
});
Related
Please see code below:
const sectionIcon = document.querySelectorAll(".nk-section-icons")
const sectionContainer = document.querySelectorAll(".nk-sec-container")
const sectionIconHover = document.querySelectorAll(".nk-section-icons")
sectionIcon.forEach((sectionBtn)=> {
sectionBtn.addEventListener("click", (btns)=> {
// console.log(sectionIconHover)
const containerTarget = btns.currentTarget.parentElement.children[1]
const containerHoverTarget = btns.currentTarget.parentElement.children[0]
sectionContainer.forEach(items => {
if(items !== containerTarget) {
items.classList.remove("show")
// itemHover.classList.remove("rb")
}
})
sectionIconHover.forEach(itemHover => {
if(itemHover !== containerHoverTarget) {
itemHover.classList.remove("rb")
}
})
containerTarget.classList.toggle("show")
containerHoverTarget.classList.add("rb")
})
})
.nk-section-icons {
height: 30px;
min-width: 30px;
width: 30px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 3px;
background: yellow;
margin-bottom: 5px;
}
.nk-section-icons.rb {
background: black;
}
.nk-sec-container {
width: 300px;
min-width: 300px;
height: 100%;
background: red;
position: absolute;
z-index: 11;
box-shadow: rgba(17, 17, 26, 0.1) 0px 0px 16px;
border-radius: 6px;
left: 70px;
top: 0px;
}
.nk-sec-container.show {
background: green;
}
.nk-section-icons-container {
position: relative;
}
<div class="nk-section-l-icons">
<div class="nk-section-icons-container">
<div class="nk-section-icons fav" data-title="Favorites">btn</div>
<div class="nk-sec-container nk-sec-fav-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons recent" data-title="Recent">btn</div>
<div class="nk-sec-container nk-sec-recent-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons notifs" data-title="Notifications">btn</div>
<div class="nk-sec-container nk-sec-notif-c">
</div>
</div>
</div>
Hello guys, can you please see my code? Currently, it's working fine when I click the button it's working the classes are moved when I click any of the buttons. However, if I tried clicking the same button again the class rb is not removed but the show class is removed. Can you please help me with how can I fix this? Thanks
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if($("p").hasClass("main"))
{
$("p").toggleClass("main1");
}
else
{
$("p").toggleClass("main");
}
});
});
</script>
<style>
.main {
font-size: 120%;
color: red;
}
.main1 {
font-size: 120%;
color: green;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><b>Note:</b> Click the button more than once to see the toggle effect.</p>
</body>
</html>
Use toggling: Toggle between adding and removing the "main" class name for all elements
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.
I am looking to add two anchor links when the mouse enters #introand hide intro and when the mouse leaves the original intro shows.
$("#intro").on("mouseenter", function() {
var link = $("<a>");
var link2 = $("<a>");
link.attr("href", "en.html");
link2.attr("href", "fr.html");
link.text("Welcome!");
link2.text("Bienvenue!");
$("#intro").addClass("link link2");
$("#intro").html(link && link2);
});
$("#intro").on("mouseleave", function() {
show(slow, this)
});
jQuery:
$(document).ready(function(){
$("#intro").mouseover(function() {
$(this).addClass("link link2");
$("#intro a").show();
$("#intro h1").hide();
});
$("#intro").mouseout(function() {
$(this).removeClass("link link2");
$("#intro a").hide();
$("#intro h1").show();
});
});
#intro {
width: 200px;
height: 200px;
background-color: red;
margin: 20px auto;
}
#intro a{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="intro">
<h1>Intro</h1>
<a href='en.html'>Welcome!</a>
<a href='fr.html'>Bienvenue!</a>
</div>
CSS:
#intro {
width: 200px;
height: 200px;
background-color: red;
margin: 20px auto;
display: flex;
justify-content: center;
align-items: center;
}
#intro a,
#intro:hover h1{
display:none;
}
#intro:hover a{
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="intro">
<h1>Intro</h1>
<a href='en.html'>Welcome!</a>
<a href='fr.html'>Bienvenue!</a>
</div>
I am basically working with a hamburger menu. At this stage, I have made a menu and when it is clicked, a cross will appear instead of it. It is all working well.
function drop(){
let bars = document.querySelector("div.bar");
let cross = document.querySelector("div.cross");
bars.style.display = "none";
cross.style.display = "flex";
}
div.bar {
display: flex;
transition: 1s;
cursor: pointer;
justify-content: space-between;
flex-direction: column;
height: 30px;
color: gray;
}
.ibar {
display: inline-flex;
width: 40px;
height: 5px;
background-color: black;
border-radius: 31%;
}
.cross{
display: none;
justify-content: center;
align-items: center;
width: fit-content;
font-size: 70px;
color: gray;
}
<div class="bar" id="bar" onclick="drop()">
<div class="ibar"></div>
<div class="ibar"></div>
<div class="ibar"></div>
</div>
<div class="cross" id="hiddenCross">×</div>
But the main problem I am facing is below:
In my function, when I add an if statement like this:
if (cross.style.display === "none"){
bars.style.display = "none";
cross.style.display = "flex";
}
then the two lines of code inside the if block (which are changing display properties) are not working.
I first thought it is some kind of property of document.querySelector which is restricting this kind of behaviour. But when I used the id's to execute the same function, the same problem persists.
The style property of elements only checks inline styles. Use getComputedStyle instead so that all CSS rules will be found.
function drop(){
let bars = document.querySelector("div.bar");
let cross = document.querySelector("div.cross");
if (window.getComputedStyle(cross).display === "none"){
bars.style.display = "none";
cross.style.display = "flex";
}
}
div.bar {
display: flex;
transition: 1s;
cursor: pointer;
justify-content: space-between;
flex-direction: column;
height: 30px;
color: gray;
}
.ibar {
display: inline-flex;
width: 40px;
height: 5px;
background-color: black;
border-radius: 31%;
}
.cross{
display: none;
justify-content: center;
align-items: center;
width: fit-content;
font-size: 70px;
color: gray;
}
<div class="bar" id="bar" onclick="drop()">
<div class="ibar"></div>
<div class="ibar"></div>
<div class="ibar"></div>
</div>
<div class="cross" id="hiddenCross">×</div>
Every time you click on the hamburger, drop() function fires and inside this function you set style.display property of "cross" element to flex. But the code inside if statement will be executed only when style.display property of "cross" element is set to none, but it happens never.
You can just use any additional class, for example, "hidden" and toggle it every time you click on menu:
when bar has class "hidden" - cross should have this class and vice versa .
And in the css file class "hidden" should have display: none property.
I'm trying to rotate the shape x with an click event using jQuery and CSS. I want to target the x with an id and toggle a class of rotate on and off. The rotate class uses the CSS transform property to create the effect.
$('#x').click(function() {
$('#x').toggleClass('.rotate');
});
.container {
height: 500px;
width: 960px;
margin: 0 auto;
display: flex;
background: skyblue;
}
#x {
margin: auto;
font-size: 9em;
color: green;
}
.rotate {
transform: rotate(7deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="x">x</div>
</div>
In some functions from jquery such as addClass, removeClass, toggleClass, you don't need to specify the selector with a dot, because you already are telling thats is a class. example:
$(this).removeClass("yourClass");
$(this).addClass("yourClass");
$(this).toggleClass("yourClass");
Your question fixed:
$('#x').click(function(){
$('#x').toggleClass('rotate');
});
.container{
height: 500px;
width: 960px;
margin: 0 auto;
display: flex;
background: skyblue;
}
#x{
margin: auto;
font-size: 9em;
color: green;
}
.rotate{
transform: rotate(7deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="container">
<div id="x">x</div>
</div>
You made an error with your Javascript:
$('#x').click(function() {
$('#x').toggleClass('.rotate');
});
you are calling toggleClass so you don't need to add a . to your selector. so:
toggleClass('.rotate')
should be:
toggleClass('rotate')
I want to hide all the div with similar id if not clicked on any of those div's. In my code it is working only for the first div since I have use index[0] to fetch the id. I want to generalize it to work for all the id.
Here is the code:
$(window).click(function(e) {
if (e.target.id != $('[id^=div_]')[0].id) {
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>
FIDDLE
The simple solution here is to use a common class on all the elements. You can then use is() to determine if e.target was one of those elements and hide/show them as needed. Try this:
$(window).click(function(e) {
if (!$(e.target).is('.div')) {
$('.div').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>
I cannot make any changes in HTML like adding classes
In that case you can check the id of the clicked element to see if it begins with div_. If not, then hide all the divs, something like this:
$(window).click(function(e) {
if (e.target.id.indexOf('div_') != 0) {
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>
Hey you can use this function
if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
$('[id^=div_]').hide();
}
filter function will filter the selected div in list of div whoes id starts with div
$(window).click(function(e) {
if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>