Reputation: 1445
I have a basic show and hide toggle of some content which you can see in this JSFiddle. Its working great and does what I need it to do.
However what I am also doing is anchoring to these divs from another page and triggering the answer div to show. I've got this working great with the below code, however I'm struggling to get the text to change to Close answer (which also toggles) when you come from another page, without effecting the manual toggle mentioned above.
I've tried a few things but it wasn't working correctly so I have stripped my code right back so that its hopefully clearer. One of the main problems I was having was only changing the text of that specific div rather than effecting all the divs with the same class on the page.
Code below:
<div id="anchorid1" class="question__wrapper">
<div class="question__item">
<p>
What sort of question am i one?
</p>
<div class="view__answer">
<div class="view__answer-btn">View Answer</div>
</div>
</div>
<div class="answer__wrapper">
<div class="answer__item"> I'm the answer that is hidden</div>
</div>
</div>
<div id="anchorid2" class="question__wrapper">
<div class="question__item">
<p>
What sort of question am i two?
</p>
<div class="view__answer">
<div class="view__answer-btn">View Answer</div>
</div>
</div>
<div class="answer__wrapper">
<div class="answer__item"> I'm the answer that is hidden</div>
</div>
</div>
$(document).ready(function () {
$('.view__answer-btn').on('click', function(e){
$(e.target).parents().next('.answer__wrapper').slideToggle(500, function () {});
$(e.target).toggleClass('open');
if ($(e.target).hasClass( 'open' )) {
$(this).html('Close Answer');
} else {
$(this).html('View Answer');
}
});
});
$(function() {
var anc = window.location.href.split('#')[1];
$('#' + anc + '.question__wrapper').find('.answer__wrapper').show();
});
Upvotes: 1
Views: 56
Reputation: 1609
Maybe this will work! Forgive the silly indentation.
$(function() {
var anc = window.location.href.split('#')[1];
$('#' + anc + '.question__wrapper').find('.answer__wrapper')
.show()
.prev().find('.view__answer-btn')
.addClass('open')
.html('Close Answer');
});
Upvotes: 1