Search code examples
jqueryremoveclass

Toggle class via ESC key using jQuery?


I've set up a jQuery function to add a class to the body on pressing the ESC key.

How can I change the code below to toggle between adding and removing the class on key press, rather than just adding it once?

if(key.code == 27 && $(document.body).hasClass('preview-mode'))
     $(document.body).removeClass('preview-mode');

Solution

  • if(key.code == 27)
        $(document.body).toggleClass('Your_class_2'); //set your default class as preview-mode 
    

    for more : jQuery Effects

    Toggle Class

    Live Demo