jQuery click working only when called within a function

Issue

When I use .click() these ways, it doesn’t work:

$(document).ready($("#addPosition").click(function(event) {
  console.log("I'm in HTML .ready()");
  event.preventDefault();
}))
$($("#addPosition").click(function(event) {
  console.log("I'm in HTML $()");
  event.preventDefault();
}))

But if I create a function with this code and call it without parentheses, it works:

function doPosition() {
$("#addPosition").click(function(event) {
  console.log("I'm in function");
  event.preventDefault();
})}
$(doPosition);

This is the HTML part:

<p>Position: <input type='submit' class="btn-sm btn btn-light" id='addPosition' value='+' /></p>

Solution

you have to pass a function in document ready

like this

//$(document).ready(() => {
//  $("#addPosition").click(function(event) {
//    console.log("I'm in HTML .ready()");
//    event.preventDefault();
//  })
//})

//or for short

$(() => {
  $("#addPosition").click(function(event) {
    console.log("I'm in HTML .ready()");
    event.preventDefault();
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="addPosition">CLICK</button>

Answered By – R4ncid

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.