Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

button click jquery not working

Should be a really simple answer but I can't figure it out right now. I have this button:

<button id="logout" type="button">Logout</button>

And it's supposed to run this jQuery code within script tags at the bottom of the body:

$("#logout").addEventListener("click", function () {
    alert('Button Clicked');
});

However, no alert pops up. I don't get it. Thanks in advance.

like image 519
Matt Avatar asked May 16 '26 01:05

Matt


2 Answers

addEventListener is a method of DOM element not of jQuery object which is an array-like structure that contains all the selected DOM elements

To attach event using jQuery, use .on => Attach an event handler function for one or more events to the selected elements

Try this:

$("#logout").on("click", function() {
  alert('Button Clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="logout" type="button">Logout</button>

Using JS:

document.getElementById("logout").addEventListener("click", function() {
  alert('Button Clicked');
});
<button id="logout" type="button">Logout</button>

Edit: You can get first DOM element from array-like object returned by jQuery selector using $(SELECTOR)[0] or $(SELECTOR).get(0)

like image 64
Rayon Avatar answered May 17 '26 13:05

Rayon


addEventListener() method registers the specified listener on the EventTarget.

If you really want to use addEventListener then write the following code:

var el = document.getElementById("logout");
el.addEventListener("click", function () {
     alert('Button Clicked');
}, false);

Otherwise do it with jquery

$(document).on("click", "#logout", function () {
    alert('Button Clicked');
});

OR

$("#logout").on("click", function () {
        alert('Button Clicked');
    });
like image 23
Manish Jangir Avatar answered May 17 '26 14:05

Manish Jangir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!