Getting the class of the element that fired an event using JQuery - javascript

is there anyway to get the class when click event is fired. My code as below, it only work for id but not class.
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id + " and " + event.target.class);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
click me 1
click me 2
</body>
</html>
jsfiddle code here

Try:
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id+" and "+$(event.target).attr('class'));
});
});

This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.

You will get all the class in below array
event.target.classList

A variant on Vishesh answer, which instead returns a Boolean:
event.target.classList.contains(className)

$(document).ready(function() {
$("a").click(function(event) {
var myClass = $(this).attr("class");
var myId = $(this).attr('id');
alert(myClass + " " + myId);
});
})
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
click me 1
click me 2
</body>
</html>
This works for me. There is no event.target.class function in jQuery.

If you are using jQuery 1.7:
alert($(this).prop("class"));
or:
alert($(event.target).prop("class"));

Careful as target might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like
var t = ev.srcElement || ev.target;
thus leading to
$(document).ready(function() {
$("a").click(function(ev) {
// get target depending on what API's in use
var t = ev.srcElement || ev.target;
alert(t.id+" and "+$(t).attr('class'));
});
});
Thx for the nice answers!

$(e.target).hasClass('active')

Related

Calling javascript function

I have the problem, that my javascript function isnĀ“t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.

Why doesn't this click handler work in JQuery?

I've got the following code in my page:
var offer_link = $('<a>').addClass('fc-offer-link');
offer_link.click(function() {
alert('Hello');
});
offer_link.attr('href', "#" + this.id);
offer_link.append(this.subject);
this.list_item = $('<li>');
this.list_item.append(offer_link);
But even though the link appears on the page, the handler never gets called. What's going on?
The problem turned out to be where the item got inserted into the DOM. It was being inserted using:
$('#my_list').html(my_new_list.html())
It should have been using:
$('#my_list').replaceWith(my_new_list)
I think you just need to append the link to an element, like this:
<script type="text/javascript">
$(function(){
var link = $("<a>Click Me!</a>").addClass("fc-offer-link").appendTo($("#div1"));
if (link){
link.click(function(){
alert("Hey there!");
});
}
});
</script>
<div id="div1"></div>
EDIT: Not sure why I was downvoted, but here's a jsFiddle

Javascript replace has no effect

This is the jQuery:
<script type="text/javascript">
$(document).ready(function(){
var relName;
$('.child').each(function() {
relName = $(this).attr('rel');
relName.replace('&','');
$(this).attr('rel', relName);
$(this).appendTo('#' + $(this).attr('rel'));
});
});
</script>
With this relevant HTML:
<div rel="MadDogs&EnglishmenHandpaintedfigurines" id="Figurines" class="category section child">
<h3 class="categoryTitle">Figurines</h3>
</div>
But for some reason, the replace has no effect whatsoever!
replace returns string with replaced data. So you need to assign back to your variable.
relName = relName.replace('&','');
replace() doesn't change the original string, it returns a new one.
It's not updating because you're not assigning the result to anything.
Try this instead:
$(this).attr('rel', relName.replace('&',''));
Here's a neat way to write it, using the callback version of attr basically every jQuery method:
$(document).ready(function() {
$('.child').attr('rel', function(i, relName) {
$(this).appendTo('#' + relName);
return relName.replace('&','');
});
});

JQuery with Element ID

I am trying to create a bit of jquery code to update an element but im having a problem. It wont update and I think its because of the element id?
Here is my JS Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#vote_button_" + $(this).attr('id')).click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
And this is the HTML Code:
<div class="vote_container">
<div class="vote_button" id="vote_button_31"><img src="/images/picture_31.png"></div>
<div class="vote_count" id="vote_count">0</div>
</div>
You're telling it to use the ID of the document (I think).
You can surely just do:
$("#vote_button_31").click(function()
{
$("#vote_count").show().html('<h2>voting, please wait...</h2>');
});
If you want the code to work on all vote buttons try this:
$(".vote_button").click(function()
{
$(this).siblings('.vote_count').show().html('<h2>voting, please wait...</h2>');
});
$("#vote_button_" + $(this).attr('id')).click(function()...
The way you've called it, this has no context at all. Since you have a class on the div in question, why not use that instead?
$(".vote_button").click(function() {...
That will also work if you don't know the id in question when the page is loaded. If you're dynamically adding the divs then you might want to use live or delegate:
$(".vote_button").live("click", function() {...
Why you don't select the element directly:
<script type="text/javascript">
$(document).ready(function()
{
$("div#vote_button_31").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
YOu cannot do this. Instead try this:
<script type="text/javascript">
$(document).ready(function()
{
$(".vote_button").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});

Alternative to document.getElementById().setAttribute() function

Is there any alternative to doing the following line:
document.getElementById("btn").setAttribute("onclick", "save(" + id + ");");
This line basically changes the onclick() event of a button to something like: save(34); , save(35); etc. However it fails in IE 7 and 6 but works in IE 8 and Firefox.
I can use jquery for this as well.
Plain old javascript:
var myButton = document.getElementById("btn");
myButton.onclick = function()
{
save(id); //where does id come from?
}
jQuery:
$(function(){
$("#btn").click(function(){
save(id); //where does id come from?
});
});
If you can use jQuery, then:
$("#btn").click(function() { save(id); })
Also this one :
$("#btn").bind('click', function() { save(id); });

Categories