I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:
$(document).click(function () {
alert($(this).text());
});
But very strangely, I get the text of the whole(!) document, not the clicked element.
How to get only the element I clicked on?
Example
<body>
<div class="myclass">test</div>
<p>asdfasfasf</p>
</body>
If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass") in jQuery.
You need to use the event.target which is the element which originally triggered the event. The this in your example code refers to document.
In jQuery, that's...
$(document).click(function(event) {
var text = $(event.target).text();
});
Without jQuery...
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
}, false);
Also, ensure if you need to support < IE9 that you use attachEvent() instead of addEventListener().
event.target to get the element
window.onclick = e => {
console.log(e.target); // to get the element
console.log(e.target.tagName); // to get the element tag name alone
}
to get the text from clicked element
window.onclick = e => {
console.log(e.target.innerText);
}
use the following inside the body tag
<body onclick="theFunction(event)">
then use in javascript the following function to get the ID
<script>
function theFunction(e)
{ alert(e.target.id);}
You can find the target element in event.target:
$(document).click(function(event) {
console.log($(event.target).text());
});
References:
http://api.jquery.com/event.target/
Use delegate and event.target. delegate takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target is the jQ-normalized property of the event object representing the object from which the event originated.
$(document).delegate('*', 'click', function (event) {
// event.target is the element
// $(event.target).text() gets its text
});
Demo: http://jsfiddle.net/xXTbP/
I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:
window.onclick = e => {
console.log(e.target);
console.log(e.target.id, ' -->', e.target.innerHTML);
}
This is the esiest way to get clicked element in javascript.
window.addEventListener('click', (e) => console.log(e.target));
$(document).click(function (e) {
alert($(e.target).text());
});
pass "this" as argument when you call the function:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<span onclick="click_here(this);">clicked</span>
<script>
function click_here(elmnt){
alert($(elmnt).text());
}
</script>
Here's a solution that uses a jQuery selector so you can easily target tags of any class, ID, type etc.
jQuery('div').on('click', function(){
var node = jQuery(this).get(0);
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
});
Related
I'm trying to clone an element that is passed into a function and all events associated to it, as there are $('.example').on('click', function(e) ... )} events like this defined in document ready.
So I do following:
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
and I try to clone this element along side its events here (I need to grab parent as .html() returns only inner html, hence element itself) :
function surpriseMe(element) {
var newElement = element.parent().clone(true,true).html();
surprise.insertBefore(element.parent());
if (numElements == 3) {
newMonth = $('<li class="item-dragable-placeholder">'+ newElement +'</li>
}
}
I believe true, true inside .clone() should force parent also grab its children events, but whenever I click on newly placed element, nothing happens
To use event delegation...
Change:
$('.example').on('click', function(e) { ...
To:
$(document).on('click', '.example', function(e) { ...
Note: Instead of using document, find the closest ancestor element (container) that's available on page load and use that.
when you do your insert, instead of inserting the new element, you ask to insert only the html, remove the html part, it will give you the element and its functionalities.
var newElement = element.parent().clone(true,true).html();
See the following (example)[http://jsfiddle.net/dshun/1j9khfnc/4/](please note, since the example code given is not complete. For example, the variable surprise, numElements are not declared. I made some assumptions in my fiddle)
$(document).ready(function(){
var numElements=0;
function surpriseMe(element) {
var newElement = element.parent().clone(true,true);
newElement.insertBefore( ".inner" );
numElements++;
if (numElements == 3) {
newMonth = $('li.item-dragable-placeholder').insert(newElement);
}
}
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
});
How to get the ID of an element passed as (e)?
window.addEventListener('load', function(){
var tags = document.getElementsByClassName("tag");
for (i=0; i<tags.length; i++){
tags[i].addEventListener('mousedown', function(e){ tagClick(e) }, false);
}
}, false);
function tagClick(e){
/* here I'm gonna need the event to cancel the bubble and the ID to work with it*/
alert('The id of the element you clicked: ' + [?object].id);
[?object].className='newClass';
e.stopPropagation();
e.cancelBubble = true;
}
I need to get the element/object inside tagClick so I can change its properties
html:
<div class="tag">
<img src="/images/tags/sample.jpg"/>
<label class="tagLabel">Sample</label>
</div>
See, the element with the event attached is the div, but ig gives me the image object instead when using e.srcElement.
When you bind an event listener with addEventListener, it's called with this referring to the element you bound the event on. So this.id will be the id of the element (if it has one).
alert('The id of the element you clicked: ' + this.id);
But you're breaking that with this line:
tags[i].addEventListener('mousedown', function(e){ tagClick(e) }, false);
...because you're putting an extra function in the middle, then calling tagClick without setting this. There's no need for that extra function, change that to:
tags[i].addEventListener('mousedown', tagClick, false);
...so this doesn't get messed up. Or alternately if you prefer to have the extra function, ensure this is maintained using Function#call:
tags[i].addEventListener('mousedown', function(e){ tagClick.call(this, e) }, false);
...but there's no reason to do that with the tagClick function shown.
The (standard) event object also has the properties target (which may not be the element you bound the event on, it may well be a descendant) and currentTarget (which will be the element you bound the event on). But this is convenient and reliable if you use addEventListener (or even attachEvent, on IE).
You can get the target of the event with e.target.
However keep in mind that some browsers consider text nodes to be a target, so try something like this:
var t = e.target;
while(t && !t.id) t = t.parentNode;
if( t) {
alert("You clicked element #"+t.id);
}
This will find the first element that actually has an ID.
Happy New Year!
EDIT: On second thought, if it's the "tag" element itself you want to refer to, just use this. In an event handler, this refers to the element that actually has the handler. Although in this case you'll need to change your handler to ('mousedown', tagClick, false)
Or better still:
document.body.addEventListener("mousedown",function(e) {
var t = e.target;
while(t && t.nodeName != "TAG") { // note, must be uppercase
t = t.parentNode;
}
if( t) {
alert("You clicked on #"+t.id);
}
},false);
Fewer event handlers is always better.
document.getElementById("body").addEventListener("mousedown", function(e){
console.log(e.target.id);
});
enjoy.
I have this situation. I have a JavaScript function that does some work on document click:
$(document).click(function () {
//---Some work is done---
});
But I also want to check which document element is clicked? So, how can I get the clicked element id anywhere in the whole document?
The element from which the event was originated can be referred using the event's target property
$(document).click(function (e) {
var id = e.target.id
});
Note: this will work only if all elements in your page has an id attribute.
Another approach could be to find the closest element with has an id like
$(document).click(function (e) {
var id = $(e.target).closest('[id]').attr('id');
});
try this
$(document).click(function (e) {
//---Some work is done---
var id = e.target.id;
});
DEMO
I need to get the ID of an element that was clicked, but I need to to keep all my js and html separate. normally id just use 'this.id' in the html. Any other ways?
This is what e.target is for. You can add an event listener anywhere you want, as long as the click event is allowed to bubble up to it (which happens by default) you can catch it. A basic example:
document.addEventListener('click', function(e) {
alert(e.target.id);
});
Clicking on each will alert its id. Hope this helps :)
<button id="foo">foo</button>
<button id="bar">bar</button>
<button id="baz">baz</button>
EDIT
http://jsfiddle.net/95NZ8/
Try something like this:
$(document).ready(function () {
$("#someWrapper").each(function () {
$(this).on('click', function () {
alert(this.id);
});
});
});
window.onclick = e => {
console.log(e.target.id);
}
to get element, tagname, classname , other attributes
window.onclick = e => {
console.log(e.target);
console.log(e.target.tagName);
console.log(e.target.className);
console.log(e.target.id);
}
I'm creating html on runtime like this:
var myVar = "<div id='abc'>some clickable text</div>"
Now, I want to attach some event, say onclick, to this div. How can I do that on next line? I'll add this to DOM later.
PS: I've to accomplish this without using JQuery.
Instead of building your div as a string, you'll want to use document.createElement('div'). This way you will have a real dom object, and can get and set it's propeties, including onClick
Will this help? Since you dynamically generate it, you know the control id of the DIV.
document.getElementbyId('abc').onClick = foo;
function foo()
{
alert("All your impl to go here");
}
Try building the div as a DOM element first.
var myVar = document.createElement("div"),
parentDiv = document.getElementById("parent_div");
parentDiv.appendChild(myVar);
myVar.innerHTML = "some clickable text";
if(myVar.addEventListener){
myVar.addEventListener("click", clickFn, false);
}
else if(myVar.attachEvent){
myVar.attachEvent("onclick", clickFn);
}
else{
myVar.onclick = clickFn;
}
The addEventListener method is standard, but not every browser plays nice with the standard.
EDIT: As mentioned, an element must be added to the DOM first.
Or you can use this technique: attach event to the document.body. Then if the event target is not the needed div than just do nothing. It is the same techinque jquery uses for its live function:
// crossbrowser event attachment function
function listen(evnt, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(evnt, func, false);
}
else if (elem.attachEvent) {
var r = elem.attachEvent("on" + evnt, func);
return r;
}
else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}
// this is an analog of the jquery.live
var assignLiveEvent = function(id, evnt, callback) {
var handler = function(e) {
e = e || window.event;
e.target = e.target || e.srcElement;
if (e.target.id == id) {
//your code here
callback(e);
}
};
listen(evnt, document.body, handler);
};
var myVar = "<div id='abc'>some clickable text</div>";
assignLiveEvent("abc", "click", function(e) {
//your code here
});
// now you can add your div to DOM even after event handler assignation
Here is demo.
Brian Glaz is totally right but, if for some reason, you really need to do it this way, you have two options:
you can only add events to something that is already in the DOM, using pure javascript, so you would have to include it in the html like:
document.body.innerHTML += myVar;
and then, attach the event with
document.getElementById('abc').addEventListener('click', function(e){
//your code
}, 1);
With jQuery, you could use .live() to attach events to elements that are not yet present in the DOM:
$('#abc').live('click', function(e){
//your code here
});
so you could add the div later...