0

I have a div class in my html file named 'btn'. In my Javascript file I use jquery to detect clicks on that btn. When the jquery function to detect clicks is written in the global scope,the function doesn't work,but when I put it inside another function and call it using developer tool console,it works. Can somebody help me out with this please?

Code for reference-

$(".btn").click(function() {
   console.log('Clicked');
}

This below code works-

function clickDetection(){
   $(".btn").click(function() {
   console.log('Clicked');
   }
}
3
  • 5
    It sounds like you've forgotten to use a document.ready handler in the first example, and the second works because you call clickDetection() after the DOM has loaded (even though that example is missing a )) Commented Feb 26, 2020 at 10:14
  • 1
    $(document).on('click', '.btn', function() { console.log('Clicked'); } try this.. Commented Feb 26, 2020 at 10:20
  • Thankyou. It's working now. Commented Feb 26, 2020 at 10:31

1 Answer 1

2

Add the function in the document.ready function of jquery. This adds the eventlistener to the button after the page is loaded. Example:

$(document).ready(() => {
  $('.test-button').on('click', () => {
    console.log('Clicked');
  });
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>click button demo</title>
</head>

<body>
    <button class="test-button">Click me</button>
</body>

</html>

To quote jQuery docs:

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated event handlers to attach event handlers.

See more at: https://api.jquery.com/on/

Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou very much. Can you please explain why it does not work when written without document ready? For example if I type in alert('Hi'); it instantly pops up after loading the page,but in this case it doesnot read the onclick jquery.
@SushmitChakraborty You were trying to add an event listener to an object that was not yet present in the DOM, see the quote at the bottom of the answer for the explanation of jQyery. The second case works because you probably run that function after the element was added to the DOM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.