Jquery add/remove class not working - javascript

I've got some jQuery that I'm using to change a class of two elements. It works once, and the elements change class once, but I want it to work interchangeably. so when they click they click the 'deselected' button it assigns itself the 'selected' class, and the 2nd button changes to a 'deselected' class.
Here's the jQuery:
$('.network_bar_deselected').on('click', function(){
$('.network_bar_selected').removeClass('network_bar_selected').addClass('network_bar_deselected');
$(this).removeClass('network_bar_deselected').addClass('network_bar_selected');
});
and the HTML is quite simple:
<div class="network_bar_selected"><h4>Network Updates</h4></div>
<div class="network_bar_deselected"><h4>Latest Tweets</h4></div>

Since you're changing classes dynamically, you should use delegation:
$(document).on("click", ".network_bar_deselected", function() {
$('.network_bar_selected').removeClass('network_bar_selected').addClass('network_bar_deselected');
$(this).removeClass('network_bar_deselected').addClass('network_bar_selected');
});
Your original code only binds the handler to the elements with the network_bar_selected class when the document is loaded, not to elements that get that class later.

Add the handler to both the classes
$('.network_bar_selected, .network_bar_deselected').on('click', function () {
$('.network_bar_selected').removeClass('network_bar_selected').addClass('network_bar_deselected');
$(this).removeClass('network_bar_deselected').addClass('network_bar_selected');
});
Demo: Fiddle

Related

How to get the current/this object on button click using bind event?

I have following code:
$(document).bind('click', '.btn-yes .btn-no', function() {
$(this).toggleClass("btn-warning");
alert("test"); // <-- this works...
});
.btn-yes and .btn-no are two classes which are attached to buttons. When they are clicked, I want the btn-warning class to get attached to that button, but this is not working...
Can anyone let me know what I am doing wrong?
You need to have a comma , between your selector:
'.btn-yes, .btn-no'
and you should use event delegation only if your elements are dynamically generated after page load.
If such a case then the preferred method is .on() as per latest jQuery library. You can see this in action in the snippet below.
$(document).on('click', '.btn-yes, .btn-no', function() {
$(this).toggleClass('btn-warning');
});
.btn-warning{background:red; color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-yes'>Yes</button><button class='btn-no'>No</button>
Problem:
When you don't use comma , in your selector such as in this case you are actually trying to bind a click event on the child .btn-no which has the parent .btn-yes.
Try this:
$(document).bind('click','.btn-yes .btn-no',function(e){
$(e.target).toggleClass("btn-warning");
});
'.btn-yes .btn-no' denotes to the btn-no inside btn-yes not separate elements. So, separate your elements with a comma and use click event for that.
I also recommend you to use on instead of bind method:
$(document).on('click', '.btn-yes, .btn-no', function(){
$(this).toggleClass("btn-warning");
});
If you have jquery version 1.7+ use on method
$(document).on('click', '.btn-yes,.btn-no', function() {
$(this).toggleClass("btn-warning");
});

Remove previously added class by jQuery

I have a follow up question to this: Add and remove a class on click using jQuery?
I'm able to add a class to a specific li element using this snipped by Jamie Taylor:
$('.team').on('click', 'li', function() {
$('.team li#member').removeClass('more');
$(this).addClass('more');
});
I'd like to remove the Class .more again, by clicking a toggle element inside the li-item.
My jQuery Snippet which doesn't work:
$('.toggle-x').click(function () {
$('.team li#member').removeClass('more');
})
Thanks for the help!
In your code, it will remove the class form only one element with id member. If you want to remove the class from all the li elements, use like this,
$('.team li.more').removeClass('more');
try this
$(".innerLiContent").click(function(){
$(this).parentsUntil( "li" ).removeClass('more');
});
Your problem is because when you click on an element X inside the <li /> the element fires the click event, and if you don't use event.stopPropagation() the <li /> will also fire the click event and the class will be added again.
Try this:
$('.toggle-x').click(function (e) {
$('.team li#member').removeClass('more');
e.stopPropagation();
})
It should work if that's your problem.

jQuery - one of the two divs open onLoad

My jquery should open only the first of two divs on page load, but now it opens both.
Also, I've added .active class to my CSS to color the active divs link, but it won't work.
Jquery
$(document).ready(function () {
$(this).find('.infoexpanderContent').slideDown();
});
$('.infoexpanderHead').click(function () {
$(this).siblings().find('.infoexpanderContent').slideUp();
$(this).find('#infoactive').addClass("active");
$(this).find('.infoexpanderContent').slideDown();
$(this).siblings().find('#infoactive').removeClass("active");
});
CSS
.active {
color: green;
}
Really new to JS and Jquery so be simple please :)
Try specifying the :first selector:
$('.infoexpanderContent:first').slideDown();
By the way, there's no need for the $(this).find() method, since in the DOM wrapper, $(this) refers to the document, which is always assumed in jQuery.
Inside the dom ready handler this refers to the document object so your selector $(this).find('.infoexpanderContent') returns all infoexpanderContent elements in the page and slides them down
Fire the click event on the first element after the click handler is added
$('.infoexpanderHead').click(function () {
$(this).siblings().find('.infoexpanderContent').slideUp();
$(this).find('#infoactive').addClass("active");
$(this).find('.infoexpanderContent').slideDown();
$(this).siblings().find('#infoactive').removeClass("active");
}).first().click();
It is better to use a manual click trigger since you also will have to add the active class to the first infoactive element

Jquery appending with styling and functions

i appending buttons with some IDs and i use those IDs to make on click stuff
when it appending didn't take button() effect
and on click it don't take the function that I created it for this button id
$("button#edit-doc").each(function() {
$(this).button();
$(this).on("click", function(){
alert("clicked");
});
});
append button
$("#append").on("click", function(){
$('div#container').append("<button id='edit-doc'> Edit </button>");
});
container
<div id="container"></div>
This seems to be what you're after:
function handler() { alert('clicked'); }
$("#append").on("click", appendButton);
function appendButton(){
$('#container').append(function() {
return $("<button id='edit-doc'> Edit </button>").on("click", handler);
})
}
http://jsfiddle.net/PF8xY/
See jQuery how to bind onclick event to dynamically added HTML element for more information on this behavior.
$(document).on("click", "#selector", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/
The first code-block attaches an event listner to all buttons with class='edit-doc', use classes instead of an id since an id's name may only exist once per page. So I was saying, when your browser reaches this code an event listner is added to all available buttons in your document at that moment. It doesn't add an event listner to buttons you will be adding later onclick of some element, because it doesn't know. You will have to explicitly execute the code again for the buttons that you append. But what you don't want is to add a new event listner to the original buttons, causing two events being called.
Something like:
// Load all buttons with class=edit-doc and add event listner
$(function() {
$("button.edit-doc").button().on("click", function(){
alert("clicked");
});
});
// Append button if button with id=append is clicked
$("#append").on("click", function(){
var button = $.parseHTML("<button class='edit-doc'>Edit</button>");
$('div#container').append(button);
$(button).button().on("click", function(){
alert("clicked");
});
});
Working example:
http://jsfiddle.net/RC9Vg/

How to trigger a class-targeted method AFTER the class has been added to an element?

In the below markup, the #enable button will add a class to the #show div. This class has a method attached to it that fades in/out the #hidden span.
However, even though the class is added to the #show div, the method attached to the class isn't triggered.
HTML
<input type='button' id='enable' value='Enable' />
<div id='show'>
Testing.. <span id='hidden'>Testing, 1, 2, 3.</span>
</div>​
JS
$(function() {
// Adds .testing class after the button is clicked. however..
$('#enable').click(function() {
$('#show').addClass('testing')
});
// It will not trigger after .testing class has been added to DIV?
$('.testing').hover(function() {
$('#hidden').fadeIn();
}, function() {
$('#hidden').fadeOut();
});
});​
Fiddle to work with: http://jsfiddle.net/jS3nM/
It seems I am missing something conceptually. What is the correct way to handle this?
jQuery does not work like CSS. When you do, $("selector"), it will return a list of elements in the document that match that selector right now.
You will then operate on those elements with jQuery methods. There is no magic like "class-targeted method" going on.
You can find add a event listener to document:
$(document).on({
mouseenter: function() {
$('#hidden').fadeIn();
},
mouseleave: function() {
$('#hidden').fadeOut();
}
}, ".testing");
document is always found and always exists, and the event listener is added to that. The selector at the end filters out what elements are qualified for the event.
Because when you bind the hover handler there is no element with class of testing in the document, you should delegate the event, you can use the on method, try the following"
$(document).on('mouseenter', '.testing', function(e) {
$('#hidden').fadeIn();
});
$(document).on('mouseleave', '.testing', function(e) {
$('#hidden').fadeOut();
});

Categories

Resources