Looking for help with toggling add/remove event listeners on click. Can anyone provide suggestions to improve my code?
I've searched through various solutions on Stackoverflow without success.
This educational tool involves rotating the center cube to match the displayed number when hovering over the numbers.
Upon page load, an event listener is added to the center cube and additional jQuery code is used to add listeners to any clicked cube to display the hovered number.
The functionality works smoothly in Chrome, somewhat in Opera, but encounters issues in FF and IE.
View current functionality
Event listener added on page load
var thisCube = '.two';
var init = function() {
var box = document.querySelector(thisCube).children[0],
showPanelButtons = document.querySelectorAll('#hover-change li'),
panelClassName = 'show-front',
hover = function( event ){
box.removeClassName( panelClassName );
panelClassName = event.target.className;
box.addClassName( panelClassName );
};
for (var i=0, len = showPanelButtons.length; i < len; i++) {
showPanelButtons[i].addEventListener( 'mouseover', hover, false);
}
};
window.addEventListener( 'DOMContentLoaded', init, false);
jQuery code to add a new listener
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').click(function() {
thisCube = $(this).data('id');
init();
});
I suspect that I'm not properly adding the event listeners, leading to issues when comparing with other solutions.
I didn't create a jsfiddle for this post due to the size limitations. Feel free to request it if needed.
Demo built based on this
--EDIT--
Attempted to use the following code to add a class rotate
, but encountered difficulties removing the event listener.
$('.one, .two, .three, .four, .five, .six, .seven, .eight, .nine').on('click', function() {
if($(this).hasClass('rotate'))
{
$(this).removeClass('rotate');
alert('remove ' + $(this).attr("class"));
$(this).off('click');
} else {
$(this).addClass('rotate');
alert('add ' + $(this).attr("class"));
thisCube = $(this).data('id');
init();
}
});
-- My Solution --
$('.container').click(function(){
$(this).toggleClass('rotate');
});
$('#hover-change').children().hover(function(){
$('.rotate > #cube').removeClass();
$('.rotate > #cube').addClass($(this).attr('class'));
},
function(){});