Reputation: 2758
How can I know on which type of HTML object I have clicked using jQuery?
For Example, If I click on Button then it should inform me that This is button object or Text input or Textarea... like that.
Why I asked this question?
Because I am facing one issue of this type.
I have one Textarea and just below underneath I have file input HTML object. I have bound Caret function (which returns current cursor position in Textarea) to that Textarea. But when I click on Browse button to upload file it gives me an error. So I want to prevent this by know which type of HTML object is?
Upvotes: 2
Views: 1694
Reputation: 8171
You can also use some DOM properties to getting the object type:
e.target.nodeName
OR
e.target.tagName
For example:
HTML -
<input class="Track" type="button" value="Submit" />
<button class="Track">Submit</button>
Jquery -
$('.Track').click(function (e) {
alert("Object: " + e.target.nodeName + " Type: " + e.target.type);
});
Upvotes: 0
Reputation: 5650
Well you may use attr("tagName") which will return name of the tag.
Example code snippet: Suppose you click on some element having id as #myId then bind click event and get the attr("tagName") (The jQuery way)
$('#myId').on('click', function(){
console.log($(this).attr('tagName'));
});
This should help.
Upvotes: 1
Reputation: 743
$(e.target) - Contains DOM element user clicked on. We can use this object to get anything and everything regarding object user has clicked on.
e.target is always going to be the top element clicked.So while every click on the screen is technically click on the body, e.target will always return the furthest child element in the tree that occupies clicked area. However, we might have multiple absolutely positioned elements occupying the same area. In this case, the element with higher z-index will be returned.
Upvotes: 0
Reputation: 3045
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="log"></div>
<input type="button" id="myButton" value="Button">
<input type="submit" id="myButton" value="submit">
<input type="text" id="myButton" value="text">
<input type="date" id="myButton" value="date">
<textarea>Test</textarea>
<script>
$("input, textarea").on('click', function (e) {
$( "#log" ).html( "clicked: " + event.target.nodeName + " Type: " + this.type);
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 10378
$(this).attr("tagName")
or can use
$(this).prop('tagName');
Upvotes: 0
Reputation: 27855
you may do it like
$(".myBtn").click(function(){
alert($(this).prop("tagName"));
});
here is a demo fiddle
Upvotes: 3
Reputation: 22212
in the click event
function(e){
var type=$(this).prop('tagName'); // I think it will need jQuery >1.6
// or
var type=$(this)[0].tagName;
}
Actually, there are quite a few posts in the past about this question.
Upvotes: 1