Trying to apply classes on a click event using JS - javascript

I'm new to JavaScript and have used the primary post about how to toggle classes from here: Change an element's class with JavaScript but for some reason my code is not executing like I would expect it to. The code is placed in the bottom of an HTML file.
<script>
$(document).ready(function () {
$('.arrow').addEventListener('click', function() {
if (this.hasClass('glyphicon-chevron-right')) {
this.addClass('glyphicon-chevron-left');
this.removeClass('glyphicon-chevron-right');
}
if (this.hasClass('glyphicon-chevron-left')) {
this.addClass('glyphicon-chevron-right');
this.removeClass('glyphicon-chevron-left');
}
}, false);
});
</script>

Set up a click listener and use .toggleClass() instead of those if clauses:
$('.arrow').on('click', function() {
$(this).toggleClass('glyphicon-chevron-right');
$(this).toggleClass('glyphicon-chevron-left');
});
Or more succinctly
$('.arrow').on('click', function() {
$(this).toggleClass('glyphicon-chevron-right glyphicon-chevron-left');
});

Just use the jQuery click event.
$('.arrow').click(function() {
if (this.hasClass('glyphicon-chevron-right')) {
this.addClass('glyphicon-chevron-left');
this.removeClass('glyphicon-chevron-right');
}
if (this.hasClass('glyphicon-chevron-left')) {
this.addClass('glyphicon-chevron-right');
this.removeClass('glyphicon-chevron-left');
}
});
if you want to add the event specifically with an event listener you would probably have to select the actual element instead of the jQuery object: $('.arrow')[0]

Related

Turn on() event back after apply off

How can I turn an on('click') event back on after I apply event off()?
$('#btn-aluno').on('click', function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').off();
});
$('#btn-familiar').on('click', function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').off();
});
new-step-email-familiar and new-step-email-aluno = <input>
btn-aluno and btn-familiar = <span> (used as a button)
Instead of turning off the event listener, you could do the same thing by using event delegation,
$(document).on('click',"#btn-aluno.active", function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').removeClass("active");
});
$(document).on('click',"#btn-familiar.active", function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').removeClass("active");
});
And whenever you want to activate the event listeners, just add the class active to the relevant elements. Also in the place of document try to use any closest static parent of the element on which the event gonna be bound.
As per your requirement, you have edit your logic like below,
$(document).on('click',"#btn-aluno.active", function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').toggleClass("active");
});
$(document).on('click',"#btn-familiar.active", function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').toggleClass("active");
});
DEMO

I'm trying to attach events using on() based on changing selectors

I have a button that can be in 2 different states (lets say Lock and Unlock). When I click on the button, I update the class on the button to reflect the binary opposite state. Each class has a different event attachment function using on(string, callback). For some reason the event being triggered remains the first callback assigned based on the original class.
HTML:
<button class="lock">Lock</button>
<button class="unlock">Unlock</button>
JavaScript:
$(document).ready(function() {
$('.lock').on('click', function() {
// Perform some magic here
console.log('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$('.unlock').on('click', function() {
// Perform some magic here
console.log('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
https://jsfiddle.net/c283uaog/ for testing.
Expected console output when clicking on the same button repeatedly:
Lock!
Unlock!
Lock!
Actual console output:
Lock!
Lock!
Lock!
Any assistance would be greatly desired
use event Delegation
$(document).on('click','.lock', function() {
$(document).on('click','.unlock', function() {
updated Demo
Or use in single function with toggleClass
$(document).on('click', '.lock,.unlock', function () {
$('#output').html($(this).attr('class'));
$(this).toggleClass('lock unlock').text($(this).attr('class'));
});
ToggleClass demo
I'd do it this way, attaching only one event: http://jsfiddle.net/jozu47tv/
$(".lock").on('click', function(e) {
e.preventDefault();
if($(this).hasClass("lock")) {
$(this).removeClass("lock").addClass("unlock");
console.log("lock -> unlock");
} else {
$(this).removeClass("unlock").addClass("lock");
console.log("unlock -> lock");
}
})
Use Event Delegation method, Try this updated fiddle,
$(document).ready(function() {
$(document).on('click', '.lock', function() {
$('#output').html('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$(document).on('click', '.unlock', function() {
$('#output').html('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
Probably, this question could answer you in a better way:
jQuery .on function for future elements, as .live is deprecated
$(document).on(event, selector, handler)
Change your html to this:
<button class="locker lock" >Lock</button>
<button class="locker unlock"">Unlock</button>
<div id="output">Output</div>
and your Js to this:
$(document).ready(function() {
$('.locker').on('click', function() {
if($(this).hasClass("lock")){
$(this).removeClass("lock");
$(this).addClass("unlock");
$(this).html("unlock");
}
else if($(this).hasClass("unlock")){
$(this).removeClass("unlock");
$(this).addClass("lock");
$(this).html("lock");
}
});
});

jQuery add/remove class using 'this'

I'm trying to append a class to a div when its click and remove when its clicked a second time I currently have this has my script -
$(".project").click(function(){
if ($(".project-expand", this).is(':visible')) {
$(".project-expand",this).hide(1000);
$('.project').delay(1000).queue(function(){
$(".project").removeClass('item-dropped').clearQueue();
});
} else if ($(".project-expand", this).is(':hidden')) {
$(".project-expand").hide(1000);
$(".project-expand",this).show(1000);
$(".project").addClass('item-dropped');
}
});
But this adds the "item-dropped" class to all of my divs that have a class "project" when I change the code to -
$(".project", this).addClass('item-dropped');
It doesn't do anything, where am I going wrong here?
Instead of using the class selector $('.project') you could simply use the target of the click event ($(this)):
$(".project").click(function () {
var project = $(this);
var projectExpand = $(".project-expand", this);
if (projectExpand.is(':visible')) {
projectExpand.hide(1000);
project.delay(1000).queue(function () {
project.removeClass('item-dropped').clearQueue();
});
} else if (projectExpand.is(':hidden')) {
$(".project-expand").hide(1000);
projectExpand.show(1000);
project.addClass('item-dropped');
}
});
Additional Info :
The reason what you were trying to do didn't work originally is because $('.project', this) looks for elements with class project inside the current element (i.e. looking for a project inside a project)
You have to use $(this) to add class on the clicked item:
$(".project").click(function(){
if ($(".project-expand", this).is(':visible')) {
$(".project-expand",this).hide(1000);
$(this).delay(1000).queue(function(){
$(this).removeClass('item-dropped').clearQueue(); // Here
});
} else if ($(".project-expand", this).is(':hidden')) {
$(".project-expand").hide(1000);
$(".project-expand",this).show(1000);
$(this).addClass('item-dropped'); // Here
}
});
you have to use :
$(this).addClass('item-dropped');
concept fiddle

How we can bind event inside jquery plugin

I need to bind click event for a anchor tag which is created dynamically.
Example:
$.fn.ccfn = function(){
$(".alreadyavailabledom").click(function(){
$("<a class="dynamicallycreated"></a>");
})
//i am trying like below, but not working
$(".dynamicallycreated").click(function(){
alert("not getting alert why?")
})
}
It is written as a plugin code, i tried with on, live etc. Not working.
you should use event delegation for that
$(document).on("click",".alreadyavailabledom",function(){
//some operation
});
It helps you to attach handlers for the future elements
Use event delegation
$(document).on('click','.dynamicallycreated',function(){
alert("not getting alert why?")
})
or bind the click when creating element
$.fn.ccfn = function () {
$(".alreadyavailabledom").click(function () {
$('<a>', {
html: "anchor",
class: "dynamicallycreated",
click: function () {
alert("clicked anchor");
}
}).appendTo('#myElement');
})
}

Prevent element from animating based on previous class

$('.example').hover(
function () {
$(this).css('background','red');
},
function () {
$(this).css('background','yellow');
}
);
$('.test').click(function(){
$(this).css('marginTop','+=20px').removeClass('example');
}
);
<div class="text example"></div>
Although the class example was seemingly removed, the hover actions for it are still being applied to the element that once had that class. How can I prevent this?
http://jsfiddle.net/gSfc3/
Here it is in jsFiddle. As you can see, after executing the click function to remove the class, the background still changes on hover.
Event handlers are bound to a Node, so it doesn't matter if that Node doesn't own a specific className anymore. You would need to .unbind() those events manually, or better, use jQuerys .off() method.
So, if you can be sure that there aren't any other event handlers bound to that node, just call
$(this).css('marginTop','+=20px').removeClass('example').off();
This will remove any event handler from that Node. If you need to be specific, you can use jQuerys Event namespacing, like so
$('.example').on( 'mouseenter.myNamespace'
function () {
$(this).css('background','red');
}
).on('mouseleave.myNamespace'
function() {
$(this).css('background','yellow');
}
);
and use this call to only unbind any event that is within the namespace .myNamespace
$(this).css('marginTop','+=20px').removeClass('example').off('.myNamespace');
$('.example').unbind('mouseenter').unbind('mouseleave')
In your code, $('.example').hover attaches a mouseenter and mouseleave directly to each element.
-or-
A better solution might be to use delegation with on
$(document.body).on('mouseenter', '.example', function() { ... });
$(document.body).on('mouseleave', '.example', function() { ... });
Using that code, removing the example class will work as expected, because the handlers are based on css selector, while .hover attaches directly to the elements.
$('.example').live({
mouseenter:function () {
$(this).css('background','red');
},
mouseleave:function () {
$(this).css('background','yellow');
}
});
demo: http://jsfiddle.net/gSfc3/1/
Try this:
$('.test').hover(
function () {
$('.example').css('background','red');
},
function () {
$('.example').css('background','yellow');
}
);

Categories

Resources