Why I cannot change button event with JQuery .click() function? - javascript

Say I have a button whose id is "btn" and I add an event to the button as:
$(document).ready(function() {
$("#btn").click(function(){
$("#label1").html((new Date()).getSeconds());
$("#btn").click(function () {});
};
})
where #label1 is a label tap supposed to show the current second.
I wish by click the button at the first time, current second will shown in the label1. And for following click on this button, nothing happen. But what I got is every time the button is clicked, new current second is shown in label1. What's wrong?

Use one() to bind event
$("#btn").one('click', function(){
$("#label1").html((new Date()).getSeconds());
});
Note that $("#btn").click(function () {}); does not unbind the event. It binds click event on that element one more time, so next time when the button is clicked two event handlers will be called one to update the html and other empty function that does nothing.
To unbind the event, off() can be used, but in this case one() is preferred.
$("#btn").on('click', function () {
$("#label1").html((new Date()).getSeconds());
$(this).off('click');
});

You can simply use .one().
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
$(document).ready(function() {
$("#btn").one('click', function(){
$("#label1").html((new Date()).getSeconds());
});
})
At-present you are binding another click handler using $("#btn").click(function () {});

Hello you can remove the click Listener the following way.
$(document).ready(function() {
$("#btn").click(function(){
$("#label1").html((new Date()).getSeconds());
$('#btn').off('click');
});
})

Related

Remove and add a class in a button jquery, can't make it work

I have a button on the page with a class next-main-button.
On page load, a modal is displayed and I have a button with class look-task-again. If I click on it I want to remove next-main-button class from next button and add this class next-task-error
Here is the next button:
<button type="button" class="btn btn-default next-main-button" id="next-button" >Next</button>
This event is executed when the modal button is clicked, here next-main-button is removed and next-task-error is added.
$(".look-task-again").off("click").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button");
$("#next-button").addClass("next-task-error");
});
If I inspect element the class is changed but if I click in the next button, the event with removed class is executed:
$('.next-main-button').off("click").on("click", function(){
nextButtonClick();
});
Not this:
$(".next-task-error").off("click").on("click", function(){
errorButtonClick();
});
I tried to use unbind method and to bind the button again, I did it like this :
$("#next-button").removeClass("next-main-button").unbind( "click" );
$("#next-button").addClass("next-task-error").bind( "click" );
In this way the next button is deactivated, nothing happens! Can somebody help me, please?
The selector that you used to get the element to bind the click handler on (i.e. .next-task-error or .next-main-button) is only executed once, and delivers one or more elements.
Then you bind a click handler to those element(s), but that binding has no knowledge of the selector you used to get those elements. The binding is done on the elements directly, and never again is their class verified (or whatever other selector you could have used).
To make it more dynamic, you could either (1) use event delegation, or (2) test the clicked element's class at the moment of the event, or (3) change the handler when the condition changes.
1. Event delegation:
$(document).on("click", ".next-main-button", function(){
nextButtonClick();
});
$(document).on("click", ".next-task-error", function(){
errorButtonClick();
});
Shorter version of the same, using chaining:
$(document).on("click", ".next-main-button", nextButtonClick)
.on("click", ".next-task-error", errorButtonClick);
2. Test class within the handler:
$('#next-button').on("click", function(){
if($(this).is('.next-main-button')) {
nextButtonClick();
} else {
errorButtonClick();
}
});
3. Alter handler when status changes
This is like you attempted to do: re-bind the correct handler when the condition changes:
// set initial click handler
$('#next-button').on("click", function(){
nextButtonClick();
});
$(".look-task-again").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button");
$("#next-button").addClass("next-task-error");
// replace click handler:
$('#next-button').off("click").on("click", function(){
errorButtonClick();
});
});
Shorter version, using chaining:
// set initial click handler
$('#next-button').on("click", nextButtonClick);
$(".look-task-again").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button")
.addClass("next-task-error")
.off("click")
.on("click", errorButtonClick);
});

How to run a certain method every time a button is clicked with changing buttons in javascript?

I want to be able to run the content() method every time a button is clicked with the id of the button as the parameter. This method removes the old buttons and displays new buttons.
This is the code I have so far:
do {
selection = $('button').click(function() {return this.id;});
content(selection);
} while(selection !== "end");
What you need is a click event handler where you call the content method
$('button').click(function () {
content(this.id);
});
If you want to execute the same method again when the replaced button is clicked then you need to use event delegation
$(document).on('click', 'button', function () {
content(this.id);
});

How to invoke inline click handler immediately using JQuery?

I write a click hander like this;
$("#button1").click(function(evntData)
{
alert("button1 clicked.");
});
to invoke it immediately I do like this;
$("#button1").click(function(evntData)
{
alert("button1 clicked.");
}(null));
in this way it is called on start up and work fine. but later when button is clicked this event handler is not called. How can I do it? Thanks
You should trigger click event:
$("#button1").click(function(evntData) {
alert("button1 clicked.");
}).trigger('click');
Another way is to actually call the function and provide the same function reference as event handler:
function onClick(evntData) {
alert("button1 clicked.");
}
$("#button1").click(onClick);
onClick(); // you can pass object parameter evntData if needed
You can use .click() after binding the click event to trigger click :
$("#button1").click(function(evntData)
{
alert("button1 clicked.");
}).click(); //or .trigger('click')

jQuery bind click firing immediately

I have a drop down menu, and clicking the icon should add the class "Open" to its parent, and then clicking the menu anywhere should close it. But the function inside the bind fires when the icon is clicked. The effect being it adds the class Open, and then removes it straight away.
This is probably a simple issue, but I cannot seem to work out why the 'click' event fires straight away!?
This question may be similar but can't still can't work it out: jQuery bind event firing the event
$(function () {
$(".ui-dropdown-action").bind("click", function () {
$(this).parent()
.addClass("Open")
.bind("click", function () {
$(this).removeClass("Open");
});
});
});
I think you might have a problem with the click event bubbling up the DOM tree. Which is why click is also being fired on the parent.
if you pass in the event object as an argument for the first bind and call event.stopPropagation() as follows
$(function () {
$(".ui-dropdown-action").bind("click", function (event) {
event.stopPropagation();
$(this).parent()
.addClass("Open")
.bind("click", function () {
$(this).removeClass("Open");
});
});
});
should fix your issue.
You can pass the event argument and stop the bubbling of the event .. Try this
$(function () {
$(".ui-dropdown-action").bind("click", function () {
$(this).parent()
.addClass("Open")
.unbind().bind("click", function (e) {
$(this).removeClass("Open");
e.stopPropagation();
});
});
});
This will make sure the parent event will not fire when the icon is clicked..
Also every single time you click the icon the event for the parent is bound again which will create multiple click events .. Need to make sure you unbind and bind them again to avoid that..
It is firing right away because the click event is bubbling to the parent and then firing that selector. To fix this you could use a setTimeout() around the 2nd bind.
$(function () {
$(".ui-dropdown-action").bind("click", function () {
var parent = $(this).parent();
parent.addClass("Open");
setTimeout(function() {
parent.bind("click", function () {
$(this).removeClass("Open");
});
}, 0);
});
});
Another option would be to to a stopPropagation() on the event on your first bind, though that would prevent any other handlers from triggering on that event.
In my case, when I use something like this
$("#modal .button")[0].click(() => console.log('test'))
its doesnt work and seems like click firing immediately
Solution for me was:
const button = $("#modal .button")[0];
$(button).click(() => console.log('test'));

overriding previously-bound click events

When I use this code with an element whose id is "foobar":
$("#foobar").click(function () { alert("first"); });
$("#foobar").click(function () { alert("second"); });
I get two alerts: "first" and "second" second.
How do I specify a click event that also clears out any previous click events attached to the element? I want the last $("#foobar").click(...) to erase any previously bound events.
You can unbind the events already attached to that element, and then attach the second event handler, so it will be the only one (note the unbind method).
$("#foobar").unbind("click").click(function() { alert("second"); });
$("#foobar").click(function () { alert("first"); });
$("#foobar").unbind('click').click(function () { alert("second"); });
Notice the unbind() method. It does exactly what it sounds like.

Categories