calling different functions from inside and outside of div - javascript

I am having a div inside a div. And I want to call a function on the click of outer div and another function on the click of inner div. Is it possible to do so?
<div onclick="function1()">
<div onclick=function2()></div>
</div>

Yes, this is very much possible. And the code you have will get the job done.
NOTE: You need to add event.stopPropagation() in case you want to prevent the bubbling of the event from the inner function.
Try this out:
function function1() {
console.log("From outer div");
}
function function2(event) {
console.log("From inner div");
event.stopPropagation();
}
#outer-div {
width: 100px;
height: 100px;
background: yellow;
}
#inner-div {
width: 50px;
height: 50px;
background: red;
position: relative;
top: 25px;
left: 25px;
}
<div id="outer-div" onclick="function1()">
<div id="inner-div" onclick="function2(event)"></div>
</div>

Yes, it is; one way to do it is the way you've done it in your question, except:
You need quotes around the inner onclick attribute value, just as you have around the outer onclick attribute value.
You probably want to pass event into at least the inner one:
<div onclick="function2(event)"></div>
and then have it call stopPropagation on that:
function function2(event) {
event.stopPropagation();
}
so that the click event isn't propagated to the parent (doesn't bubble any further). If the click bubbles, function1 will be called as well.
Example:
function function1() {
console.log("function1 called");
}
function function2(event) {
event.stopPropagation();
console.log("function2 called");
}
<div onclick="function1()">
<div onclick="function2(event)">this div fires function2</div>
clicking here will fire function1
</div>
You might also consider modern event handling rather than onxyz-attribute-style event handlers; search for examples of addEventListener for details; my answer here also has a useful workaround for obsolete browsers.

Related

How can I prevent parent element event execution from code inside children event

My question in the title probably looks vague. And I sketched an example for the question:
container.onclick = () => {
alert(0);
};
content.onclick = () => {
alert("how can I prevent here appearance alert(0) from parent element event?");
//how can I prevent parent event by content clicked?
};
#container{
height: 100px;
background-color: gray;
}
#content{
height: 50px;
width: 150px;
background-color: green;
}
<div id="container">
<div id="content"></div>
</div>k
This is a simple example. In a real project, I can't combine these two events into one, because the first one is programmatically assigned somewhere in the bowels of my framework and it shouldn't be removed from the EventListener after clicking on content
In General, is it possible to somehow interrupt the execution of the call chain event by clicking in the DOM layers? I tried to do this:
content.onclick = () => {
alert("how can I prevent here appearance alert(0) from parent element event?");
e.preventDefault();
return false;
//how can I prevent parent event by content clicked?
};
But this, of course, was not successful
You should pass the event by dependency injection to the specific method (content.onclick) and then stop the propagation of it.
container.onclick = () => {
alert(0);
};
content.onclick = (e) => {
e.stopPropagation();
alert("VoilĂ , this prevent that appears alert(0) from parent element event.");
};
#container{
height: 100px;
background-color: gray;
}
#content{
height: 50px;
width: 150px;
background-color: green;
}
<div id="container">
<div id="content"></div>
</div>
For this, you can use stop propogation of js like this
<div id="container">
<div id="content" onclick="event.stopPropagation();">
</div>
</div>
So when you click on content it will not trigger container event only.

Can't preventDefault() on drop event on a div with Svelte

I'm trying to implement a file dropper on a <div> as a Svelte component. I've tried every combination of preventDefault but the browser still loads the dropped file instead of passing it to the component.
<script>
function handleDrop(event) {
event.preventDefault();
console.log("onDrop");
}
function handleDragover(event) {
console.log("dragOver");
}
</script>
<style>
.dropzone {
display: block;
width: 100vw;
height: 300px;
background-color: #555;
}
</style>
<div class="dropzone" on:drop|preventDefault={handleDrop}
on:dragover|once|preventDefault={handleDragover}></div>
I've tried with and without event.preventDefault(); in handler functions. Also tried with on:dragenter event and different combinations of modifiers, i.e. with stopPropagation. The browser still opens the dropped file. What am I doing wrong? Thanks!
(UPDATE) FIX:
Okay, the culprit was the |once modifier. Once removed from the on:dragover in <div> everything works great, except that dragover event fires continuously while dragging across the div. event.preventDefault(); inside handler functions is not needed as the |preventDefault modifier works correctly. Here is the code (omitting <style> for brevity):
<script>
function handleDrop(event) {
console.log("onDrop");
}
function handleDragover(event) {
console.log("onDragOver");
}
</script>
<div class="dropzone" on:drop|preventDefault={handleDrop}
on:dragover|preventDefault={handleDragover}></div>
Not submitting this as an answer yet, because I would like to find out why I can't use |once modifier for dragover event, which would be useful for my app. Thanks!
Problem:
This is a common gotcha rooted in HTML drag-and-drop (not Svelte's fault), where the last dragover event must be canceled in order to cancel drop. Looking at Svelte's once directive, it's just a closure that runs your handler one time. However, dragover will fire multiple times before being dropped, so the immediately preceding dragover is not prevented.
Solution:
Just include the directive without a handler:
<div
on:dragover|preventDefault
on:drop|preventDefault={handler}
>
<style>
.dropzone {
display: block;
width: 100vw;
height: 300px;
background-color: #555;
}
</style>
<div class="dropzone" on:drop={event => handleDrop(event)}
on:dragover={handleDragover}>
</div>
<script>
export function handleDragover (ev) {
ev.preventDefault();
console.log("dragOver");
}
export function handleDrop (ev) {
ev.preventDefault();
console.log("onDrop");
}
</script>
Look here: https://svelte.dev/repl/3721cbc9490a4c51b07068944a36a40d?version=3.4.2
https://v2.svelte.dev/repl?version=2.9.10&gist=8a9b145a738530b20d0c3ba138512289

How to make sure clickable objects don't propagate to the wrong element?

Languages involved: HTML, CSS, JS
Context: I'm relatively new to web development. I have two elements overlapping each other. One is a slider, one is a div. The slider is on top of the div.
Code snippets:
<div id="myDiv">
<input id="mySlider" type="range" min=1 max=100 step=1>
</div>
and
initListeners() {
document.getElementById("myDiv").addEventListener("click", divFunction);
document.getElementById("mySlider").addEventListener("input", sliderFunction);
}
I need to make it that when you click the slider, it doesn't click the div. How would I go about doing that? I've tried z-index, but that doesn't seem to change anything.
Thanks in advance!
As I'm sure you've figured out by now, events in JavaScript by default bubble up from a child to a parent. You need to stop that from happening at the child level, also known as preventing propagation.
Using the stopPropagation function, you can handle this as follows:
function sliderFunction(e) {
e.stopPropagation();
}
Simple. That event will no longer reach the parent.
EDIT
While stop propagation is the correct method to use, event listeners must also match in type. Therefore, both the slider and the parent DIV must have click event listeners (instead of input and click). stopPropagation stops propagation of a specific type of event.
function divFunction() {
console.log('DIV clicked!');
}
function sliderFunction(event) {
event.stopPropagation();
console.log('Slider clicked!');
}
function initListeners() {
document.getElementById('myDiv').addEventListener('click', divFunction);
document.getElementById('mySlider').addEventListener('click', sliderFunction);
}
initListeners();
/* unnecessary visual aides */
body *:not(label) {
padding: 2rem;
outline: 1px solid red;
position: relative;
}
label {
display: inline-block;
position: absolute;
background: #222;
color: #fff;
top: 0; left: 0;
}
<div id="myDiv">
<label>#myDiv</label>
<div id="tools">
<label>#tools</label>
<input type="range" id="mySlider">
</div>
</div>
You can also check the target once you fire that click event. I've used this approach before:
JSFiddle: http://jsfiddle.net/L4ck7ygo/1/
function divFunction(e) {
if (e.target !== this) {
return;
} else {
console.log('hit');
}
}
When the fiddle first loads, click the slider and you'll see the console log out some text. To see it work, remove the line that is being pointed to and rerun the fiddle. Now when you click the slider, you won't see anything logged in the console, but if you click on the div and not the slider, it will log to the console.
function initListeners() {
document.getElementById("myDiv").addEventListener("click", divFunction);
document.getElementById("mySlider").addEventListener("input", sliderFunction);
}
initListeners();
function divFunction(e) {
console.log('Firing...') // <-- This will log on any click
if (e.target !== this) {
return;
} else {
console.log('hit'); // <-- This will NOT log except for div click
}
}
function sliderFunction() {
console.log('Doing stuffs...');
}
<div id="myDiv">
<input id="mySlider" type="range" min=1 max=100 step=1>
</div>
UPDATE: Stupidity on my part. I had the ordering wrong for the elements which caused propagation to not act as intended.

Javascript pass onclick on child to parent

I have div (.upload-drop-zone, yellow zone at screenshot) with another div (.dropzone-width, blue zone) inside.
<div class="upload-drop-zone dz-clickable" id="drop-zone-600">
<div class="dropzone-width">600 PX</div>
</div>
There is a javascript onclick event attached to .upload-drop-zone (when I click on it, it shows file chooser dialog). Event attached by third-party plugin, so I have no access to function which be called.
The problem is that if I make click on .dropzone-width, click event did not pass to .upload-drop-zone so nothing happens instead of showing file chooser dialog. What can I do to fix it?
P.S.: Sorry for bad english.
Try this, I had a same issue before. No javscript required...
.dropzone-width { pointer-events: none; }
You can listen for a click in the inner div and fire the click on the outer div.
$("#drop-zone-600").click(function (e) {
alert("hey");
});
$("#dzw").click(function (e) {
$("#drop-zone-600").onclick();
});
.upload-drop-zone {
width: 200px;
height: 200px;
border: 1px solid red;
background: darkred;
}
.dropzone-width {
width: 100px;
height: 100px;
border: 1px solid green;
background: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upload-drop-zone dz-clickable" id="drop-zone-600">
<div id ="dzw" class="dropzone-width">600 PX</div>
</div>
Despite the fact that the alert function is inside the click event listener of the #drop-zone-600 div, you can see the alert by clicking any of the divs.
One possibility is to synthetically fire the click event. See How can I trigger a JavaScript event click
fireEvent( document.getElementById('drop-zone-600'), 'click' );
Try this via jquery:
$(".dropzone-width").on("click", function(){
$("#drop-zone-600").trigger("click");
});

Prevent custom event from executing

I want to prevent custom event on parent when child is clicked. Note that I don't have access to the code of parent event. I've tried doing e.preventDefault() on the button itself but it doesn't help.
Is there any way of ignoring all parent events when something inside of it is clicked?
$(function(){
// Note that this is just an example, I don't have access to this code
// This is some custom event inside custom plugin
$('.container').on('click', function() {
alert('This should be alerted only if you click on green box');
});
$('.btn').on('click', function() {
// Here I want to make sure that *parent* events are not triggered.
alert('Button is triggered, green box should be not triggered');
});
});
.container {
width: 300px;
height: 200px;
background: green;
padding-top: 100px;
}
.btn {
width: 100px;
height: 100px;
display: block;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="btn">Click Me</button>
</div>
Since you're using jQuery, you can use the event.stopPropagation() method. The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. You can see it in action here
$(document).ready(function () {
$("#button").click(function (event) {
alert("This is the button.");
// Comment the following to see the difference
event.stopPropagation();
});
$("#outerdiv").click(function (event) {
alert("This is the outer div.");
});
});
In this simple example, if you click on the button, the event is handled by its own handler and it won't bubble up the DOM hierarchy. You can add a very simple handler calling event.stopPropagation() on the button and it won't bubble up. No need to mess with the parent's JS.

Categories