Having:
<div id="outerDiv">
<div id="innerDiv" style="margin: 10px">Content goes here</div>
</div>
I want to identify those mouse events that happen outside innerDiv but inside outerDiv (said in a different way, those events over the innerDiv margin).
This is easy to achieve if I add outerDiv a padding or a border, but I would like to know if there is another way to do this without having to add extra pixels to outerDiv.
Thanks
Using jQuery I would do the following
$("#outerDiv").bind("event", function(e) {
if ($(e.target).closest("#innerDiv")) {
alert("from inner div");
}
else {
alert("from outer div only");
}
});
Explanation:
#outerDiv will get a bubbled event. If the event's target or target's ancestor is #innerDiv then we know it originated within the inner div. Otherwise it did not. Since it hit #outerDiv we know that it happened somewhere in #outerDiv but not in #innerDiv
This can be achieved by use of a flag:
<div id="outerDiv" style="border:thin solid red;">
<div id="innerDiv" style="border:thin solid blue; margin: 10px;">Content goes here</div>
</div>
<script language="javascript">
var flag = false;
document.getElementById("outerDiv").onclick = function(){
if (flag) {
flag = false;
return false;
}
alert("Clicked outerDiv");
}
document.getElementById("innerDiv").onclick = function(){
flag = true;
alert("Clicked innerDiv");
}
</script>
The essence is that the event for innerDiv will fire first. If so, prevent the event for outerDiv.
The technique works for onmousedown, onmouseup and onmousemove.
Related
By triggering an onClick event I would like to select the same element the onClick event is attached to, to add a class to that same element. What I tried is the following:
<div class="class1" onClick="TestFunction();">Click</div>
<script>
function TestFunction() {
$(this).addClass('active');
}
</script>
After clicking the div, the class "active" should be added to the same element, resulting in...
<div class="class1 active" onClick="TestFunction();">Click</div>
However this doesn't work. I am wondering whether the this selector works differently in this case.
The structure of the div element should stay the same and also the function should stay in the same place as it is on the onClick attribute.
The reason is this refers to the global Window object inside the function.
You have to pass this to the function so that you can refer that inside the function:
.active{
color:green;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1" onClick="TestFunction(this);">Click</div>
<script>
function TestFunction(el) {
console.log(this.constructor.name) //Window
$(el).addClass('active');
}
</script>
Though it is better to avoid inline event handler:
$('.class1').click(function(){
$(this).addClass('active');
});
.active{
color:green;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1">Click</div>
When using an inline handler the function invoked runs under the scope of the window element, not the element which raised the event. To work around that you can pass this as an argument:
<div class="class1" onClick="TestFunction(this);">Click</div>
function TestFunction(el) {
el.addClass('active');
}
However this is not good practice. Inline event attributes are outdated and now considered bad practice. The better way to achieve this is to attach unobtrusive event handlers. In plain JS it would look like this:
<div class="class1">Click</div>
document.querySelectorAll('.class1').forEach(el => {
el.addEventListener('click', function() {
this.classList.add('active');
});
});
In jQuery it would look like this:
<div class="class1">Click</div>
jQuery($ => {
$('.class1').on('click', function() {
$(this).addClass('active');
});
});
<body>
<div id="e1">Element X1</div>
<div id="e2">Element 2X</div>
<div id="e3">Element X3</div>
Hide
</body>
How can i hide the entire body And only show #e2 when i click on #hide, But if i clicked anywhere else out of #e2 again, the hide effect will stop and return to normal.
Something like this? NB: make sure to give your hide link a unique ID.
Showing/hiding works well with jQuery show and hide methods, but since you wanted the elements to stay in their place, it is more suitable to use the visibility style attribute:
$('#hide').click(function () {
// hide all in body except #e2, and #e2's parents.
$('body *').not($('#e2').parents().addBack()).css({visibility: 'hidden'});
return false; // cancel bubbling and default hyperlink effect.
});
$('#e2').click(function () { // click on #e2
return false; // cancel bubbling -- ignore click.
})
$(document).click(function (e) { // click on document
$('body *').css({visibility: 'visible'}); // show all in body.
});
div { border: 1px solid}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="e1">Element X1</div>
<div id="e2">Element 2X</div>
<div id="e3">Element X3</div>
Hide
Be aware that these div elements stretch across horizontally, so a click to the right of the text "Element 2X" will still be on #e2.
Something like this:
// Get reference to the hyperlink
var hideElem = document.getElementById("e4");
// Set up click event handler for link
hideElem.addEventListener("click", function(e){
var elems = document.querySelectorAll("body *:not(#e2)");
Array.prototype.slice.call(elems).forEach(function(value){
value.classList.add("hide");
});
e.stopPropagation();
});
// Set up click event handler for document
document.addEventListener("click", function(){
var elems = document.querySelectorAll("body *");
Array.prototype.slice.call(elems).forEach(function(value){
value.classList.remove("hide");
});
});
.hide { display:none; }
<div id="e1">Element X1</div>
<div id="e2">Element 2X</div>
<div id="e3">Element X3</div>
Hide
$('body').click(function(evt){
if(!$(evt.target).is('#e2')) {
//If not e2 is clicked then restore the state back of page by removing a specific class
}
});
You will need help of css class .hide {display:none;} and add and remove this class when e2 is clicked and remove this class when body is clicked but not e2 as provided above
I have a div that listens for mousedown event. The div has some child buttons (absolutely positioned outside the div). I want to be able to click these buttons. But when I press the mouse button, the parent div intercepts the mousedown event. I can test the .target member to ignore the event if it happened on the buttons, but it seems that I never get the click event on these buttons this way.
Is there a way to solve this without adding yet another ancestor div?
You can use event.target == this
Example :
<html>
<head>
<style>
div {
width: 100px;
background-color: yellow;
height: 100px;
}
</style>
</head>
<body>
<div id="d">I am div
<button id="btn1">Button1</button>
</div>
<script>
var divMousedown = document.getElementById("d");
var Child = document.getElementById("btn1");
divMousedown.onmousedown = function(event) {
if(event.target == this)
alert("You Mouse down on Div");
}
Child.onclick = function(event){
if(event.target == this)
alert("You Click on Button")
}
</script>
</body>
</html>
How do I listen a mouseover event from shadow DOM. I did try as snipcode below but nothing happen. The template instance is generated after button Add is clicked and I register mouseover event for it and hopping this event is fired when mouseover.
Thank a lot
HTML
<body>
<h1 class="text-center">Test import Node</h1>
<div class="container-fluid" style=" background-color: #FAFAFA"></div>
<div class="col-md-12" id = 'root'>
<button type="button" class="btn btn-default go" id='_add'><i class="fa fa-pencil-square-o"></i> Add</button>
<div id = 'textbox' style="height: 200px; width: 400px; font-size: 18px"></div>
</div>
<template id = 'area'>
<div style="height : 400px; width: 300px ; background-color: red"></div>
</template>
</body>
Javascript
$(document).ready(function() {
var button = document.querySelector('#_add');
button.addEventListener('click', function(){
check();
}, false);
});
function check(){
// document.querySelector('#textbox').innerHTML = "Ukie";
var content = document.querySelector('#area').content;
content.addEventListener('mouseover', function(){
display();
}, false);
var root = document.querySelector('#root');
root.appendChild(document.importNode(content, true));
}
function display(){
document.querySelector('#textbox').innerHTML = "Here";
}
As per addEventListener docs:
The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).
Therefore element must exist in the DOM, when you call addEventListener on it.
As a workaround, you can use event delegation using jquery on method to achieve the same. Here is a working jsfiddle by tweaking your sample a bit.
$('#root').on('mouseover', '.dyn', function(){
display();
});
Here bound element will be parent of template content(about which you are sure that it will exist while binding event) and you'll pass selector of your content html to .on method as argument. Thus whenever event occurs on child(in this case your template content) it will bubble up to parent and callback will be triggered.
You can use on function with jQuery. With on function you can "bind" events on element which not created in the DOM when the code was executed.
Read this: http://api.jquery.com/on/
It maybe easy but i can't think anything to find the way when i click outside the textbox to alert something in javascript BUT when i click inside the text nothing to happen.The input text is inside the div element.
So,let's assume that my html is like bellow:
<div id="myone" onclick="javascript: myfunc();">
<input type="text" id="myInput"></input>
</div>
function myfunc()
{
alert('ok');
}
How to change that?
Thank you a lot!
Do this:
var div = document.getElementById('myone');
var funct = function(){
var input = div.querySelector("#myInput");
return false;
};
div.onclick = funct;
You shoud use this condition. e.target !== this
It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.
Use it inside your click function like this and see it in action:
$('.divover').on('click', function(e) {
if (e.target !== this) return;
thefunc();
});
var thefunc = function myfunc() {
alert('ok');
}
.divover {
padding: 20px;
background: yellow;
}
span {
background: blue;
color: white;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='divover'>somelabel:
<span><input type="text" class="as" name="forename"></span>
</div>
This will work, if you do this carefully.
<div id="myone" onclick="javascript: myfunc();">
//your stuff in the clickable division.
</div>
<div style="position:absolute;">
<!--Adjust this division in such a way that, it comes inside your clickable division--><input
type="text" id="myInput"></input>
</div>
//Your script function/code here
function myfunc()
{
alert('ok');
}