OnClick event for div inside lots of container Divs - javascript

I have an app I'm developing and I need a onclick() event to be fired when a <div> is clicked.
So in other words,
<div id="panda"></div>
$("#panda").click(function () {
console.log("some text");
});
So this statement works but now lets say I have,
<div id="panda">
<lots of children>
<div id="koala">
</div>
</lots of children>
</div>
$("#koala").click(function () {
console.log("doesnt work");
});
Now you see for the life of me I can't get koala to be clickable. The click event on parents works fine, and click evens for some empty divs I use as buttons work fine, but for some reason I cant get I filled child <div> to be clickable.
Any ideas what the case could be?
I tried this,
$('#panda').click(function(e){
if ($(e.target).is('#koala'))
{
console.log("koala");
}
});
But it just logs every click on the parent.

One option is to listen to the div children for panda.
$("#panda").on('click','div',function() {
console.log($(this).text()+' '+$(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="panda">
<div id="koala">
koala
</div>
<div id="bear">
bear
</div>
</div>

Try making the selector '#panda #koala' like this
$("#panda #koala").click(function () {
console.log("koala");
});

Here is an example,
<div id="panda">Panda
<div id="koala">Koala</div>
</div>
$("#panda").on('click', '#koala', function () {
alert("koala!!!");
});
Here is a Fiddle

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>

jQuery click event removing first element

Im working on a project and on my .ejs file I have a popup:
<div id="just-claimed-popup2" class="popup">
<h6>You just claimed:</h6>
<h2 id="card-just-claimed"></h2>
<p class="show-message">Show this Screen!</p>
<button id="deletePromoFromHome" class="close-button">Close</button>
</div>
On my javascript file I have a code that creates cards on a loop:
$('#promotion-container footer').before(`
<div class="promo card promo${i}">
<div class="promo-wrapper">
<div class="promo-header">
<h2 class="promo-title">${eventName}</h2>
<span class="close-promo-wrapper"><span class="close-promo"></span></span>
</div>
<div class="promo-info">
<span class="promo-details">
<p class="promo-detail promo-location">${eventLocation}</p>
<p class="promo-detail promo-date">${eventDate}</p>
<p class="promo-detail promo-time">${eventTime}
<span class="promo-description"></span>
<span class="buttonRedemp${i}">
<button class="redddButt load-button2" data="Reedem Card">Reedem Card</button>
</span>
</div>
</div>
</div>
`)
I want the card to disappear when people click 'redddButt', this is my code:
$(`#promotion-container .promo${i} .redddButt`).on('click', function(e){
e.stopPropagation();
$(`div.promo${i}`).addClass('toDelete')
var esc = $.Event("keyup", { keyCode: 27 });
$(document).trigger(esc);
$('#just-claimed-popup2').addClass('reveal');
$('#card-just-claimed').text(eventName);
$('#deletePromoFromHome').click(function(){
$('div.toDelete').fadeOut("slow")
})
})
PROBLEM: it always removes just the first card clicked and if you click the button in another one it stops working, so it only works once. If I console.log something the click event is happening, it's just not running the code inside of it.
Try changing your handler to:
$('body').on('click', `#promotion-container .promo${i} .redddButt`, function(e){
//function stuff here
}
The problem might be that elements are generated after the handler is attached.
Your code is missing some few closing tags. Since the cards are dynamically generated, try using (not tested):
var buttonContext;
$(document).on('click', '#promotion-container .promo .redddButt', function() {
buttonContext = $(this);
// Something
});
$('#deletePromoFromHome').click(function(){
buttonContext.closest('.promo').fadeOut("slow");
});
You can omit this line: $(div.promo${i}).addClass('toDelete');
The cards may have a single class (.promo) instead of (.promo#), unless may be you want to do further manipulation (say different styling etc).
Check this for more details on $(document): https://stackoverflow.com/a/32066793/3906884

Child div affects parent div in css and triggers jquery method

I have parent div with class a "very-big-div" that nests another "container-div" that by its turn also nests another child divs. The very big div's made to act like a button and the div that come right after it is a container that appears when I click the very big div.
<div class="very-big">
<div class="container">
<!-- Some other more nested divs that has anchors and buttons -->
<div class="friend-request">
<div class="button-div">
<button class="accept">Trigger</button>
<button class="refuse">Trigger</button>
</div>
</div>
</div>
</div>
The problem is 2 things first: the css problem has not yet been solved
I assigned a hover pseudo class for the "very-big-div", and whenever I hover the "container-div" the hover properties(background-color) is applied to the "very-big-div". This is not what I intend to make, I want to only hover "very-big" div for the hover to apply.
.very-big{
background-color:green;
}
The second problem is : I have a jquery that deals with the container so it is toggled on/off by the "very-big-div"
$(document).ready(function(){
$("#container-div").hide();
$("#very-big-div").click(function(){
$("#container-div").toggle();
});
});
the container has both anchor and button tags whenever I click the an anchor or a button inside the container it is toggled to close itself, and that is not what I want, what I want is just when I only press the "very-big-div" the toggle is activated.
Same as #Jhecht has given the answer, I have just inherited his to mine.
You can stop propagation of the click of child element that trigger toggle by using target and excluding all the child elements of your .very-big container as:
$(".very-big").click(function(e) {
var target = $(e.target);
if (!target.is('.very-big *')) {
$(".container").toggle();
}
});
Code Snippet:
$(document).ready(function() {
$(".container").hide();
$(".very-big").click(function(e) {
var target = $(e.target);
if (!target.is('.very-big *')) {
$(".container").toggle();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="very-big">
Other Text
<div class="container">
This is text to fill stuff out so I can click on it.
</div>
</div>
This works for me, but I am not sure if it is what you need.
Please add in the minimum HTML, CSS, and Javascript needed to fully recreate the error you are seeing.
$(document).ready(function() {
$(".container").hide();
$(".very-big").click(function(e) {
console.log(e);
var current = $(e.toElement);
if (current.is('.container')) {
e.stopPropagation();
return false;
}
$('.container').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="very-big">
Other Text
<div class="container">
This is text to fill stuff out so I can click on it.
</div>
</div>

How could i target a div and it's child to handle a click?

I have a <div class="stock"></div>wrapped around :
<div class="stockAdd"></div>
<div class="stockRemove"></div>
<div class="stockInput"></div>
I want to prevent a click inside my .stock to trigger a function. For now i have the following :
if ($(event.target).is('.stockInput') || $(event.target).is('.stockAdd') || $(event.target).is('.stockRemove')) {
console.log("Ajout stock");
return
}
Isn't there a better way to select thos three divs ? The $(event.target).is('.stock') don't get the job done when i click my nested divs.
Thanks
If I understand you correctly, you want to catch click events on .stockAdd, .stockRemove, and .stockInput, but not on other elements within .stock itself, is that correct?
If so, a delegated event can take care of that without any need to manually check the event target:
$('.stock').on('click', '.stockAdd, .stockRemove, .stockInput', function() {
alert("Clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAdd">stockAdd</div>
<div class="stockRemove">stockRemove</div>
<div class="stockInput">stockInput</div>
<div>No event</div>
</div>
I would strongly recommend against depending on event.target here; it's too fragile. Any HTML tags nested inside your desired targets would break things:
$('.stock').on('click', function(event) {
if (event.target.className=="stockAll") {
alert("clicked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAll">
This <b> will not work if someone clicks in the bold area</b> but works outside
</div>
</div>
You can add a separate class to all of them like .stock-inner and then grab them all with $('.stock-inner') or you can use a $("div[class^='stock-inner']) - this will grab the parent .stock div...
Also, to reject a click event within the handler you're gunna want to use e.preventDefault() where e is the event object.
the reason it doesn't work well on nested divs is they pass the conditional if in your example, to make it stricter you could add div to selector:
if ($(event.target).is('div.stockInput') || $(event.target).is('div.stockAdd') || $(event.target).is('div.stockRemove'))
You can attach the event on .stock and then filter using the event.target.
HTML
<div class="stock" style="border: 10px solid #000;">
<div class="stockAdd">Add</div>
<div class="stockRemove">Remove</div>
<div class="stockInput">Input</div>
</div>
JavaScript
$('.stock').on('click', function(e) {
if( e.target.className !== 'stock' ) {
console.log(e.target.className);
}
});
jsfiddle

Fire click event on a div excluding one child div and it's descendents

Inside that I have other child divs. Those have child divs too.
<div class="parent">
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
</div>
I want to add a click event that fires when I click any element inside parent div, including parent div, excluding child_1 div and its descendants.
Currently I tried with
jQuery(".parent").not(".child_1").click(function(event) {
});
But the click event works when I click on child_1 div and it's descendants.
What is the problem here? please help.
UPDATE
here i have another click event for child_1
jQuery(".child_1").click(function(event) {
});
You should do it like this.
$('.parent').on('click', function () {
// do your stuff here
}).find('.child_1').on('click', function (e) {
e.stopPropagation();
});
Here is a fiddle http://jsfiddle.net/BbX7D/1/
You still have to catch the click event on the elements that you want to exclude, otherwise the click will just bubble up to the .parent element.
Use the closest method to check if the clicked element is, or is a child of, an element with the class .child_1. Use stopPropagation to keep the event from bubbling:
$('.parent,.parent *').click(function(e){
if ($(this).closest('.child_1').length > 0) {
alert('in child_1');
} else {
alert('not in child_1');
}
e.stopPropagation();
});
Demo: http://jsfiddle.net/Guffa/tETCQ/
I think it should be
jQuery(".parent, .parent *").not(".child_1").click(function(event) {
});
Try this (fiddle):
(edit + updated fiddle)
I spotted a flaw. This version checks if the clicked element is or is inside an element which has the class 'exclude':
<div class="parent">
<div class="child_1 exclude">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
</div>
jQuery(".parent").click(function(event)
{
if ($(event.target).closest('.exclude').length>0) return false;
alert('hi');
});
a bit of an old question, but figured i'd throw out my resolution in case it helps anyone else.
this is pretty much what i did. this example uses your markup:
$('.parent').on('click', function(e) {
var $target = $(e.target);
if (!$target.parents('.child_1').length && !$target.hasClass('child_1')) {
// do what you need on the parent's click event
// add 'e.preventDefault()' here if you need
}
// no need to prevent default or stop propagation here
// this will allow click events on child elements to work
});

Categories

Resources