I've got the following JavaScript code to track clicks on a div:
var anchor = document.getElementById('clickMe');
if (anchor.addEventListener) {
anchor.addEventListener('click', clickHandlerOpen, false);
} else if (anchor.attachEvent) {
anchor.attachEvent('onclick', function () {
return clickHandlerOpen.apply(anchor, [window.event])
});
}
My html looks like this:
<div id="clickMe">
<div id="someContent"><p>hello</p></div>
<div id="closeMe">X</div>
</div>
How can i exclude the id closeMe from the above click handler? I want the closeMe to have its own.
Please note that i do not want to use jQuery.
Check the target.id of the clicked element inside your function:
clickHandlerOpen(event) {
//Satisfy IE8
event = event || window.event; // get window.event if argument is falsy (in IE)
// get srcElement if target is falsy (IE)
var targetElement = event.target || event.srcElement;
if (targetElement.id == 'closeMe') return false;
//your code here
}
Related
I use a click listener like this so that a click that goes to link.php will execute some code:
document.addEventListener('click', function(e) {
var tre = e.target.href || '';
if( tre.indexOf("link.php") > -1) {
alert('it worked');
}
}, false);
This works:
<a href="/link.php?destination=1" target="_blank">
link text
</a>
But clicks on images or divs don't:
<a href="/link.php?destination=1" target="_blank">
<img src="/image.jpg">
<span>link text</span>
</a>
since clicks are on the image and span, not the <a> tag. What's the simplest way to make this work?
JavaScript does have a native .closest() method (although it is currently considered experimental and has limited browser support). You can use this method in order to get the closest a ancestor element (or the element itself, which means that it would work in both of the cases that you provided).
Example Here
document.addEventListener('click', function(e) {
var href = e.target.closest('a').href || '';
if (href.indexOf("link.php") > -1) {
// ...
}
}, false);
Alternatively, you could check if each parent node is an a element:
Example Here
document.addEventListener('click', function(e) {
var target = e.target
while (target && target.tagName !== 'A') {
target = target.parentNode;
if (!target) { return; }
}
if (target.href.indexOf("link.php") > -1) {
// ...
}
}, false);
Another option is to attach the event listener directly to the a element and then access the currentTarget property in order to get the element that the event was attached to (rather than the element that triggered the event). However, that would only attach the event to a single a element:
Example Here
document.querySelector('a').addEventListener('click', function(e) {
var href = e.currentTarget.href || '';
if (href.indexOf("link.php") > -1) {
// ...
}
}, false);
So this is just a small personal project that I'm working on using awesomium in .net. So in awesomium I have this browser open and all that and I want to click this button that has this code.
<a class="buttonright" > Bump </a>
But considering it's a class and not a button I'm having trouble finding a way to "click" it. My plan is to use javascript in awesomium to click it but maybe I'm approaching this from the wrong direction?
Thanks
Update:
After a lot of comments (back and forth) I set up a fiddle, with a working version of this code (the code here works, too, but needed some debugging). The eventTrigger function in the fiddle has been stripped of all comments, but I've added an example usage of this function, which is generously sprinkled with comments.
Browse through it, fork it, play around and get familiar with the code and concepts used there. Have fun:
Here's the fiddle
If by "finding a way to click it" you mean: how to programmatically click this anchor element, then this is what you can use:
Here's a X-browser, slightly verbose yet comprehensive approach:
var eventTrigger = function(node, event)
{
var e, eClass,
doc = node.ownerDocument || (node.nodeType === (document.DOCUMENT_NODE || 9) ? node : document);
//after checking John Resig's Pro JavaScript Techniques
//the statement above is best written with an explicit 9
//Given the fact that IE doesn't do document.<NODE_CONSTANT>:
//doc = node.ownerDocument || (node.nodeType === 9 ? node : document);
if (node.dispatchEvent)
{//dispatchEvent method is present, we have an OK browser
if (event === 'click' || event.indexOf('mouse') >= 0)
eClass = 'MouseEvents';//clik, mouseup & mousedown are MouseEvents
else
eClass = 'HTMLEvents';//change, focus, blur... => HTMLEvents
//now create an event object of the corresponding class
e = doc.createEvent(eClass);
//initialize it, if it's a change event, don't let it bubble
//change events don't bubble in IE<9, but most browsers do
//e.initEvent(event, true, true); would be valid, though not standard
e.initEvent(event, !(event === 'change'), true);
//optional, non-standard -> a flag for internal use in your code
e.synthetic = true;//mark event as synthetic
//dispatch event to given node
node.dispatchEvent(e, true);
//return here, to avoid else branch
return true;
}
if (node.fireEvent)
{//old IE's use fireEvent method, its API is simpler, and less powerful
//a standard event, IE events do not contain event-specific details
e = doc.createEventObject();
//same as before: optional, non-standard (but then IE never was :-P)
e.synthetic = true;
//~same as dispatchEvent, but event name preceded by "on"
node.fireEvent('on' + event, e);
return true;//end IE
}
//last-resort fallback -> trigger any directly bound handler manually
//alternatively throw Error!
event = 'on' + event;
//use bracket notation, to use event's value, and invoke
return node[event]();//invoke "onclick"
};
In your case, you can use this function by querying the DOM for that particular element, like so:
var elem = document.querySelector('.buttonright');//IE8 and up, will only select 1 element
//document.querySelectorAll('.buttonright'); returns a nodelist (array-like object) with all elements that have this class
eventTrigger(elem, 'click');
That should have the effect of clicking the anchor element
If you're looking for a way to handle click events on this element (an anchor that has a buttonright class), then a simple event listener is all you need:
document.body.addEventListener('click', function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'a' && target.className.match(/\bbuttonright\b/))
{//clicked element was a link, with the buttonright class
alert('You clicked a button/link thingy');
}
}, false);
That's the cleanest way to do things (one event listener handles all click events). Of course, you can bind the handler to specific elements, too:
var buttons = document.querySelectorAll('.buttonright'),
handler = function(e)
{
alert('Clicked!');
};
for (var i=0;i<buttons.length;++i)
{
buttons[i].addEventListener('click',handler, false);
}
Depending on how you want to handle the event, there are numerous roads you can take.
The simplest one is this :
<script type="text/javascript">
function buttonRight_onclick(event, sender)
{
alert("HEY YOU CLICKED ME!");
}
</script>
<a class="buttonright" click="buttonRight_onclick(event, this)">
whereas if you were using a framework like jQuery, you could do it like this:
<script type="text/javascript">
$(document).ready(function() {
$(".buttonright").on("click", function(event) {
alert("HEY YOU CLICKED ME!");
});
});
</script>
<a class="buttonright" >Bump</a>
<a class="buttonright" >Also bump</a>
<script type="text/javascript">
function Button_onclick(event, sender)
{
alert("Button Clicked!");
}
</script>
<a class="Button" click="Button_onclick(event, this)">
I have searched for a good solution everywhere, yet I can't find one which does not use jQuery.
Is there a cross-browser, normal way (without weird hacks or easy to break code), to detect a click outside of an element (which may or may not have children)?
Add an event listener to document and use Node.contains() to find whether the target of the event (which is the inner-most clicked element) is inside your specified element. It works even in IE5
const specifiedElement = document.getElementById('a')
// I'm using "click" but it works with any event
document.addEventListener('click', event => {
const isClickInside = specifiedElement.contains(event.target)
if (!isClickInside) {
// The click was OUTSIDE the specifiedElement, do something
}
})
var specifiedElement = document.getElementById('a');
//I'm using "click" but it works with any event
document.addEventListener('click', function(event) {
var isClickInside = specifiedElement.contains(event.target);
if (isClickInside) {
alert('You clicked inside A')
} else {
alert('You clicked outside A')
}
});
div {
margin: auto;
padding: 1em;
max-width: 6em;
background: rgba(0, 0, 0, .2);
text-align: center;
}
Is the click inside A or outside?
<div id="a">A
<div id="b">B
<div id="c">C</div>
</div>
</div>
You need to handle the click event on document level. In the event object, you have a target property, the inner-most DOM element that was clicked. With this you check itself and walk up its parents until the document element, if one of them is your watched element.
See the example on jsFiddle
document.addEventListener("click", function (e) {
var level = 0;
for (var element = e.target; element; element = element.parentNode) {
if (element.id === 'x') {
document.getElementById("out").innerHTML = (level ? "inner " : "") + "x clicked";
return;
}
level++;
}
document.getElementById("out").innerHTML = "not x clicked";
});
As always, this isn't cross-bad-browser compatible because of addEventListener/attachEvent, but it works like this.
A child is clicked, when not event.target, but one of it's parents is the watched element (i'm simply counting level for this). You may also have a boolean var, if the element is found or not, to not return the handler from inside the for clause. My example is limiting to that the handler only finishes, when nothing matches.
Adding cross-browser compatability, I'm usually doing it like this:
var addEvent = function (element, eventName, fn, useCapture) {
if (element.addEventListener) {
element.addEventListener(eventName, fn, useCapture);
}
else if (element.attachEvent) {
element.attachEvent(eventName, function (e) {
fn.apply(element, arguments);
}, useCapture);
}
};
This is cross-browser compatible code for attaching an event listener/handler, inclusive rewriting this in IE, to be the element, as like jQuery does for its event handlers. There are plenty of arguments to have some bits of jQuery in mind ;)
How about this:
jsBin demo
document.onclick = function(event){
var hasParent = false;
for(var node = event.target; node != document.body; node = node.parentNode)
{
if(node.id == 'div1'){
hasParent = true;
break;
}
}
if(hasParent)
alert('inside');
else
alert('outside');
}
you can use composePath() to check if the click happened outside or inside of a target div that may or may not have children:
const targetDiv = document.querySelector('#targetDiv')
document.addEventListener('click', (e) => {
const isClickedInsideDiv = e.composedPath().includes(targetDiv)
if (isClickedInsideDiv) {
console.log('clicked inside of div')
} else {
console.log('clicked outside of div')
}
})
I did a lot of research on it to find a better method. JavaScript method .contains go recursively in DOM to check whether it contains target or not. I used it in one of react project but when react DOM changes on set state, .contains method does not work. SO i came up with this solution
//Basic Html snippet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="mydiv">
<h2>
click outside this div to test
</h2>
Check click outside
</div>
</body>
</html>
//Implementation in Vanilla javaScript
const node = document.getElementById('mydiv')
//minor css to make div more obvious
node.style.width = '300px'
node.style.height = '100px'
node.style.background = 'red'
let isCursorInside = false
//Attach mouseover event listener and update in variable
node.addEventListener('mouseover', function() {
isCursorInside = true
console.log('cursor inside')
})
/Attach mouseout event listener and update in variable
node.addEventListener('mouseout', function() {
isCursorInside = false
console.log('cursor outside')
})
document.addEventListener('click', function() {
//And if isCursorInside = false it means cursor is outside
if(!isCursorInside) {
alert('Outside div click detected')
}
})
WORKING DEMO jsfiddle
using the js Element.closest() method:
let popup = document.querySelector('.parent-element')
popup.addEventListener('click', (e) => {
if (!e.target.closest('.child-element')) {
// clicked outside
}
});
To hide element by click outside of it I usually apply such simple code:
var bodyTag = document.getElementsByTagName('body');
var element = document.getElementById('element');
function clickedOrNot(e) {
if (e.target !== element) {
// action in the case of click outside
bodyTag[0].removeEventListener('click', clickedOrNot, true);
}
}
bodyTag[0].addEventListener('click', clickedOrNot, true);
Another very simple and quick approach to this problem is to map the array of path into the event object returned by the listener. If the id or class name of your element matches one of those in the array, the click is inside your element.
(This solution can be useful if you don't want to get the element directly (e.g: document.getElementById('...'), for example in a reactjs/nextjs app, in ssr..).
Here is an example:
document.addEventListener('click', e => {
let clickedOutside = true;
e.path.forEach(item => {
if (!clickedOutside)
return;
if (item.className === 'your-element-class')
clickedOutside = false;
});
if (clickedOutside)
// Make an action if it's clicked outside..
});
I hope this answer will help you !
(Let me know if my solution is not a good solution or if you see something to improve.)
I have a container on a page that should be prepared for focusing, i.e. when user pressed TAB button, the first active element in the container must be focused.
The simplest way I have thought so far is to find the last active element before the container, focus it and then blur it. Will it work? Is there a simpler way? How to find the last active element before the container (cross-browser)?
I do not want to change tabbed elements order, I just want to define the next element that will be selected.
Please use raw javascript, not frameworks.
The only thing I can think of is looping over the container child nodes and try focusing them until you succeed:
<script type="text/javascript">
document.onkeyup = function (e) {
if (!e)
e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
FocusFirst(document.getElementById("MyContainer"));
}
}
function FocusFirst(element) {
try {
element.focus();
}
catch(ex) {}
if (document.activeElement == element)
return true;
for (var i = 0; i < element.childNodes.length; i++) {
var oChild = element.childNodes[i];
if (FocusFirst(oChild))
return true;
}
return false;
}
</script>
Sample HTML tested with: (IE, Chrome)
<div id="MyContainer">
<div>hello</div>
<div><span><input type="text" /></span></div>
<div><input type="text" /></div>
</div>
This will focus the first input box of the container upon tab click.
Add a listener to the document and change focus onKeyUp. Remove the listener once tab has been pressed:
document.onkeyup = onKeyEvent;
function onKeyEvent (e) {
if (e.keyCode == 9) {
document.onkeyup = null;
document.getElementById ('whatever').focus();
}
}
Here is the solution that I've used finally.
I just create fake empty link in the beginnig of the container and focus it. The link will be removed when it lose focus.
function prefocusElement(node)
{
var fake = document.createElement("a");
fake.setAttribute("href", "#");
node.insertBefore(fake, node.firstChild);
fake.focus();
fake.addEventListener("blur", function(e) { node.removeChild(fake); }, false);
};
I have code like:
document.onmousedown = function(){
alert('test');
}
Now, except the element with ID "box", clicking should call this function, i.e. the equivalent of jQuery's .not() selector.
The jQuery code would be:
$(document).not('#box').mousedown(function(){
alert('test');
});
How can I achieve the same thing without using jQuery?
Edit: I don't want jQuery code, but i want an action similar to the .not() selector of jQuery in Javascript.
Edit: I am making an addthis-like widget. It is a 10kb file which will show a popup when a text is selected. It will not use jQuery.
In my case, when a text is selected, a popup is shown. When the document is clicked somewhere other than the widget, the widget should disappear.
To do this properly, you need to check whether e.target || e.srcElement or any of its parents has id === 'box'.
For example: (with jQuery)
$(document).mousedown(function(e) {
if ($(e.target).closest('#box').length)
return;
//Do things
});
Without jQuery:
function isBox(elem) {
return elem != null && (elem.id === 'box' || isBox(elem.parentNode));
}
document.onmousedown = function(e) {
e = e || window.event;
if (isBox(e.target || e.srcElement))
return;
//Do things
};
Alternatively, you could handle the mousedown event for the box element and cancel bubbling.
Here's one way that should work:
document.onmousedown = function(e){
var event = e || window.event;
var element = event.target || event.srcElement;
if (target.id !== "box") { alert("hi"); }
}
or if you would like it to be reusable with different ids:
function myNot(id, callback) {
return function (e) {
var event = e || window.event;
var element = event.target || event.srcElement;
if (target.id !== id) { callback(); }
}
}
and to use it:
document.onmousedown = myNot("box", function () {
alert("hi");
});
The cleanest way I can come up with for what you're trying to do is to set a document.onmousedown event and then halt event propagation on the box.onmousedown event. This avoids creating a large number of onmousedown events all over the document, and avoids having to recurse through the entire parent hierarchy of a node every time an event is triggered.
document.onmousedown = function() {
alert("Foo!");
};
document.getElementById("box").onmousedown = function(e) {
alert("Bar!");
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
};