cup_of
cup_of

Reputation: 6697

Trigger function only on "onclick"

Hello I need a function to run when an a tag is clicked. I am using the onclick="" but it seems that the function runs on page load, instead of waiting to run when the a tag is clicked on. How do I make it so the function only runs when the a tag is clicked?

Here is my code.

HTML:

<a class="req_btn" onclick="conversionOne()">text</a>

<script type='text/javascript'>
    (function conversionOne() {
        alert("something"); 
    })();
</script>

Thanks!

Upvotes: 0

Views: 199

Answers (4)

XYZ
XYZ

Reputation: 4480

(function conversionOne() {
    alert("something"); 
})();

calling function like this will work onload Change this to

 function conversionOne() {
    alert("something"); 
};

More info

Upvotes: 1

Ezkin
Ezkin

Reputation: 101

Doing this

(function(){
    /** code **/
})();

Means the code will be executed imediatelly. in your case you want to create a function so you need this :

function conversionOne() {
    /** code **/
}

or

var conversionOne = function () {
    /** code **/
}

Upvotes: 1

J. Orbe
J. Orbe

Reputation: 153

You are using a self-executing function. Declare the function in the global scope without executing it.

function conversionOne() {
    alert("something"); 
}

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 193258

You are invoking the function when the script loads using an IIFE. Instead of this:

(function conversionOne() {
    alert("something"); 
})();

Do this:

function conversionOne() {
    alert("something"); 
}

Upvotes: 6

Related Questions