.removeClass doesn't work how addClass does? - javascript

Forgive me for being a noob, but shouldn't this work?
$(document).ready(function() {
$('.button').click(function() {
$(this).addClass('button-clicked');
});
$('.button-clicked').click(function() {
$(this).removeClass('button-clicked');
});
});
Shouldn't the second click remove the class and take it back to .button?
Here it is on jsfiddle: http://jsfiddle.net/pXdwM/

no, because at the point you're calling the second click() the button doesn't have ".button-clicked" and therefore event handler is not assigned. You could rewrite it like this
$('.button').click(function() {
$(this).toggleClass('button-clicked');
});
or use live()
$('.button-clicked').live("click", function() {
$(this).removeClass('button-clicked');
});

You are adding an event to each element with class '.button-clicked', but the class does not apply until you actually click. So you need to move the second listener into the first callback, or use the toggleClass function:
$('.button').click(function() {
$(this).toggleClass('button-clicked');
});

Related

Get single event on click on div in for loop

var id=100;
for(var i=0;i<5;i++) {
$("#divtext_"+id).click(function(e) {
onClicked();
});
}
function onClicked() {
alert("Clicked")
}
I tried with .on() , delegate(), and one() events.
When I clicked div, the onClicked() function gave an alert() 4 times.
Is it possible when I click div text/image to get one time function/alert?
This is how I would expect the code to run under jquery, the options here would be to either use .unbind (http://api.jquery.com/unbind/) to remove all previous instructions for this div or to check if the event has already been bound, this has been covered here. How to check if click event is already bound - JQuery
Presuming you have divs with IDs divtext_0 ... divtext_4
for(var i=0;i<5;i++) {
$("#divtext_"+i).click(function(e) {
onClicked();
});
}
function onClicked() {
alert("Clicked")
}
At the moment you are adding multiple click handlers to the div divtext_100 - rather than adding one click handler to multiple divs.
It is hard to say what is best without seeing your HTML - but if you gave all your divs a class, e.g. 'clickable', then you can avoid any loops and make any div with that class clickable.
<div class="clickable"></dvi>
You could simply do.
$(".clickable").click(function(e) {
onClicked();
});
function onClicked() {
alert("Clicked")
}
try this:
$("#divtext_"+id).one("click", function(e){
onClicked();
});
You can use
$("#divtext_"+id).off('click',onClicked).on('click',onClicked);
function onClicked() {
alert("Clicked")
}
'.off' prevents binding of onClicked function multiple times. I think using .off will solve your problem.
If you are using older version of jquery then use .unbind.

How to toggle an element with on()?

I am using the Hammer.js library for mobile touch events and in their example for use with jQuery, they have the following:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
console.log(this, event);
});
This is straightforward; however, I would like to incorporate a toggle behavior to #test_el. In other words, if the above example was replaced with something like this:
$('button').hammer().on("tap", function() {
$('div').addClass('open');
}, function {
$('div').addClass('close');
});
How would I get this "toggle" behavior to work?
Initially, you could add a starting class to all buttons. Then on event, you can check if the class exists. This lets you know what state the element was in when you tapped it.
$('button').addClass('close');
$('button').hammer().on('tap', function() {
if ($(this).hasClass('close')) {
$(this).removeClass('close').addClass('open');
// Event code
}
else {
$(this).removeClass('open').addClass('close');
// Event code
}
});
jQuery also provides a toggleClass method.
There is already a toggleClass function available in JQuery, it seems that it does what you want.
Try:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
$(this).toggleClass("classnamehere");
});
Where classnamehere would be your class name.

jQuery click function acting strange when adding/removing classes

I have two list items that, when clicked, should change classes from '.off' to '.on'. Only one element should be '.on' at a time so when one is already turned on and the other is clicked both elements should change classes from '.off' to '.on' and vice versa. If a list item with a class of '.on' is clicked it should change classes to '.off'
The problem I am having is when a list item with class '.on' is clicked it still runs the click function as if it had a class of '.off'
My html:
<ul>
<li>ABOUT</li>
<li>SUBMIT</li>
</ul>
My javascript (running on jQuery 1.7.1)
$('.off').click(function(event) {
event.preventDefault();
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
});
$('.on').click(function(event) {
event.preventDefault();
$(this).addClass("off").removeClass("on");
});
Does anyone know what is going on here? Is there something wrong in my code or have I encountered some sort of bug here?
http://jsfiddle.net/ZC3CW/6/
The selectors you're using to bind the event using click() are used to select the elements to add the event handler to. The selector is not considered when the handler is run.
You should be looking for something more like this:
$('li').click(function(event) {
event.preventDefault();
if ($(this).hasClass('off')) {
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
} else { // $(this).hasClass('on');
$(this).addClass("off").removeClass("on");
}
});
You might want to make the li selector more explicit by adding a class/id to the ul or li's.
To confuse things further, you could also do this (if you're using jQuery > 1.7);
$(document).on('click', '.off', function(event) {
event.preventDefault();
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
});
$(document).on('click', '.on', function(event) {
event.preventDefault();
$(this).addClass("off").removeClass("on");
});
This is because the .on() function works by attaching the event handler to the selected elements (document), and will only execute the handler (the function) on the event specified (click) if the element that the event originated from matches the selector .off at the time the event fired, not at binding time.
I would suggest adding a click handle to a different selector, this should work for you...
$("ul li a").click(function(e){
e.preventDefault();
if($(this).hasClass("off")){
$("ul li a").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
}
else{
$(this).addClass("off").removeClass("on");
}
});
The problem is that jQuery handlers get attached at page load and remain the same regardless of changing their classes. Use live('click', handler) on('click', handler) instead of click().
Edit: just noticed that .live() is deprecated in jQuery 1.7.
The problem as I see it is that your "on" class is not in play at the time of the click event, so your $('.on').click method is never being called.
Try re-assigning your events after changing classes (example follows) :
var assignClicks = function () {
$('.off').click(function(event) {
event.preventDefault();
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
assignClicks();
});
$('.on').click(function(event) {
event.preventDefault();
$(this).addClass("off").removeClass("on");
assignClicks();
});
};
assignClicks();
Hope this helps,
Pete
The click is bound to the element not the class.
Maybe you can attach the events to the elements and detect/toggle the elements classes:
$('li').click(function(event) {
event.preventDefault();
if( $(this).hasClass('on') ) {
$(this).removeClass('on');
}
else {
$(this).addClass('on');
$(this).siblings().removeClass('on');
}
});

How to check if there is already a click/event associated to an element

lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});

Access an element by class using jQuery

I have a table with an ID of InstrumentListGrid. When a row is selected, it sets the class to ui-iggrid-activerow. I want to add a jQuery event on that row for when someone clicks it.
So far I have
$("#InstrumentListGrid tr.ui-iggrid-activerow").click(function (event) {
alert("YAY!");
});
but that isn't firing. How do I bind to an element by class?
since the class is presumably added dynamically you should use .delegate()
$('#InstrumentListGrid').delegate('.ui-iggrid-activerow', 'click', function (e) {
// do stuff.
});
It appears that ui-iggrid-activerow is dynamically added. Use the live() function:
$('#InstrumentListGrid tr.ui-iggrid-activerow').live('click', function() {
alert('YAY!');
});

Categories