Click Node Without Clicking Parent Node - javascript

I have a <button> that is wrapped inside of a <div>. I want to be able to click the button without actually clicking on the <div> as well. The <button> needs to remain inside of the <div>.
Heres the code:
<div onclick='console.log("Div was clicked.")'>
This is the Div
<button onclick='console.log("Button was clicked.")'>Button</button>
</div>
When i click on the <div> console logs "Div was clicked.".
When i click on the <button> console logs "Button was clicked." AND "Div was clicked.".
How can i click on the <button> WITHOUT a click registering on the <div>?
Any alternatives/workarounds?
Thanks guys.

Add event.stopPropagation() in your button onclick handler.
<div onclick='console.log("Div was clicked.")'>
This is the Div
<button onclick='event.stopPropagation(); console.log("Button was clicked.")'>Button</button>
</div>

You can also check the target.id. Here's a small example using jQuery:
HTML:
<div id="parent">
This is the Div
<button onclick='console.log("Button was clicked.")'>Button</button>
</div>
jQuery:
$('#parent').click(function(e)
{
if (e.target.id == "parent") {console.log("Div was clicked.")}
});
Fiddle: http://jsfiddle.net/mrnLLvac/

Add the following JavaScript function:
function CancelMouseEvent (Event)
{
Event = Event ? Event : window.Event;
if (Event.stopPropagation) { Event.stopPropagation(); }
if (Event.preventDefault) { Event.preventDefault(); }
Event.cancelBubble = true;
Event.cancel = true;
Event.returnValue = false;
return false;
}
Now use this in HTML:
<button onclick='console.log("Button was clicked."); CancelMouseEvent(event);'>Button</button>

Usually, it is recommended to not use the older method of event binding to HTML. It is recommended to use addEventListener, that way your JS stays in your JS and your HTML is only HTML.
A simple example below:
<div id="wrap">
This is the Div
<button id="button">Button</button>
</div>
<script>
var wrap = document.getElementById('wrap');
wrap.addEventListener('click', handleClick, true);
function handleClick(e) {
e.stopPropagation;
if (e.target.id === 'button') {
// do stuff because button was clicked
console.log('button was clicked');
}
}
</script>
EDIT: why your code didnt work
Your code didn't work because events "bubble" up the DOM (they can also be "captured"...), in your case even if you clicked "button", the following events were triggered:
Button (target) === (bubbling up to its parent) === DIV (its event was also triggered).

Related

JS - Stop function above current function

I have a jQuery click event which adds a class (active) to a dropdown.
In the dropdown there are boxes (with the class generically called box).
Currently the jQuery event fires anytime you click anywhere in the item class, but if you click the box it also closes the dropdown. Thus I am adding an if statement above the addClass part which checks if you clicked a box.
Here's the html:
<div class="trainee-item">
<div class="dropdown">
<div class="box"></div>
</div>
</div>
and here's the JS:
$('.item').click(function(e) {
$('.box').click(function() {
console.log('stop!!!');
});
if ($(this).children('.dropdown').hasClass('active')) {
$(this).children('.dropdown').removeClass('active');
return;
}
$(this).children('.dropdown').addClass('active');
});
I've tried return (where the console.log('stop!!!!'); currently is, but that only stops the $('.box').click(function() (the immediate "parent" function). I am trying to stop the function above that one
Any help? thanks
One way would be
$('.item').click(function(e){
if (e.target.className=="box"){
e.preventDefault()
return
}
})
$('.item').click(function(e) {
if (e.target.className=="box"){
e.preventDefault()
alert("don't close it!")
return
}
if ($(this).children('.dropdown').hasClass('active')) {
$(this).children('.dropdown').removeClass('active');
return;
}
$(this).children('.dropdown').addClass('active');
});
.dropdown{display:none;width:100px;height:100px;background:#bbb}
.active{height:120px;}
.item{height:20px;background:#ccc}
.active.dropdown{display:block}
.box{border-bottom:1px solid #999;padding:10px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trainee-item item">
<div>Click me</div>
<div class="dropdown">
<div class="box">hi</div>
</div>
</div>
You should separate these into separate click events. You should also delegate them, since you'll trigger both due to event bubbling. It's been a while since I've written jQuery, but from what I remember you should be using .on();, since you can delegate with that method.
I'll leave the delegation as homework for you, but here's how you should be approaching this issue:
$('.item').on('click', function(e, el) {
var $child = $(this).children('.dropdown'),
activeClass = 'active';
$child.hasClass(activeClass) ? $child.removeClass(activeClass) : $child.addClass(activeClass);
});
$('.box').on('click', function(e, el) {
console.log('box clicked');
});

Prevent onclick from firing

I was working around with form submissions in html. Please take a look at below code
<form id="form1">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script>
$("#btn1").click(function (event) {
alert("event triggered");
if(some_condition == true){
// stop firing onclick method but it always submits the form
event.stopImmediatePropogation(); // not working
event.preventDefault(); // not working
event.stopPropogation(); // not working it's for bubbled events
}
});
function clicked(){ alert("clicked me"); }
</script>
I want to stop clicked() function from firing which is attached to inline onclick attribute. I would like to run my jquery click function and if something goes wrong, I dont want to trigger onclick but it always runs clicked() function. Could any one help me. Any help is greatly appreciated.
The order in which an onxyz handler is called relative to dynamically-attached handlers varies from browser to browser, so your handler may well not run before the original does.
To deal with that, you save and remove the onclick handler:
var btn = $("#btn1");
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
Then, in your handler, if you want that function to be called, you call it:
clickhandler.call(this, event);
Example:
// Get the button
var btn = $("#btn1");
// Save and remove the onclick handler
var clickHandler = btn[0].onclick;
btn[0].onclick = false;
// Hook up your handler
$("#btn1").click(function(event) {
alert("event triggered");
if (!confirm("Allow it?")) {
// Disallowed, don't call it
alert("stopped it");
} else {
// Allowed, call it
clickHandler.call(this, event);
}
});
// The onclick handler
function clicked() {
alert("clicked me");
}
<form id="form1" onsubmit="return false">
<button id="btn1" onclick="clicked();">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Try event.stopPropagation()
api docs
if condition is true then remove the 'onclick' attribute
if (some_condition == true) {
$("#btn1").removeAttr('onclick').click(function(event) {
alert("event triggered");
//do something
});
}
function clicked() {
alert("clicked me");
}
I am sharing a quick workaround without knowing why you cannot add logic to stop adding "onclick="clicked();" code which you are saying getting automatically added.
I recommend you hide button with id as "btn1". Add style display:none. You donot need on ready function for this but simply add style attribute to the button btn1 or if that is also not possible directly then use jQuery to do that post document ready.
Read :
How to change css display none or block property using Jquery?
Then add a new button to the form using jQuery with id as "btn2" and add register the btn2 click event as well. DO this after form load.
<form id="form1">
<div id="newbut">
<button id="btn1" onclick="clicked();">Submit</button>
</div>
</form>
jQuery("#newbut").html('<button id="btn2">Submit</button>');
$(document).on('click', '#btn2', function(){
// Your Code
});
Refer below url to how to register click event for new button:
Adding click event for a button created dynamically using jQuery
jquery - Click event not working for dynamically created button
Can't you do the condition check and the clicked() logic in one function? i.e
<script>
function clicked() {
if(some_condition == true){
return;
}
alert("clicked me");
}
</script>

Initiate click on div using tab and enter

I have a and div element
link
<div tabindex="0">div</div>
And click event handlers
$("a").on("click",function(){
alert(" a click")
});
$("div").on("click",function(){
alert("div click")
});
Using keyboard tab I can navigate to a link ,press Enter and see alert,but I can't do this for div.
Is it possible initiate click event for div as same as for a tag,without using any other events(keypress)?
JSfiddle
You can create a custom event like this:
$("div").on("click enter",function(){
alert("div click")
})
.on('keypress', function(e) {
if(e.which === 13) {
$(this).trigger( 'enter' );
}
});
DEMO
I know this is an old post but i thought i might add something.
PeterKA has a nice solution but i would improve it just a bit.
Instead of triggering a new custom event like enter just trigger the click event. This way you don't need to modify existing code and add the new event to every listener you have.
Each element that listens to click will be triggered.
$('.btn').on("click",function(){
alert("div click")
})
// at a centrelized spot in your app
$('.btn').on('keypress', function(e) {
if(e.which === 13) {
$(this).trigger('click');
}
});
$(document).ready(function(){
$('#firstDiv').focus(); // just focusing the first div
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstDiv" class="btn" tabindex="0">div</div>
<div class="btn" tabindex="0">div</div>
<div class="btn" tabindex="0">div</div>

Javascript shows ids of both body and clicked elemnt on click event

I have one js function,say check(val). I call it on click event on body and one tag. When I click on body it correctly shows id of body element. But,when when I click on , it shows ids of both and body!
I just want to display id of on click and on body's click event some other action to be executed.
My sample HTML code:
<body id="body" onclick="check(this.id);">
<a href="#" id="ele" onclick="check(this.id)">Hello</div>
</body>
JS Code :
function check(val)
{
if(val=="ele"){
alert("element is clicked");
}else if(val=="body"){
alert("Body is clicked");
}
}
you need to stop Propagation of event using event.stopPropagation() method. already #StephenThomas mentioned this in comment of your question.
try this,
HTML markup:
<body id="body" onclick="check(event,this.id);">
<a href="#" id="ele" onclick="check(event,this.id)">Hello</div>
</body>
javascript code:
function check(event, val) {
if (val == "ele") {
alert("element is clicked");
event.stopPropagation(); //here we stop propagation of the event
} else if (val == "body") {
alert("Body is clicked");
}
}
SEE THIS DEMO.
I hope this would help you...
Every browser handles event bubbling differently. Some will show both and some will only show the link. You can change the function to fit every clicked element:
function check(val)
{
alert("Clicked element type is: " + val.nodeName);
}
This way you don't need any id detection because you check the type of the node itself.
You are getting both ids because when you click on the anchor you are also clicking on the body since the anchor is a child of the body element.
important note:when you click on the anchor you are also clicking on the body
use like this
<body id="body" onclick="check(this);">
Hello
</body>
Javascript
function check(val)
{
if(val.id.toString()=="ele"){
alert("element is clicked");
}else if(val.id.toString()=="body"){
alert("Body is clicked");
}
}

How to stop onclick event in div from propagating to the document?

I want to stop propagation of this div's onclick event to the document? When the user click on the "div", both alerts appear: 1) the div's alert and 2) the document's alert. I want to suppress the document alert.
I know how to do it using addEventListener, but is there another way to to do it? The problem below is that I don't know how to get ahold of the event -- I tried "event = element.onclick", shown below, but that doesn't work. How do I get the event?
<head>
<script>
function showMenu(element) {
alert("div clicked");
event = element.onclick; // HOW TO GET HOLD OF THE EVENT?
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
document.onclick = function() {
alert('document clicked');
};
</script>
</head>
<body>
<div id="foodmenu" onclick="showMenu(this);">Click inside this div</div>
or click outside the div.
</body>
Change your function definition to include the event:
function showMenu(event, element) {
alert("div clicked");
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
Then change the call to pass in the event:
div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>
Try EventListeners:
html:
<div id="fooddmenu">Click inside this div</div>or click outside the div.​​​​​​​​​​
js:
function showMenu(e) {
alert("div clicked");
}
document.onclick = function() {
alert('document clicked');
};
window.onload = function(){
document.getElementById("fooddmenu").addEventListener("click", function(e){
showMenu(this);
e.stopPropagation();
});
};
Add the onclick to the body element.
Douglas,
It does stop the event from getting bubbled up.
Check this out http://jsbin.com/ahoyi/edit
here, if you comment the alert statement, it will show 2 alerts on clicking the smaller box else only one.
Hope this helps.
well, that's a jquery code.
$("#id") same as document.getElementById("id")
.click function is same as addEvent("click", function() { ... } );
so basically both the functions there are click handlers for Parent and Child DIVs.
Observe the output by commenting / uncommenting the "return false;" statement.
Hope that helps.
By the way, sorry for that "$" confusion.
$("div").click(function(){
...
...
...
return false; //this will stop the further propagation of the event
});
Add Pointer-events: none to the particular element will help to stop pointer events.
event.StopPropagation() will help us to avoid child propagating

Categories

Resources