How to get DOM or jQuery element by mouse click?
For example I have the next code:
$("*").mouseup(
function()
{
var clickedElement = ???????????????
}
);
So, how to init 'clickedElement' variable?
Thank you.
Inside an event handler, this refers to the DOM element the event was raised on.
$("*").mouseup(function() {
var clickedElement = this;
});
To get a jQuery element, just pass this to jQuery.
But: It would be much much much better to use event delegation, instead of binding an event handler to every element. You can get the origin of the event with event.target:
$(document).mouseup(function(event) {
var clickedElement = event.target;
});
And a further note: This will not necessarily give you the clicked element, but the element over which the mouse button was released, which can be different from the element the button was pressed. You might want to bind to the click event.
I also suggest to read a jQuery tutorial where these basics are covered.
If you don't want to attach an event to every DOM element (which I wouldn't recommend)...
$(document).mouseup(function(event) {
var clickedElement = event.target;
});
jsFiddle.
Here, any element's event will bubble up all the way to document, where it will be handled, and the originating element that started the event will be in event.target.
Use this. i.e.:
$("*").mouseup( function() {
var clickedElement = this; //HTML DOM Element
var $clickedElement = $(this); //jQuery Wrapped HTML DOM Element
} );
Related
I have a link that will load via ajax some content.
My problem is, I don't want to remove the text "Load comments", I just want to not allow more clicks in this class.
Load comments
Jquery
var Progressajax = false;
$(function() {
$(".showcomments").click(function(){
if(Progressajax) return;
Progressajax = true;
var element = $(this);
var id = element.attr("id");
Progressajax = false;
alert("ok");
$(data).hide().prependTo('.varload'+id).fadeIn(1000);
//$(element).remove();
$(element).removeAttr("href");
$(element).removeClass('showcomments');
});
});
I just want to see OK the first time. How can I remove this class?
$(element).removeClass('showcomments');
This is not working...
http://jsfiddle.net/qsn1tuk1/
Use jQuery's one() function
$(".showcomments").one("click", function() {
http://www.w3schools.com/jquery/event_one.asp
The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs.
When using the one() method, the event handler function is only run ONCE for each element.
When you bind an event handler, you bind to the element, not to the class. Removing a class from an element doesn't change which event handlers are bound to the element.
You could use off() to remove the event handler:
$(this).off('click');
http://jsfiddle.net/om6ggvyu/
I have a problem. I've a function dropcopy() that calls on a div for drag&drop.
function dropcopy(ev) {
ev.preventDefault();
elencoOggetti = new Array();
var copyimg = document.getElementById(data).cloneNode(true);
//copyimg.id = data;
ev.target.appendChild(copyimg);
}
This function copy the object but not work the listener on clone. The listener is this
$("#filtro").click(function() {
alert('ciao');
});
Why isn't it working? Please help me.
First of all, you shouldn't clone an element without changing its id. IDs must be unique.
Event listeners are binded to the first element when created. Clones doesn't have the listeners binded. You can bind it again, or bind the listeners to a parent object instead of the objects themselves. You can do that like this:
$('body').on('click', '#filtro', function(){
alert('ciao');
});
This means the listener is attached to the body instead of the element itself, and it'll be fired only if the event was fired by #filtro.
I belive that you are binding the element, when it is not existing, so add the guard:
$(document).ready(function(){
$("#filtro").click(function(){
alert('ciao');
});
}
If you wanna bind it after cloning, you can rerun this function above:
function resetUI(){
$("#filtro").click(function(){
alert('ciao');
});
}
Or overwrite the DOM, look on the docs of jquery if you wanna bind that to every name on update.
I have two elements, like this:
var parent = document.getElementById("el");
var child = parent.children[0];
and then a eventListener:
parent.addEventListener("click", function() {
alert("Hello World!")
});
and the problem is that when you click the child, the parents click event will be fired.
I want only when you click on the parent to fire the alert, not when you click on the child.
I am not using JQuery and won't.
I have searched on google, and all results uses e.stopPropogation which is JQuery.
So what's the best way to do this in plain JS?
Thanks alot.
You need to prevent event bubbling up to the parent element. For this you have to bind one more event handler to the child element:
child.addEventListener("click", function(e) {
e.stopPropagation();
});
Click event bubbles which means that event travels up DOM tree from child to parent unless its propagation is stopped.
You can check the ID of the clicked element and use that to control the trigger:
http://jsfiddle.net/nccjgtp6/
<div id="el">
This is a thing.
<div id="el2"> This is a second thing. </div>
</div>
var parent = document.getElementById("el");
var child = parent.children[0];
parent.addEventListener("click", function(e) {
console.log(e);
if(e.srcElement.id == 'el') {
alert('Hello world');
}
});
I do not know if this will work consistently in all browsers, but works for me in Chrome.
If I'm not mistaken, it's the event.stopPropagation(); line of code you need.
My case
$(".myElementWithSpecialActionHandler").click(function(){});
after the element was relocated, say insert to a different position of the page,
var content_from_table = from_table_obj.html();
var content_target_table = to_table_obj.html();
before the ajax call. And I put
from_table_obj.html(content_target_table);
to_table_obj.html(content_from_table);" in the ajax response handler.
after that the event handler function stops working. So I have to do
// after DOM manipulation
// again >.<
$(".myElementWithSpecialActionHandler").click(function(){});
Is event delegation the only to solve this? Or are there better way to avoid the scenario at the first place?
EDIT : added "relocate" code
What you're doing is deleting the element and creating it again (Don't know why). So it no longer is the same element and your event handler won't work.
In this case, yes, you should use event delegation:
$(document).on('click', ".myElementWithSpecialActionHandler", function(){});
EDIT:
You can use .appendTo() to add it to another place (maybe a hidden div or something). Or you could just appendTo() it to its destination but hide it until you ajax callback fires. I created a little jsfiddle to show you that appendTo() does not remove the event handler: jsfiddle
var divId = '#div2';
$('button').on('click', function() {
$(this).appendTo(divId);
divId = divId == '#div2' ? '#div1' : '#div2';
});
Hope this helps you.
I am using xui js for a mobile web app. Xui js doesn't support the live event like jquery $("#selector").live(). I would like to write some thing at approximates the jquery live.
How does jquery handle event delegation?
Thank you for your time
Mac
To expand on Gaby's answer...
I needed to also look to see if the immediate child was clicked. This can be expanded further to have more of a true delegate like we have in jQuery. However, this code sufficed for my needs.
xui.extend({
is: function (selector) {
var matchedNodes = x$(selector), i=0;
for (i; i<matchedNodes.length; i++)
if (this[0] == matchedNodes[i]) return true;
return false;
},
delegate: function(selector, event, handler){
this.on(event, function(evt){
var elem = evt.target;
if ( x$(elem).is(selector) ){
handler.apply(x$(elem), arguments);
} else{
if ( x$(elem.parentElement).is(selector) ){
handler.apply(x$(elem.parentElement), arguments);
}
}
});
}
});
You can just set the event handling on the document (as live does), or even better find a parent of the elements you want to handle and bind to that (as the delegate does).
Here is a plugin to simulate the delegate function of jquery.
xui.extend({
is: function (selector) {
var matchedNodes = x$(selector), i=0;
for (i; i<matchedNodes.length; i++)
if (this[0] == matchedNodes[i]) return true;
return false;
},
delegate: function(selector, event, handler){
this.on(event, function(evt){
var elem = evt.target;
if ( x$(elem).is(selector) ){
handler.apply(x$(elem), arguments);
}
});
}
});
Usage
x$('ul').delegate('li','click', function(){ this.attr('style','color:red'); });
This will bind an listener to the ul elements, that will handle click events initiated by their descendant li elements. (it will change the clicked elements color to red)
Demo at http://jsfiddle.net/gaby/vhsPU/
As every event delegation system, it makes usage of the fact that browser events do bubble "bottom up". That means, if we have a structure like
<body>
<div>
<span>foobar 1</span>
<span>foobar 2</span>
<span>foobar 3</span>
</div>
</body>
and somebody clicks on the inner foobar span, the browser checks if any event handlers are bound to the span for that click event. If so, execute them. Now the event "bubbles up" to its parent (div). Again, the browser checks if any click event handlers are bound to it, if so execute, and so forth up until the document.documentElement.
In the above example, we would need to bind three event handlers for every <span> element. Knowing the above described concept, we now can just bind one event handler to the <div> parent node and check for the target within the event object. That target is always the original element where the event happened.
There are a couple more things to know. You can stop the propagation of events for instance to explicitly not allow an event to bubble up any further. That can be done by invoking .stopPropagation() which is a method from the event object.