Reputation: 5106
I have to functions: openNav
and closeNav
and a button:
<a href="#" data-toggle="sidebar-collapse-button">
<img class="sidebar-img" id = "collapse-img" src="${pageContext.request.contextPath}/imgs/main/sidebar/collapse.png"/>
<span class="sidebar-text">Collapse</span>
</a>
A try to set a conditional onClick
like this:
var collapsed = 0;
$('[data-toggle=sidebar-collapse-button]').click(function() {
if (collapsed==0) {
closeNav();
}
else {
openNav();
}
});
So that when collapsed = 1
function openNav
is called and vice versa:
function openNav() {
...
collapsed=0;
}
function closeNav() {
...
collapsed=1;
}
However it only works the first time to call closeNav
and then the button doesn't react at all.
Upvotes: 0
Views: 959
Reputation: 418
As @connexo said, I would be inclined to use a toggle as well - if it is a show and hide you are trying to achieve.
If you want to use your logic, you can do something like this using a data attribute (or something similar):
Eg:
<a href="#" data-toggle="sidebar-collapse-button" data-state="0">
<img class="sidebar-img" id = "collapse-img" src="https://via.placeholder.com/150"/>
<span class="sidebar-text">Collapse</span>
</a>
And for your script you can use:
var collapsed = 0;
$('[data-toggle=sidebar-collapse-button]').click(function() {
var state = $(this).data('state');
if (state == "0") {
console.log("Closed");
$(this).data('state','1')
} else {
console.log("Opened");
$(this).data('state','0')
}
console.log(state);
});
Further reading on data: .data()
Upvotes: 1
Reputation: 130
Here is a simple toggler in vanilla Javascript. I am not sure want you want to do or what frameworks you use but this is the basic idea
<a href="#" onCLick="toggleSidebar()" data-toggle="sidebar-collapse-button">
<span class="sidebar-text">Collapse</span>
</a>
<div id="myDiv">
Collapsed div
</div>
toggleSidebar = () => {
let element = document.getElementById("myDiv")
if(element.classList.contains("mystyle")){
element.classList.remove("mystyle");
} else element.classList.add("mystyle");
}
Upvotes: 1