javascript: remove/add class function

502 Views Asked by At

i found a very simple javascript function for a slideshow (here). It works perfectly, but i want to change something about the control buttons. Right now, the play/pause button displays it's own name, like this:

<button class="controls" id="pause">Pause</button>

The javascript is set to run a function called pauseSlideshow under certain circumstances which not only pauses/resumes the slideshow, but also changes the displayed content of the button from "pause" to "play":

var playing = true;
var pauseButton = document.getElementById('pause');

function pauseSlideshow() {
    pauseButton.innerHTML = 'Play';
    playing = false;
    clearInterval(slideInterval);
}

now, what i want to do is to leave the button empty and work width background images, and to do that i planned to do a simple class swap whenever the pauseSlideshow function is triggered. So, first i added a class called pause to the button with the desired background image set in the style:

<button class="controls pause" id="pause"></button>

and next i was going to do something like this:

var playing = true;
var pauseButton = document.getElementById('pause');

function pauseSlideshow() {
    pauseButton.removeClass('pause');
    pauseButton.addClass('play');
    playing = false;
    clearInterval(slideInterval);
}

(where play is another class with a different background image). Sufficient to say, as soon as pauseSlideshow runs, the function crashes. I'm writing something wrong or in the wrong place, but i know that the approach is viable.

please, can anybody point out the error?

EDIT:

Use $(pauseButton).removeClass('pause'); and $(pauseButton).addClass('play');. addClass and removeCalss are jQuery methods. And you need to add jQuery reference too. – user3698428

document.getElementById("pause") does not return a jQuery element. .removeClass() and .addClass() are jQuery functions. So basically you are trying to call jQuery functions on a non-jQuery element and it's throwing an error. Change it to var pauseButton = $("#pause"); or $(pauseButton).removeClass(...); $(pauseButton).addClass(...);

when i try either way, console returns: Uncaught ReferenceError: $ is not defined

1

There are 1 best solutions below

0
Simon On

When working in pure javascript, you should use this to add or remove class:

pauseButton.classList.remove('pause');
pauseButton.classList.add('play');

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList