Get element id using element class - javascript

I'd like to get the id of the pressed element.
I know it's a very common question but I do not want a solution in jquery (I'm trying to use it as few as possible)
I cannot modify the html, supposing is something like:
<p id='123' class='my_class'>x</p>
I cannot create something like:
<p id='123' class='my_class' onclick='console.log(this.id + " pressed");'>x</p>
This is my personal attempt:
$(document).on('click', '.my_class', this.id, function (id) {
console.log( id + " pressed!");
});
But I keep obtaining this:
[object Object] pressed!

var elems = document.getElementsByClassName("my_class");
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener('click', function() {
console.log(this.id + " pressed");
});
}
Here is solution without jquery.

You are almost right. Use the below code:
$(document).on('click', '.my_class', function () {
console.log( this.id + " pressed!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='123' class='my_class'>x</p>
Explanation
You should not be sending the third argument with this as it is not contextual. The syntax of the .on is:
.on( events [, selector ] [, data ], handler )
You can completely ignore the third option and that doesn't matter. Always, inside the function, the this will point to the current element, the event is triggered on.
And in your code, you are passing id as the parameter to the call back function, which is the event (EventObject). That's why you got [Object object].
Hope it makes sense.

id in the arguments points to the event object, make it
$(document).on('click', '.my_class', this.id, function (id) {
console.log( id.target.id + " pressed!");
});
or
$(document).on('click', '.my_class', this.id, function (e) {
console.log( e.target.id + " pressed!");
});

Related

jquery ignoring first click

I have this function:
NewShowHideDiv2(iconID, divID, disabled) {
var x = document.getElementById(divID);
var y = document.getElementById(iconID);
$(eval(y)).click(function() {
console.log(eval(y));
$(eval(y)).toggleClass( "clicked" );
});
$(eval(x)).slideToggle("slow", function() {
});
}
All i am trying to get it to do is toggle the "clicked" class on click. However, it ignores the first and second click, and then applies it on the third and all subsequent odd number clicks. any ideas?
Without knowing how NewShowHideDiv2 is called it's difficult to be certain but there are some likely issues.
First, by putting your click binding function inside another function, the event isn't bound to the element until NewShowHideDiv2 is run. So you'll want to pull that out and put it in something like this:
$( document ).ready(function() {
$(eval(y)).click(function() {
console.log(eval(y));
$(eval(y)).toggleClass( "clicked" );
});
});
Also, the eval approach on the JS object is likely causing issues and certainly isn't the best practice. You'll want to modify that to be:
$( document ).ready(function() {
$("#iconIDHere").click(function() {
console.log(this);
$(this).toggleClass( "clicked" );
});
function NewShowHideDiv2(divID, disabled) {
$("#" + divID).slideToggle("slow", function() {
});
}
});
Try this with vanilla JS:
var x = document.getElementById('divID');
x.addEventListener('click', function(e) {
if(e.target.classList.contains('clicked')) {
e.target.classList.remove('clicked');
} else {
e.target.classList.add('clicked');
}
});
I think JQuery is:
$('#divID').click(function() {
$('#divID').toggleClass('clicked');
});

Passing function and function argument in .on('click') event handler? [duplicate]

This question already has answers here:
How can I pass arguments to event handlers in jQuery?
(6 answers)
Closed 6 years ago.
When I click on the button it will say Bruce Wayne is Batman. In the last jQuery line, for the 'click' function, if I pass the parameter 'guy', the jQuery wont run, but if I don't pass in a parameter I get undefined. What am I doing wrong? Thanks in advance.
$("div").on('click', 'button', click(guy));
The jsFiddle link, HTML and JS are below.
https://jsfiddle.net/wrj5w1Lk/
<div>
<button>
Click Me! Click Me!
</button>
<p>Hello</p>
</div>
$(document).ready(function() {
var Person = function(first, last, secret) {
this.first = first;
this.last = last;
this.secret = secret;
}
var guy = new Person("Bruce", "Wayne", "Batman");
var click = function(person) {
$(this).closest('div').find('p').text(person.first + " " + person.last + " is " + person.secret);
};
$("div").on('click', 'button', click(guy));
});
You have two issues, firstly you need to wrap the call to click() in an anonymous function. Secondly you need to pass the reference of the current button element to your click() function. Try this:
var click = function($element, person) {
$element.closest('div').find('p').text(person.first + " " + person.last + " is " + person.secret);
};
$("div").on('click', 'button', function() {
click($(this), guy);
});
Updated fiddle
I think what you're looking for is how to pass custom data to the event handler using .on(). The link references the optional [ data ] object of the .on() function. This allows you to pass custom data outside of the normal event data to your event handler for further processing. An example is shown below:
$(document).ready(function() {
var Person = function(first, last, secret) {
this.first = first;
this.last = last;
this.secret = secret;
}
var guy = new Person("Bruce", "Wayne", "Batman");
var click = function(event) {
$(this).closest('div').find('p').text(event.data.first + " " + event.data.last + " is " + event.data.secret);
};
$("div").on('click', 'button', guy, click);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button>
Click Me! Click Me!
</button>
<p>Hello</p>
</div>
I've edited your snippet from your question to use this method of passing data. Your custom object is passed in the event.data object of the callback. By accessing, event.data.[first,last,secret] you can reference the properties of the Person(...) object from within your callback.

Passing this to a method?

p.num = 100;
$('body').on('click', '.del', this.delete.bind(this));
p.delete = function(e) {
console.log(this.num); //100
//how can I get the .del element?
}
I'm trying to get the element that produced the click, but I also need access to the num property.
How can I access both types of 'this' inside my delete method?
The callback for an event receives an Event object that you can use to retrieve the element on which the event was called.
function(e) {
var element = $(e.target); //This is the element that the event was called on.
}
Disclaimer : This is the my exact answer (adapted with the current code) taken from here : Pass additional arguments to event handler?
Yet, the question doesn't seem to be an exact duplicate (but i may be wrong).
As said in the documentation of .on, you can pass datas to your event.
.on( events [, selector ] [, data ], handler )
data
Type: Anything
Data to be passed to the handler in event.data when an event is triggered.
So your event could look like that :
p.num = 100;
$('body').on('click', '.del', {object : this}, this.delete);
p.delete = function(e) {
var myObj = e.data.object;
// [myObj] will be your plugin
// [this] will be the clicked element
// [e] will be you event
}
if you're using jquery, you can combine those functions all into one like below:
note: num is an attribute so you have to use .attr().
$(document).ready(function() {
$('body').on('click', '.del', function() {
var num = $(this).attr('num');
alert('click function and num = ' + num);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Delete
or if you really want to keep them separate functions....:
$(document).ready(function() {
$('.del').on('click', function() {
deleteThis($(this));
});
});
function deleteThis(element){
var num = element.attr('num');
alert('click function and num = ' + num);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Delete
also, if youre using separate functions for the click and the delete, pass the element from click to delete: pass element - callDeleteFunction($(this)), and retrieve element - myDeleteFunction(element aka $(this))
I'm not sure what you're asking about but maybe this is what you want:
var p = {};
p.num = 100;
$('body').on('click', '.del', p.delete); // don't bind to this
p.delete = function(e) {
console.log(p.num); // here you still can call p
// this is del DOM element
}

get clicked element ID or Name jquery or javascript

I wants to get the ID or the name of the clicked elemt by using the following code. this code is working fine if i have only one element.
$(window).mousedown( function(e) {
mouseTracker.clickState = true;
console.log( "id:" + e.target.id + " name:" + e.target.name );
}).mouseup( function() {
mouseTracker.clickObject = '';
});
but if element is wrapped up in other elements then i am unable to get the ID. for example:
<div id="main">
<div id="subDiv">
<span id="spID" onClick="alert ('hello world')"> Click Me </span>
</div>
</div>
in the above case, it is return the ID of the main div. how can i get the clicked element.
The most secure way to do this is to add an event listener to each element. There are different ways to do that:
First as you have coded in your HTML:
var testfunction = function(event){
// Do something
};
<span id="spID" onclick="testfunction(event)"></span>
Or nicer:
<span id="spID"></span>
var element = document.getElementById('spID');
element.addEventListener('click', function(event){
// do something
})
Best regards
Dustin
I wouldn't use inline scripting if it was me. The bigger a project gets, the messier this becomes. I tend to have all my event listeners tucked away together in an init function that you can just add to as you need more event listeners:
In the head of your HTML:
<script src="global.js"></script>
<script>
$(document).ready(function() {
global.init();
});
</script>
In a separate js file, linked to your HTML (e.g. global.js):
(function (global, $, undefined) {
global.init = function() {
//bind your event listeners in here
};
})(window.global = window.global || {}, jQuery));
In terms of using this for the purposes of what you are trying to do, if you have a series of these clickable spans, I would use a class selector, so you only have to bind the click event once, otherwise if you are binding to only one span as above then you already know the ID anyway as you had to use it in the bind.
Using class:
global.init = function() {
//assuming you have applied the class "clickable-span" to all the spans you want to be clickable
$('.clickable-span').on('click', function(evt) {
var id = $(this).attr('id'),
name = $(this).attr('name');
console.log( "id:" + id + " name:" + name );
});
//add more event listeners here
};

JQuery attach event to method in instance

I have code that looks like this....
function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
$(this.input).bind('keyup'....);
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
this.input = the 1st element of type input found within 'id' which is what I will be referencing. This works fine for what I need.
What I want to do then is to bind the keyup event on 'input'. However I want the event to reference the instance method contained in my function - this.KeyUpHandler().
Also I need 'e' to be event that would have been passed into the function had I just done this on the markup for the input (onkeypress="keyuphandler();").
Any ideas how I can bind the event to the a function in the instance of the function I am working within?
function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
that=this;
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', this.KeyUpHandler);
}
It is important that you call bind() after defining the function!
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', function(){
this.KeyUpHandler(event);
//more code can go here
});

Categories