Skip to content Skip to sidebar Skip to footer

Why Do I Have To Click This Input Button Twice To Call A Function?

I have a simple input button (not a submit) with an onclick function to show or hide another div. For some reason, I have to click the button twice, once to select it, then a secon

Solution 1:

The first time, isdisplayed is empty, so you jump to the else condition. After the else is done, the style is set to none.

The second call, sees the style as none, and updates it to block, then displays it.

As mentioned below, add the display:none directly on the id to solve the issue

<div id="request_info_form_layer_wrapper" style="display:none;">

Solution 2:

When you click the first time, the onclick event is fired and it goes to the else part, because your style attribute is not set and hence display gives you empty value which is not equal to 'none'. Hence it goes to the else part and assigns the display attribute as 'none'. so

<divid="request_info_form_layer_wrapper"style="display:none"><divid="request_info_form_wrapper"><formname="request_info"id="request_info_form"action="/somepage"method="post"><h3>Name</h3><inputtype="text"id="name_input" /><br /><p>Preferred method of contact</p><h3>Email</h3><inputtype="text"id="email_input" /><br /><br /><h3>Phone</h3><inputtype="text"id="phone_input" /><br /><br /><p>Thanks for your interest in our program. We'll only use your contact information to send additional materials to help you understand the program better.</p><inputtype="submit"id="submit_button"value="SUBMIT" /></form></div>

Put the above and your function should work on the first click.

Solution 3:

Checking if the display style is none will fail. You can fix it by changing your css or by swapping your function around to check if isdisplayed == 'block' rather than isdisplayed == 'none'.

There's a good explanation here: Why does my button need to be clicked twice for the event handler to work the first time, but thereafter just once?

Solution 4:

There is a difference between the element's style attribute and the class property. Meaning yourElement.style is the attribute attached to the element. This is not the same as the styles defined by a css class. You can either add a style attribute to your element:

<divstyle="display:none;">...</div>

or access the underlying css class:

// pure JSdocument.styleSheets[0].cssRules[0]
// but I would highly recommend to use jQuery:
$("#element").css("style", "none");
// and check via var isDisplayed = $("#element").css("style");

Post a Comment for "Why Do I Have To Click This Input Button Twice To Call A Function?"