Alessandro Minneci
Alessandro Minneci

Reputation: 301

How can I get a OnClick Event to execute only once?

I've created a <asp:textbox id="TextBoxPassnummer" OnClick="openPopup()" />. When a user clicks on the textbox a popup windows opens via JS:

function openPopup(){
    var myWindow = newwindow = window.open("http://localhost:59969/test.aspx", "Anleitung", "width=200, height=800, toolbars=0, width=950, left=200,top=200,scrollbars=1,resizable=1");
}

The Popup-Windows contains Information on what to enter in the Textbox(TextBoxPassnummer). After the user closed the Popupwindow the method openPopup() shouldn't execute again if he click on the textbox to enter his information. With my Code shown above, the PopupWindows opens everytime.

How do I solve this Problem, any Suggestion? Thanks...

Tried it like this too:

     <% bool windowHasOpened = false;     %>

    if(windowHasOpened == false){


    function openPopup(){


        var myWindow = newwindow = window.open("http://localhost:59969/test.aspx", "Anleitung", "width=200, height=800, toolbars=0, width=950, left=200,top=200,scrollbars=1,resizable=1");
        <%windowHasOpened = true;  %>
    }

Upvotes: 0

Views: 1452

Answers (2)

David Gilbertson
David Gilbertson

Reputation: 4863

You have two options:

Store a variable windowHasOpened, set it to false. Then inside openPopup only continue to open the window if windowHasOpened === false. The first time the function is called, set windowHasOpened = true.

OR

Add the event listener in code like (make sure the code runs after the document has loaded).

document.getElementById("TextBoxPassnummer").addEventListener('click', openPopup);

Then in openPopup, remove the listener like this:

document.getElementById("TextBoxPassnummer").removeEventListener('click', openPopup);

You can use a library like jQuery if you want but it's probably overkill (plain JavaScript ain't that hard).

Upvotes: 0

eisbehr
eisbehr

Reputation: 12452

If you have jQuery available, you can use one. It will bind a one-time event listener, which unbind itself after the first use. When using this, you have to remove the onClick="openPopup()" from the #TextBoxPassnummer element.

function openPopup() {
    alert("popup opend");
}

$("#TextBoxPassnummer").one("click", openPopup);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="TextBoxPassnummer"></textarea>

Upvotes: 3

Related Questions