I was studying a colleague's code and I noticed an event that I haven't used before and I can't find it online either.
This is the code:
$('body').on('items-set', function(){
bindDropdown();
console.log('must bind event')
})
That console log never runs, I don't see the message in the console. What does 'items-set' mean?
It's most likely a custom event, triggered by the following code.
$('body').trigger('items-set');
'items-set' is not a standard javascript/jquery event. Most likely it is either a custom event created by the user or of some library that is included in the page.
And the obvious reason I can think of for the console.log not being called is that the event is not triggered..
Also, if you cant find the custom event declaration anywhere, could be a 'stray' segment of code that the developer forgot to delete and which doesn't really do anything?
correct is 3 parameters of $.on method
$('body').on(EVENT_HERE, SELECTOR_HERE, function(){
bindDropdown();
console.log('must bind event')
})
Related
I need to change behavior of jQuery library (date range picker), it have code like this:
box.find('.month').off("change").change(function(evt) {
dateChanged($(this));
});
box.find('.year').off("change").change(function(evt) {
dateChanged($(this));
});
Those are two select elements. It don't return false and functions inside handler don't access the event. But for some reason my events that use delegation doesn't work. They are ignored.
$picker.on('change', 'select', function() {
console.log('CHANGE');
});
The console log is not executing, but if I remove previous lines from the library, my event delegation code works fine.
NOTE: $picker is object in my code that is parent of box element. But I also have event added on $(document) that is also not working.
First time I see something like this. Adding event directly to element, prevents event propagation. Can someone explain what is happening here? Is this documented anywhere?
This happens in Firefox and Chrome.
If someone need simple example, I can create one. But thought that this is self explanatory.
EDIT: I've created a simple reproduction and it works fine. I have complex application with a lot of files (R Shiny Application), but I don't see any change events in dev tools. Are there any way of making the event not propagate? Maybe using event capturing. What should I search for in order to find the code that is preventing the events from propagating?
I just got through figuring out that I need to watch out for duplicate event handlers in jquery if I'm dynamically assigning them multiple times as described here: http://www.parallaxinfotech.com/blog/preventing-duplicate-jquery-click-events
Do I need to watch out for this or handle it somehow if I'm declaring a function dynamically within another function multiple times? How does JavaScript really handle this? Does it only use the last function that was called or does it only instantiate a function once at load time? From what I can tell it's not running the function multiple times.
$(document).on("click",".button",function() {
function alertThem()
{
alert('Clicked!');
}
alertThem();
});
JavaScript will remember every function you're assigning it.
$('button').click(function(){
alert('hi')
})
$('button').click(function(){
alert('hi')
})
The code above will alert "hi" twice. If you're assign new function and you want to clear the old one, you can do unbind().click(). what it will do is it will unbind all events, or you can do unbind('click') which will unbind just the click. see https://jsfiddle.net/rznbtc1p/
$('button').click(function(){
alert('hi')
})
$('button').unbind().click(function(){
alert('hi')
})
The link you provided does not work (gives me timeout) so I hope I understood what you asked.
About what happens there:
In your script you created a closure and bound it to a click event. Each time you click on the element with class button, the anonymous function is triggered. Each time is triggered it defines function alertThem(), and calls it. Only once defines it, only once calls it. The scope of that function is its parent, the closure. That function is not defined outside that scope, so no need to worry about double definition.
Side note here: Personally as a rule of thumb don't think is a good idea to define functions like this, but if it suits your project... go for it.
Now about duplication. Since I cannot see the link, I think you are referring to double event binding.
In js can bind any number of events to the same element. You can for example bind on click something that says "Hi, you clicked me", then bind also on click something that says "Hi, you received a message before saying you clicked me". When you click that element, you will see both messages.
This can actually become a problem. You have 3 options:
Be really careful how you bind events
Keep tracking of what you bound
Check if events are already bound (although that is a bit unreliable). You can check how here: jQuery find events handlers registered with an object
In your code snippet, you aren't creating duplicate event handlers.
What is happening in your snippet is that you are creating a new function alertThem within the scope of your click handler function and then executing it in the line below.
I'm using Chrome DevTools to debug JavaScript. In my script I bound a click event to an element using the jQuery bind() method.
How to check if that event was fired or not?
Edit
Sorry because I wasn't so specific, I know that I can use console.log() or set a breakpoint inside the event listener body. What I'm talking about here is an out of box feature of the Chrome DevTools that allows you to check that without using the console, e.g a tab that contains all the events that were fired with related information.
Regarding Chrome, checkout the monitorEvents() via the command line API.
Open the console via Menu > Tools > JavaScript Console.
Enter monitorEvents(window);
View the console flooded with events
...
mousemove MouseEvent {dataTransfer: ...}
mouseout MouseEvent {dataTransfer: ...}
mouseover MouseEvent {dataTransfer: ...}
change Event {clipboardData: ...}
...
There are other examples in the documentation. I'm guessing this feature was added after the previous answer.
Use console.log() for more user friendly check (console must be opened of course to see the result):
$("#myElement").bind("click", function() {
console.log("Fired!");
});
Or you can alert it, which is much more anoying tho:
$("#myElement").bind("click", function() {
alert("Fired!");
});
You can try below code to check if event fire or not.
var eventFire = false;
$("button").on("click", function() {
eventFire = true;
if(eventFire){
alert('Event Fired')
}
});
I normally use an alert (because we develop on Rails -- console is unreliable):
$(document).on("event", "#element", function() {
alert("event");
});
The bottom line is you're going to have to trigger some "visible" thing to see if the event fired. If it doesn't, you'll either not be binding to the correct element, or your event won't be firing
Hope this helps!
Using jQuery Try the following:
$("#el").on("click", function() {
console.log("Fired!");
});
You can then see if the event was fired or not. So basically Just add a log in your function of where the event is triggering should do the trick.
You can put an "alert('message');" in your event handler and see a popup each time the handler fires.
Or you can put a "console.log('message');" in your event handler and review the log to see all the times that the event fired.
Or you can put "debugger" in your event handler and step through your code as it executes in the chrome debugger.
There is also a way to dynamically find an event handler and insert a debugger break point in your code using the chrome dev tools elements panel.
Is it possible to have multiple click events for the same element? I have tried to simply have it like so:
$('#templates').click(function(e) {
do something..
});
$('#templates').click(function(e) {
do something else also..
});
Yet only the second event fires. I cannot find any decent answers explaining how to do this for a singular element in an on-click?
Note: the first click event calls server-side and loads a new PHP template (this may have an effect on what I can use in the second call I guess, as individually both clicks work but the server call does not work if I try a second click for the same element)
$('#templates').click(function(e) {
functionOne();
functionTwo();
});
function functionOne(){
}
function functionTwo(){
}
perhaps?
Please check this fiddle:
http://jsfiddle.net/DqSSd/
As you can see it should work well.
So please provide more information, and it would be better, if you provide JS fiddle as well.
Because so far the problem might be in:
second event is fired before first event returns the result
first event returns error from the server
some of events contains syntax error
etc
You may check something of those with investigation of NET calls to server (with Firebug or Chrome Developer toolbar).
Also for testing purposes you can type in console $('#templates').data("events"), so you will be able to see all events and handlers for particular element.
Here's a snippet of my code:
$(".item").click(function () {
alert("clicked!");
});
And I have (hypothetically; in actuality it's far more complicated) the following on my page:
<img src="1.jpg" />
However, when I click the image, I do not get an alert.
What is my mistake?
Is your selector actually matching anything? Try using the jQuery debug plugin (http://jquery.glyphix.com/) and doing this:
$(".item").debug().click(function() {
alert("clicked!");
});
.debug() will log whatever is matched to the Firebug console (you are using firebug, right? :-) ) without "breaking the chain" so you can use it inline like this.
If that turns out correctly, there may be some issue with the browser navigating to "#" before it can show your alert. Try using the .preventDefault() method on the event object to prevent this behavior:
$(".item").click(function(evt) {
evt.preventDefault();
alert("clicked!");
});
First question - are you adding the element to be clicked dynamically? If it is,
you should use the live event since that will take care dynamically created elements.
http://docs.jquery.com/Events/live#typefn
Use bind.
$(".item").bind("click", function(e) { ... });
modifying the selector?
$(".item > img")
I had this problem recently after adding a context menu jquery plugin. The pluging was binding to the click event of the body and then unbinding click event - it seemed to remove all bindings to click event for all elements. Maybe a suggestion to turn off plugins or check you're not unbinding click for a parent element yourself.
The code you have posted is correct, so I suspect there's something else going on that you haven't considered.
Firstly, if there was an error somewhere (even not in that exact bit of code) that might cause it to stop working. Put an alert just after this line to check that it runs.
Check that no other elements are catching the event and stopping it from propagating. This has bitten me before in the past... If there's anything else handling a click which has stopPropagation() or return false in it, that might be the problem.
One thing I've found (though only with links going elsewhere) is that adding return false; in may help, if it's just firing the anchor off instead of evaluating the alert. I can't really say why this would be the case, but that's a solution I found to a similar problem recently.