简体   繁体   中英

classList.toggle doesn't work in Firefox

I have noticed that toggling class in Firefox is not working and I'm not sure why.

var contactUs = document.querySelectorAll('.contact-us')[0];

var buttonExpand = document.querySelectorAll('a.write')[0];
buttonExpand.addEventListener('click', function(e) {
    contactUs.classList.toggle('js-expand-form');
    console.log('click');
},false);

When I click on a.write in Firefox nothing happens. It works on Chrome and IE.

The problem is related both to event binding and to classList.toggle , because console.log('click') doesn't work in FF and when I type manually from console:

document.querySelectorAll('.contact-us')[0].classList.toggle('js-expand-form')

it returns true or false but nothing actually changes - inspected element doesn't get a new class.
What concerns me even more is that the same line pasted in Chrome's console doesn't take effect either, despite the fact it works in normal circumstances.

jQuery's equivalent jQuery('.contact-us').toggleClass('js-expand-form') works in every browser, including pasting into console.

See the fiddle .

You change the class on link ( a.write ). I'd guess that the link fires, page reloads and changes are flushed away.

Try to add

e.preventDefault();

in the handler after the toggle() command.

Mystery solved. The problem was caused by including code in window.onload :

window.onload = function() {
var buttonExpand = document.querySelectorAll('a.write')[0];
buttonExpand.addEventListener('click', function(e) {
    console.log('click');
},false);
}

It started to work in Firefox after moving it elsewhere:

var buttonExpand = document.querySelectorAll('a.write')[0];
buttonExpand.addEventListener('click', function(e) {
    console.log('click');
},false);

window.onload = function() {
}

Not sure why Firefox had problem with that, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM