I am using this code to remove and a CSS class:
$('.called').click(function() {
$('called').removeClass('fa-phone-square').addClass('fa-check');
})
The problem is, it removes and adds classes to ALL tags with the class '.called'. I want this function to work only for the single item that has been clicked.
How would I do this?
In jQuery event handlers this gets bound the the DOM node that fired the event.
$('.called').click(function() {
$(this).removeClass('fa-phone-square').addClass('fa-check');
})
You would have to do this:
$('.called').click(function() {
$(this).removeClass('fa-phone-square').addClass('fa-check');
})
"this" inside the click handler refers to the element that has been clicked and which you want to apply the changes.
If you instead apply the ".called" selector again it will select all items with the "called" class and apply the removeClass and addClass to all of them which is the behavior you are experiencing now.
Inside the callback, $(this) refers to the element that was clicked.
You can also have the event as an argument in the callback and get the clicked element with event.target - https://api.jquery.com/event.target/
Difference between using $(this) and event.target - Difference between $(this) and event.target?
Related
Say I have:
<a href="http://foo.com" class="SiteClass">
Then I via jQuery I do some tests and conditionally update the class depending on the outcome, for example adding SiteDown css via jQuery addClass method, resulting in:
<a href="http://foo.com" class="SiteClass SiteDown">
I have the following JavaScript which does not fire:
$("a .SiteDown").on('click', function(e){
e.preventDefault();
e.stopPropagation();
alert('Clicked SiteDown');
});
What do I need to be able to fire an alert (or any other code there) when a link with class SiteDown is clicked, keeping in mind this class can be added dynamically.
You selector is incorrect, remove space to convert it to element with class selector.
$("a.SiteDown").on('click', function(e){
//....
});
As of now its descendant selector.
As you are approach when manipulation selector, use Event Delegation using on().
$(document).on('click', "a.SiteDown", function(e){
//....
});
In place of document you should use closest static container.
In your code $("a .SiteDown") you are looking for an element that is child of a remove space and it will be ok. use $("a.SiteDown") meaning a with class SiteDown
I am trying to implement a function which changes style of element on click and remove it when unfocus. For ex: When element2 is clicked, it should remove class of other elements, and add class to the clicked element only.
<div class="dope" id="element777"></div>
<div class="dope" id="element2"></div>
<div class="dope" id="element11"></div>
<div class="dope" id="element245"></div>
<div class="dope" id="element60"></div>
.....(More are created automatically, numbers are not estimatable)
I couldnt know the element ids that are created. The only remains same is class.
I have tried this, but its an unprofessional approach.
$('#element1').click(function(){
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element1").blur(function(){
$("#element1").removeClass(dope);
});
$('#element2').click(function(){
$("#element2").addClass(dope2);
$("#element1").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element2").blur(function(){
$("#element2").removeClass(dope);
});
What is the best approach for automating this function, instead of adding click and blur (unfocus) function to ALL of elements ?
You can listen for click events on any div with an id containing the word "element', then target its siblings elements (those that are not clicked, without referring to them by id). This might do it:
$("div[id*='element']").click(function(){
$(this).addClass('dope').siblings('.dope').removeClass('dope');
});
Your jQuery could be vastly simpler if you leverage this and siblings:
Instead of:
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
It could be:
$('.dope').click(
function() {
$(this).addClass(dope2).siblings().removeClass(dope);
}
);
NOTE:
Do you have a variable called dope with the class name, or is dope the class name? If it's the classname, you need to put it in quotes: $(this).addClass('dope2'), etc.
If you are removing the class dope, then will want to add a class you can always use to select these elements (so that when you remove dope, it continues to work).
Button part:
$("div").click(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).addClass("dope2");
$(".dope").not($(this)).removeClass("dope");
}
})
Blur part:
$("div").blur(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).removeClass("dope");
}
}
I would recommend using the :focus css selector rather than using javascript to do what you are doing... Read more here. Instead of having a click listener, the focus selector will take care of that for you and automatically remove the styling when the element is out of focus.
I have this code:
$(".div").click(function ()
{
alert("hi");
});
...but when I create new div:
$("body").append("<div>1</div>");
...and click on this div, it doesn't say "hi".
I know that I can do onclick="callfunction()" on the div element, but I would like to avoid using that method.
Problems
You were attempting to create a bind on an element that didn't yet exist - so it couldn't be bound.
You used .div as a selector. The selector .div is looking for an element with class="div" rather than an element of type div.
Solution 1 - Delegation
With delegation you create a bind on an element that exists in the structure above where you will be dynamically adding an element that you want to listen for.
To use delegation, change to this:
$("body").on("click", "div", function ()
{
alert("hi");
});
Here is an example showing delegation vs binding on a future element without delegation:
Fiddle
Solution 2 - Bind to element on creation
The alternative would be to add the bind on the creation of the new element, that would look something like this:
$newEle = $("<div>1</div>").click( function() {
alert("hi");
});
$("body").append($newEle);
Fiddle
Use the appendChild() method to add the DIV to the end of your document. See: http://www.w3schools.com/jsref/met_node_appendchild.asp
Your other logic can follow the creation of the div.
I am aware that e.target contains the info of the element just below the cursor, but what if I want to know the class name of the div which has a table>tr>td>button in it and I'm clicking that button inside that td. I know this events bubbles up and there should be a way to find out if the div exists in that bubbling levels. Any help.
Scenario: button is inside a modal window. How do I find the modal windows class name on click of the button inside it.
Use .closest() to traverse up the DOM to the nearest match:
var parentDiv = $(yourButton).closest('div');
Or in the button's click:
$(yourButton).click(function() {
var nearestParentDiv = $(this).closest('div');
// And read its class
console.log(nearestParentDiv.attr('class'));
});
The selector .closest() accepts can of course be more specific than this, so if if the modal window <div> has some known class but you need to inspect its other classes, you should use the more specific selector.
Yes as you say the event will bubble up to your div, so just make the div handle the event with .on() , like this:
$('#yourdiv').on('click',':button',function(e) {
alert( $(e.delegateTarget).attr('class') );//alerts the classes of #yourdiv
alert( $(this).attr('id'));//alerts the id of the clicked button (if have one)
});
UPDATE:
Fixed obtaining the reference to the original div where the event was attached. With event.delegateTarget from the Event object . Thanks Cristophe and Kevin B. for spotting the error.
See working demo
You can use .parent() to get the parent div attributes like id: http://jsbin.com/ololad/1/edit
$('button').click(function(){
console.log($(this).parent().attr('id'));
});
How would I add a class to an object of a specific class upon click? The elements that should gain an extra class contain the "date" class.
$(".date").bind("click",addClass());
function addClass(){
//objectClicked.className+=""
}
I'm having trouble figuring out how to identify the exact element that was clicked.
In a jQuery event handler, this is bound to the source element of the event, so your can use $(this).addClass('yourClass'); to add the new class to the clicked element.
$(".date").bind("click", addClass);
function addClass() {
$(this).addClass('yourClass');
}
Also, watch out that you don't invoke the addClass function in the call to bind. That won't work. You need to pass the function itself as I have.
Though FishBasketGordo answer is a working solutions, you can also do it this way :
$(".date").click(function() {
$(this).addClass("yourClass");
});