I got this script half-working but need help finishing it off. My jQuery skills are weak at best.
I’m basically creating an interactive flow chart using jQuery to add an expand class. But I went in search of a solution that would be more elegant than 1000 individual addClass scripts.
HTML (I removed excessive stuff):
<div class="x">
<div class="x">Question</div>
<button for="question-1-yes-action" class="x">Yes</button>
<button for="question-1-no-action" class="x">No</button>
</div>
<div class="x">
<div id="question-1-yes-action" class="x">
<div class="x">Answer Yes</div>
</div>
<div id="question-1-no-action" class="x">
<div class="x">Answer No</div>
</div>
</div>
jQuery:
$(function() {
var currentFlow = $("button").attr("for");
$("button").click(function() {
$( "div[ id=" + currentFlow + "]").addClass( "expand" );
});
});
The idea was to identify the container that needed the "expand" class added to it based on the for/ID relationship. At first, I thought it worked! If I click "Yes" the "Answer Yes" will get the "expand" class added to it. However… if I click "No," the "Answer Yes" also gets the "expand" class added to it. So clearly I did something wrong. I just don’t know what it is or if my logic will even succeed.
Any advice would be appreciated.
3
Answers
Your code is nearly there, the issue you have is that you only set
currentFlow
once, when the page loads. It instead needs to be set when theclick
event happens, and it needs to read thefor
from the button which was clicked.In addition, it’s not good practice to create non-standard attributes in your HTML. In this case,
for
. If you want to store custom metadata in your HTML, use adata
attribute instead.Lastly, if you’re going to select an element by its
id
, use anid
selector, not an attribute selector.Here’s a working example with all these amendments incorporated:
Note that I also replaced all your
x
classes with more meaningful names.You will have to fetch the
for
attribute on click of thebutton
. So that the script fetches the attribute of the clicked button.In your case, by default the attribute of the first button is retrieved. I have modified the code as shown below: