0

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!

cup_of
  • 5,779
  • 6
  • 37
  • 81

4 Answers4

6

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"); 
}
Ori Drori
  • 166,183
  • 27
  • 198
  • 186
1

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

function conversionOne() {
    alert("something"); 
}
J. Orbe
  • 143
  • 1
  • 5
1
(function conversionOne() {
    alert("something"); 
})();

calling function like this will work onload Change this to

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

More info

Community
  • 1
  • 1
XYZ
  • 4,370
  • 2
  • 13
  • 30
  • thanks for your answer, but Ori Drori posted this right before you. I will give you an upvote though. Thanks – cup_of Oct 24 '16 at 18:05
1

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 **/
}
Ezkin
  • 101
  • 3