matt_bois
matt_bois

Reputation: 43

javascript function onclick must click twice -_- why so?

I have a page(it is an faq page for a web site) such that when a user click on a div (e.g. #question01) there's a new div that appears below it. Really easy but the thing is that with my function, when you click the first time, nothing appears, then another click and there you go. My #faqAnswer01 has now a "unhide" class which is set to display:block; (.hide = display:none;)

So here are my two question :

1- Why do I have to click twice for my function to get executed?

2- How can I fix my code so that it works after just one click?

HTML CODE

<div id="faqContainer">

   <div id="question01" onclick="showAnswer('faqAnswer01','imgArrow01');">Here's a question?<img src="public/images/gt.png" class="imgArrow" id="imgArrow01"></div>
        <div id="faqAnswer01" class="faqAnswerDiv hide">bla bla bla</div>

   <div id="question02" onclick="showAnswer('faqAnswer02','imgArrow02');">Another question here? <img src="public/images/gt.png" class="imgArrow" id="imgArrow02"></div>
    <div id="faqAnswer02" class="faqAnswerDiv hide">answer here.</div>

</div>

My function:

function showAnswer(idAnswer , idImg) {
    if (document.getElementById(idImg).src == "http://www.cbifinance.org/public/images/gt.png") {
        document.getElementById(idImg).src = "http://www.cbifinance.org/public/images/gt90.png";
        document.getElementById(idAnswer).className = 'faqAnswerDiv unhide';
    } else {
        document.getElementById(idImg).src = "http://www.cbifinance.org/public/images/gt.png";
        document.getElementById(idAnswer).className = 'faqAnswerDiv hide';
    }
}

Upvotes: 1

Views: 1523

Answers (2)

iLikePrograms
iLikePrograms

Reputation: 468

Try changing the image.src to the full URL and it should work.

The reason this would work is that your src is public/images/gt.png even though when it loads the image it finds it correctly, the src is still public/images/gt.png.

So the first time you click, it runs into the else statement, and sets the src to the full absolute url. Then you click again and it changed the src to what you expected the first time. The same goes for the class, its adding the hide class to the image, which it already has but the second time it adds show. The code is functioning correctly, the if statement is just wrong.

Upvotes: 3

Hanky Panky
Hanky Panky

Reputation: 46900

Because first time the src is not what your if is checking for

src="public/images/gt.png"

VS

src="http://www.cbifinance.org/public/images/gt.png"

Then on the first click you set it to that. And then for the second time your if condition is met.

Upvotes: 2

Related Questions