Reputation: 37
This is the jQuery code that basically opens and closes a div:
jQuery('#filter_werk').find('.raven-sortable').addClass('opened');
var toggle = document.getElementById('deknop');
var slider = document.querySelector('.raven-sortable');
toggle.addEventListener('click', toggleSlider, false);
function toggleSlider(){
if (slider.classList.contains('opened')) {
slider.classList.remove('opened');
slider.classList.add('closed');
} else {
slider.classList.remove('closed');
slider.classList.add('opened');
}
}
</script>
What I'm trying to do is change the content of the following div from "FILTER +" to "FILTER -" and back again to "FILTER +" when its clicked again
<div id="deknop">FILTER +</div>
Could this be done without breaking the current jQuery code? Thank you!
Upvotes: 0
Views: 47
Reputation: 1992
Well,
if I had to do this jQuery-style, I would either way try to separate the data from the view. Something like:
(() => {
const state = {
sliderOpen: true,
};
const $slider = $('.raven-sortable');
const $toggle = $('#deknop');
const updateView = () => {
if (state.sliderOpen) {
$slider.addClass('opened').removeClass('closed');
} else {
$slider.addClass('closed').removeClass('opened');
}
$toggle.text(`FILTER ${state.sliderOpen ? '+' : '-'}`);
};
const onToggleClick = () => {
state.sliderOpen = !state.sliderOpen;
updateView();
};
$toggle.click(onToggleClick);
updateView();
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="raven-sortable">Raven sortable</button>
<button id="deknop"></button>
Upvotes: 0
Reputation: 947
You can add some logic to your toggleSlider()
function that will change your #deknop
text based on what it currently is (either ‘FILTER +’ or ‘FILTER -‘ like this:
function toggleSlider(){
$('#deknop').html($('#deknop').text() == 'FILTER +' ? 'FILTER -' : 'FILTER +');
if (slider.classList.contains('opened')) {
slider.classList.remove('opened');
slider.classList.add('closed');
} else {
slider.classList.remove('closed');
slider.classList.add('opened');
}
}
Upvotes: 0
Reputation: 486
As I understood the function toggleSlider
works fine so try:
function toggleSlider(){
if (slider.classList.contains('opened')) {
slider.classList.remove('opened');
slider.classList.add('closed');
toggle.innerHTML = "FILTER +";
} else {
slider.classList.remove('closed');
slider.classList.add('opened');
toggle.innerHTML = "FILTER -";
}
}
Upvotes: 1