javascript - How to remove event listener from DOM element? -
i toggle add/remove event listeners on click. point out how improve code?
i've read number of answers on stackoverflow none have helped me.
this learning tool hovering pointer on displayed numbers makes center cube rotate display same number.
when page loads event listener added centre cube , wrote little jquery add listeners clicked cube show number pointer hovers on.
works in chrome, sorta in opera. ff thinks salvador dali , ie... duh!
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 ); }; (var i=0, len = showpanelbuttons.length; < len; i++) { showpanelbuttons[i].addeventlistener( 'mouseover', hover, false); } }; window.addeventlistener( 'domcontentloaded', init, false);
jquery add new listener
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').click(function() { thiscube = $(this).data('id'); init(); });
i'm sure i'm not adding event listeners correctly , causing trouble when read other solutions.
i didn't build jsfiddle post new rule of posting relevant code make post far large. if see on jsfiddle please ask.
--edit--
i tried adding code add class rotate
, if element has class remove rotate
, remove event listener. wont remove 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(); } });
-- solution --
$('.container').click(function(){ $(this).toggleclass('rotate'); }); $('#hover-change').children().hover(function(){ $('.rotate > #cube').removeclass(); $('.rotate > #cube').addclass($(this).attr('class')); }, function(){});
you can use jquery.on add event listeners , jquery.off remove them.
//add $('.one, .three, .four, .five, .six, .seven, .eight, .nine').on('click', function() { thiscube = $(this).data('id'); init(); }); // remove $('.one, .three, .four, .five, .six, .seven, .eight, .nine').off('click');
you can use event namespace well:
//add $('.one, .three, .four, .five, .six, .seven, .eight, .nine').on('click.mynamespace', function() { thiscube = $(this).data('id'); init(); }); // remove $('.one, .three, .four, .five, .six, .seven, .eight, .nine').off('click.mynamespace');
this way don't mess other handlers..
hope helps...
Comments
Post a Comment