Reputation: 2279
I am trying to change the ID of an DIV to collapse/expanded it and the approach I have works fine, until I add more than one of them. If I do, and I expand the first image, IsCollapsed will change to false, even though the first second image is still collapsed. This means the button has to be clicked twice. I know this is a logic problem but I can't think of a solution. Does anyone have any ideas?
Here is a link to the actual thing: http://meet-cristian.com/Projects/webfaction.html
<script>
var IsCollapsed = true;
function Expand(ButtonID,CollapsedID,ExpandedID){
if (IsCollapsed == true){
// IsCollapsed = false;
document.getElementById(CollapsedID).id = ExpandedID;
document.getElementById(ButtonID).innerText = '[-] Collapse Image';
} else {
// IsCollapsed = true;
document.getElementById(ExpandedID).id = CollapsedID;
document.getElementById(ButtonID).innerText = '[+] Expand Image';
}
}
</script>
<div class="project-image" id="webfaction-03"></div>
<button type="button" class="expand" id="expand-01" onclick="Expand('expand-01', 'webfaction-03', 'webfaction-03-expanded'); IsCollapsed = !IsCollapsed;">[+] Expand Image</button>
<div class="project-image" id="webfaction-04"></div>
<button type="button" class="expand" id="expand-02" onclick="Expand('expand-02', 'webfaction-04', 'webfaction-04-expanded'); IsCollapsed = !IsCollapsed;">[+] Expand Image</button>
Upvotes: 0
Views: 58
Reputation: 36599
In short, you will have to maintain IsCollapsed
status for all the buttons. It could be done using maintaining a object having button IDs as keys.
var ref = {};
function Expand(ButtonID, CollapsedID, ExpandedID) {
if (typeof ref[ButtonID] === 'undefined') {
ref[ButtonID] = true
}
if (ref[ButtonID] == true) {
ref[ButtonID] = false;
document.getElementById(CollapsedID).id = ExpandedID;
document.getElementById(ButtonID).innerText = '[-] Collapse Image';
} else {
ref[ButtonID] = true;
document.getElementById(ExpandedID).id = CollapsedID;
document.getElementById(ButtonID).innerText = '[+] Expand Image';
}
}
<div class="project-image" id="webfaction-03"></div>
<button type="button" class="expand" id="expand-01" onclick="Expand('expand-01', 'webfaction-03', 'webfaction-03-expanded');">[+] Expand Image</button>
<div class="project-image" id="webfaction-04"></div>
<button type="button" class="expand" id="expand-02" onclick="Expand('expand-02', 'webfaction-04', 'webfaction-04-expanded');">[+] Expand Image</button>
Upvotes: 3