Weird Behaviour With on Click Event Binding; Event Not Firing

Strange behaviour using .on() for click event - Fired twice

$(document).on("click", ".jumpTo .number", function(){
console.log("Jump");
});

In this case the click handler is set on the document object. So whenever you click somewhere on the page, it will fire and look for a ".jumpTo .number" element inside it. If it finds it, it will check if the click was on it and your function will execute.

$(".jumpTo").on("click", ".number", function(){
console.log("Jump");
});

Here the click handler will be on .jumpTo

As Al.G said probably this code gets executed multiple times, so you actually add that handler multiple times, hence the double firing.
One way to solve it is to do something like this:

$(".jumpTo").unbind("click").on("click"...

Another is to change your code to make sure the .on() call doesn't get executed twice.

Why Angular2 (click) event is not firing on a <div>?

Your code snippet looks all good!

The issue is in your CSS styles. Your <div> probably either inherits a different position value or simply - goes behind another element which element blocks your <div> (does not allow it to be clicked).

By changing the position to relative it works, most probably because this position enables z-index and moves your <div> on top to the other element that's blocking it.

This should be enough for you to figure it out. But if you want more detailed answer - please share your CSS too.

jQuery click event weird behavior

The reason is that the Yes and No button displayed on the alert for your different buttons are the same every time.

So everytime the window pops up you bind a new click function to your yes button, and when you finally click it all the bound functions will trigger.

  //This code is called everytime a button is clicked, so your Yes and No
//Button will execute as many callbacks when clicked.
$("[data-alert=1]").click(function() {
fnc(clicked);
alert.Close();
});
$("[data-alert=0]").click(function() {
alert.Close();
});

As for the solution, just bind the click event to Yes or No once (not every time a button is clicked), store the last button clicked in a global variable (or whatever property or whatever element) and retrieve it in your callback function.

$(function() {
var btn;
// Custom callback function
function callback(clicked) {
$("#result").append("<br/>").append(clicked);
}
// Custom alert function
var alert = {
Check: function(fnc, clicked) {
$("#alert").show();
$("#alert").attr("last-clicked", clicked);
},
Close: function() {
$("#alert").hide();
return false;
}
};

//Only called once
$("[data-alert=1]").click(function() {
callback($("#alert").attr("last-clicked"));
alert.Close();
});
$("[data-alert=0]").click(function() {
alert.Close();
});

// Custom button function
$("[data-mod]").click(function() {
btn = $(this);
return alert.Check(callback, btn.data("mod"));
})
});

An alternative is to use .off to remove all previous click bindings to your button, like such:

  $("[data-alert=1]").off("click").click(function() {
fnc(clicked);
alert.Close();
});

But the downside is that it will remove all callbacks to the click events, even those that another part of the code could have put there. That's why maybe you're better off doing something like:

  $(document).on("click", "[data-alert=1]", function(...) {...});

Call this once and this will work even for dynamically created alert windows after this call.

Click event doesn't work on dynamically generated elements

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Source

Here's what you're looking for:

var counter = 0;
$("button").click(function() { $("h2").append("<p class='test'>click me " + (++counter) + "</p>")});
// With on():
$("h2").on("click", "p.test", function(){ alert($(this).text());});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><h2></h2><button>generate new element</button>

Click event not fired when change event fired simultaneously

The issue has to do with the hello.foo:

Template.hello.foo = function() {
return Session.get("foo");
};

and the fact that the value of foo is used to reactively populate the text input. If you remove the hello.foo function everything works as expected. When the user clicks the button, the change event fires which sets the "foo" session variable which in turn causes the template to re-render. I think the rendering process clears the remaining event queue, so the click handler never fires.

There are a couple of ways you can fix this. An easy (but crude) way is just to delay setting the session variable in the change event handler. For example:

Meteor.setTimeout(function(){Session.set("foo", bar);}, 100);

Obviously you would need to choose an appropriate delay and that may be browser/data dependent. Alternatively, you can just put the text input in its own template. For example:

<template name="hello">
{{> helloText}}
<input type="button" class="buttonid" value="{{something}}" />
</template>

<template name="helloText">
<input type="text" class="textid" value="{{foo}}"/>
</template>

After binding the events properly to this new template, you will find that helloText will be rendered separately from hello and thus your events will be preserved.

strange behaviour of jquery 'click' event

.click and .bind don't have event delegation. You're executing them before the elements are loaded into the DOM. Either move your .click to below the anchors or add it inside a DOM ready event:

$(document).ready(function() {
$('a').click(function(){
//do something..
});
});

OR

$(function() {
$('a').click(function(){
//do something..
});
});

Both of the above have the same result, use whichever you find more readable/maintainable.

.live works right now as it uses event delegation, which is, per a layman's view, similar to

$(document).on('click', 'a', function(){
//do something..
});

Note that .live is deprecated in jQuery 1.7+ so you should prefer the .on method for event delegation. Also note that .on only has the event delegation effect when bound to a parent element passing a descendants selector parameter.

Here's a Fiddle with $(document).ready().

edit: As per OP's comment, since you're adding anchor tags dynamically, you have 2 options: event delegation (recommended) or re-binding the events every time you add new content.

In jQuery 1.7+, you should use .on() for event delegation:

$('#AnchorsDivID').on('click', 'a', function(){
//do something..
});

Here's a full featured live demo with .on event delegation and Ajax:

JSFiddle

In jQuery <=1.6.4, you will have to use .delegate() or .live(). Which one provides better usability and performance for each version is shown at the .live() jQuery API page.

For jQuery >=1.4.3 <1.7:

$('#AnchorsDivID').delegate('a', 'click', function(){
//do something..
});

Why doesn't click event always fire?

I recently came across this again, and fortunately have managed to isolate the problem and work around it.

It was actually due to something being registered in the mousedown event, which was moving the DOM element svg:circle to the top based on a z-order. It does this by taking it out the DOM and re-inserting it at the appropriate place.

This produces something that flows like this:

  • mouseenter
  • mousedown

    • (move DOM element but keep same event wrapper)
    • mouseup

The problem is, as far as the browser is concerned the mousedown and mouseup occurred almost on different elements in the DOM, moving it has messed up the event model.

Therefore in my case I've applied a fix by firing the click event manually on mouseup if the original mousedown occured within the same element.

Strange behaviour binding event to element jQuery

What would cause it not to work is if the element is not yet available (the DOM not being ready) when you try to add the listener. jQuery offers a convenient method to make sure the DOM is fully parsed and all elements are accessible called $(document).ready():

$(document).ready(function() {
$('#js-course-applications').on('change', function(){
alert("Wey!"); //doesn't fire
});
})

The event delegation thing works because here the element only needs to be accessible when the event occurs. It is typically used to add listeners for events triggered by elements that get added to the page dynamically by Javascript.

Please note that event delegation only works on events that bubble. (For example blur and focus do not bubble by default.)

Are you sure there's only one element with that id? Otherwise selecting it using the id will always only find the first occurrence. You need to make sure each id value in your whole document is unique.



Related Topics



Leave a reply



Submit