Reputation: 33
Ive got this so far
var main = function() {
/* Push the body and the nav over by 285px over */
$('.fa-plus').click(function() {
$(this).removeClass( "fa-plus" ).addClass( "fa-times" );
$('#side-menu').animate({
left: "0px"
}, 200);
$('#content-area').animate({
left: "200px"
}, 140);
});
/* Then push them back */
$('.fa-times').click(function() {
$(this).removeClass( "fa-times" ).addClass( "fa-plus" );
$('#side-menu').animate({
left: "-285px"
}, 200);
$('#content-area').animate({
left: "0px"
}, 200);
});
};
$(document).ready(main);
Full script and html here http://jsfiddle.net/sd6b5my4/
What im trying to achieve is when you press on fa-plus the menu opens and changes the fa-plus to fa-times giving the impression of it transforming, however the script to close it and turn the fa-times back to fa-plus doesn't seem to be working
can anyone help me?
Thank you
Upvotes: 2
Views: 38
Reputation: 10618
The problem is that the $('.fa-times').click()
is not bound to the element yet because the element you're trying to bind this event to doesn't have the fa-times
class yet. It gets the class only when it's clicked on. One solution is event delegation as mentioned by the other answer.
Other solution could be to create 2 elements - a plus button and a cross button, with the cross button hidden initially.
So, the markup would look something like:
<i class="fa fa-times"></i><i class="fa fa-plus"></i>
And the script would change to:
var main = function() {
// Hide the cross initially.
$(".fa-times").hide();
$('.fa-plus').click(function() {
$(this).hide(); // Hide the plus
$(".fa-times").show(); // Show the cross
...
});
$('.fa-times').click(function() {
$(this).hide(); // Hide the cross
$(".fa-plus").show(); // Show the plus
...
});
}
Upvotes: 0
Reputation: 240888
The event listener $('.fa-times').click(function() { ... });
never even gets called because at the time the script is executed, there are no elements with class .fa-times
. When you change the element's class, the initial event listener is still attached to the element, but the expected event listener isn't.
One solution would be to use event delegation and bind the click events to a constant parent element. In this case, document
.
$(document).on('click', '.fa-plus', function () {
// ...
});
$(document).on('click', '.fa-times', function () {
// ...
});
Alternatively, a better option would be to use one click
event listener, and then add conditional logic to determine what class the element has.
For instance:
$('.toggleableIcon').on('click', function () {
if ($(this).hasClass('fa-plus')) {
$(this).removeClass("fa-plus").addClass("fa-times");
$('#side-menu').animate({
left: "0px"
}, 200);
$('#content-area').animate({
left: "200px"
}, 140);
} else {
$(this).removeClass("fa-times").addClass("fa-plus");
$('#side-menu').animate({
left: "-285px"
}, 200);
$('#content-area').animate({
left: "0px"
}, 200);
}
});
Upvotes: 2