I have a following Javascript function for expand collapse of the content:
function showAns(inp){
var hide="#hideAns"+inp;
var show="#showAns"+inp;
var ansdiv ="#ans"+inp;
$(hide).click(function(){
$(ansdiv).hide(500);
$(hide).hide();
$(show).show();
});
$(show).click(function(){
$(ansdiv).show(500);
$(hide).show();
$(show).hide();
});
}
This function is called from following piece of generated HTML code:
<div class="qbox">
<span class="qclass">Q. No.1) This is test question 112
<img id ="showAns1" class="icons" src="img/expand.png" onclick="javascript:showAns(1)" alt="show" width="20" height="20" style="float:right; cursor:pointer;">
<img id="hideAns1" class="icons" src="img/collapse.png" onclick="javascript:showAns(1)" alt="hide" width="20" height="20" style="float:right; display:none; cursor:pointer;">
</span>
<img alt="image" class="img" src="img/sample.jpg">
<hr />
<span id="ans1">This is test answer 112</span>
</div>
<br>
<div class="qbox">
<span class="qclass">Q. No.2) This is test question 110
<img id ="showAns2" class="icons" src="img/expand.png" onclick="javascript:showAns(2)" alt="show" width="20" height="20" style="float:right; cursor:pointer;">
<img id="hideAns2" class="icons" src="img/collapse.png" onclick="javascript:showAns(2)" alt="hide" width="20" height="20" style="float:right; display:none; cursor:pointer;">
</span>
<hr />
<span id="ans2">This is test answer 110</span>
</div>
<br>
problem here is that I have to click thrice the image first time then only expand collapse works fine. Once I click the image twice after that expand collapse works fine. I don't know what I am doing wrong, any help will be highly appreciated. Thank you.
showAns()You are only binding events not executing them$(document).ready()not as anonClickevent. It works the second time because after you click it the first time, it has bound the events.