Jquery on/off event - javascript

So I was given code that looks like
this.$dropdownButton.off('click.fpmenu').on('click.fpmenu', function (evt) {});
where
this.$dropdownButton
Is a valid button element.
However, at the same place if I search for .fpmenu ($('.fpmenu')), I don't get anything.
Is the on/off events that I am trying to attach to $dropdownButton suppose to be a delegate of the click function of fpmenu? If it can't find fpmenu, would it cause the event not to be attached?

The fpmenu is the namespace of the event handler. This enables jQuery to remove specific event handlers, without changing others.
See Event names and namespaces in jQuery's .on() documentation.
Example - click button and see which event handler is called
var button = $('button');
button.on('click.fpmenu', function () { console.log('fpmenu'); }); // add fpmenu named event
button.on('click.somethingElse', function () { console.log('somethingElse'); }); // add somethingElse named event
button.off('click.fpmenu'); // remove fpmenu named event
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click me</button>

Related

nested ajax call click event or event.default function not working

first i created navigation click event
$('#inner-navigation li a')
.on('click', function (e) {
e.preventDefault();
AjaxNavUrl.checkURL(this.hash);
});
then it conducts ajax call and response html data
based on navigation key
$(".panel-body").html(data);
first ajax click working nicely..
then whithin that responese html data there is rest of click event and ajax call like
$(document.body).on('click', '.page-demos .page-wrapper', function (e) {
e.preventDefault();
and this
$(document.body).on('click', '.button-next', function (e) {
e.preventDefault();
but it seems like click event or e.preventDeafult() function is not working
I got the answer from jQuery doc here is what I learned,
Event Propagation
Understanding how events propagate is an important factor in being able to leverage Event Delegation. Any time one of our anchor tags is clicked, a click event is fired for that anchor, and then bubbles up the DOM tree, triggering each of its parent click event handlers:
<a>
<li>
<ul #list>
<div #container>
<body>
<html>
document root
This means that anytime you click one of our bound anchor tags, you are effectively clicking the entire document body! This is called event bubbling or event propagation.
Since we know how events bubble, we can create a delegated event:
$("#list").on("click", "a", function(event) {
event.preventDefault();
console.log($(this).text());
});
Notice how we have moved the a part from the selector to the second parameter position of the .on() method. This second, selector parameter tells the handler to listen for the specified event, and when it hears it, check to see if the triggering element for that event matches the second parameter. In this case, the triggering event is our anchor tag, which matches that parameter. Since it matches, our anonymous function will execute. We have now attached a single click event listener to our <ul> that will listen for clicks on its descendant anchors, instead of attaching an unknown number of directly bound events to the existing anchor tags only.
linkUsing the Triggering Element
What if we wanted to open the link in a new window if that link is an external one (as denoted here by beginning with "http")?
// Attach a delegated event handler
$("#list").on("click", "a", function(event) {
var elem = $(this);
if (elem.is("[href^='http']")) {
elem.attr("target", "_blank");
}
});
This simply passes the .is() method a selector to see if the href attribute of the element starts with "http". We have also removed the event.preventDefault(); statement as we want the default action to happen (which is to follow the href).
We can actually simplify our code by allowing the selector parameter of .on() do our logic for us:
// Attach a delegated event handler with a more refined selector
$("#list").on( "click", "a[href^='http']", function(event) {
$(this).attr("target", "_blank");
});
The click binding adds an event handler so that your chosen JavaScript function will be invoked when the associated DOM element is clicked. This is most commonly used with elements like button, input, and a, but actually works with any visible DOM element.
Example
<div>
You've clicked <span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
</div>
<script type="text/javascript">
var viewModel = {
numberOfClicks : ko.observable(0),
incrementClickCounter : function() {
var previousCount = this.numberOfClicks();
this.numberOfClicks(previousCount + 1);
}
};
</script>
Each time you click the button, this will invoke incrementClickCounter() on the view model, which in turn changes the view model state, which causes the UI to update.

Remove jQuery delegated event handler on specific object

I've attached delegated event handlers to a number of elements on the page using a single selector. As the events are triggered for individual elements, I'd like to turn off only that element's event handler based on some conditional logic. That means I won't necessarily want to disable the event on the very first click. But I can't figure out how to do it without turning off all of them.
HTML:
<button>One</button>
<button>Two</button>
<button>Three</button>
JS:
$(document).on('click', 'button', function(ev) {
// doesn't work because argument needs to be a string
$(document).off('click', $(ev.target));
// doesn't do what I want b/c turns off events on all buttons, not just this one
$(document).off('click', 'button');
// doesn't work because event is on document, not button
$(ev.target).off('click');
});
jQuery's off documentation says I need to provide a string as the second argument, not a jQuery object ($(ev.target)), but if I provide a string, there's no value that refers only to the item clicked.
From jQuery's off documentation:
To remove specific delegated event handlers, provide a selector
argument. The selector string must exactly match the one passed to
.on() when the event handler was attached. To remove all delegated
events from an element without removing non-delegated events, use the
special value "**".
So how do I turn off a delegated event handler for a specific element?
Here's a JSFiddle of the code above
UPDATE: Added a few examples of options that don't work, based on initial answers provided.
After having read thru on the web, the answer is you can't! You can either remove all or none. A workaround could be something like the following.
$(document).on('click', '.btn', function (ev) {
alert('pressed');
$(this).removeClass("btn");
});
Demo#Fiddle
Sample HTML:
<button class="btn">One</button>
<button class="btn">Two</button>
<button class="btn">Three</button>
In addition to what lshettyl said (the current top post) - an additional work around is to bind a new event listener directly to the element that you're trying to remove the listener and call stopPropagation() therein.
What this will do is prevent the event from traveling up the DOM and reaching the event handler that is initially bound to the document. Also this will allow you to keep some functionality on the button click, such as an alert to the user that this button has already been clicked - or something to that effect.
$(document).on('click', 'button', function(ev) {
// Your logic to occur on button click
// Prevent further click on just this button
$(this).click(function(event) {
event.stopPropagation();
}):
});
Question: Do you have to use the delegated events? LIke LShetty said, it is not possible to remove a delegated event for a single element. You either remove the entire event delegation, or leave it. You could try using a different selector instead like in this example
$('button').on('click', function(ev) {
$('#output').append('Clicked! ');
$(this).off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<button>One</button>
<button>Two</button>
<button>Three</button>
<div id="output"></div>

How to add onclick to Div with a specific class name?

I have a few generated div's on my page listing events on a calender, they all have the same class "fc-event-inner". I would like to add a onclick to these div's but am struggling to get this right.
This is what iv tried, no onclick is added and no errors on page.
$(document).ready(function () {
$('.fc-event-inner').each(
function (element) {
Event.observe("click", element, EventClick);
}
);
function EventClick() {
alert("You clicked an event")
}
});
This is an example of a generated event div:
<div class="fc-event-inner">
<span class="fc-event-title">Requested<br>by Santa</span>
</div>
Use the delegate version of on
$(document).on("click", ".fc-event-inner", function(){
/// do your stuff here
});
This catches the click at the document level then applies the class filter to see if the item clicked is relevant.
Example JSFiddle: http://jsfiddle.net/BkRJ2/
In answer to comment:
You can access the clicked element via this inside the event function. e.g.
$(document).on("click", ".fc-event-inner", function(){
var id = this.id; // Get the DOM element id (if it has one)
var $this = $(this); // Convert DOM element into a jQuery object to do cool stuff
$this.css({'background-color': 'red'}); // e.g. Turn clicked element red
});
*Note: You should never have to run an Each in order to catch events on multiple items that have a common class.
You do not need each() to bind event to elements with specific class, just selector is enough. Use jQuery on() with event delegation it will bind event to those which are generted after the binding code.
$(document).on("click", ".fc-event-inner", function(){
alert("click");
});
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers, jQuery doc.
<div class="fc-event-inner">
<span class="fc-event-title">Requested<br />by Santa</span>
</div>
Your JS:
<script>
$(document).ready(function () {
$('.fc-event-inner').on("click", EventClick);
function EventClick() {
alert("You clicked an event")
}
});
</script>
http://jsfiddle.net/UBhk9/
Some explanation:
Because you are using a class(it may be used multiple times, in contrast to an id) it will work for all the elements with this class name. The .on method will attach the event handler(in this example "click") to the selector(the class .fc-event-inner). If you want to remove events bounds you've to use the .off() method and if you only want to attach the event once you can use the .one() method.

JQuery: on doesn't work properly

I have create dynamic html buttons and I want to set click event to them. Here is my html output and codes :
<td style="width:90px;">
<input type="button" class="btn_Yeni" id="btnYeni"></td>
$(".btn_Yeni").on("click", function () {
alert('asd');
});
$(".btn_Yeni").trigger("click");
Nothing happens after I click the button. Do you have any suggestion?
Since the html buttons are added dynamically, you need to use event delegation to register the event handler like:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on('click', '.btn_Yeni', function(event) {
alert('asd');
});
UPDATE
Since, the buttons are added to a table cells, as visible in your HTML markup, you can do this:
$('#tableID').on('click', '.btn_Yeni', function(event) {
alert('asd');
});
This will attach your event to any button within the #tableID element,
reducing the scope of having to check the whole document element tree and increasing efficiency.
Since you have dynamic buttons you need to use event delegation.
Just using .on() to register event handlers does not make use of event delegation, it has a very specific format for making use of event delegation. The event should be attached to an element which is already present in the page(like the document object in the below case) then the dynamic element selector has to be passed as the second parameter to the on() method
$(document).on("click", ".btn_Yeni", function () {
alert('asd');
});
This is the approach when using dynamic elements.
$("body").on("click",".btn_Yeni", function () {
alert('asd');
});
How is it done:
the handler is not attached to the element itself ( cuz it does not exists when registering) -
so you attach the handler to the body element. and via event bubbling - the delegate element is checked(against) when it reaches the body ( where the handler is actually attached to).
I have put together a fiddle for you to explore dynamic button additions and using the on method for event delegation.
<ul id="btnCollection">
<li>
<input type="button" class="btn_Yeni" value="Your Button" />
</li>
</ul>
var button = $("#btnCollection:last-child").html();
$("#btnCollection").on("click", ".btn_Yeni", function (event) {
alert("Adding another button");
$("#btnCollection").append(button);
});
http://jsfiddle.net/itanex/yak7c/
DEMOenter link description here
$(document).on("click", ".btn_Yeni", function () {
alert('asd');
});
function addrow(){
var $tr = $("#baserow")
var $clone=$tr.clone();
$tr.after($clone);
}

jQuery - multiple event listeners for same button

Say I have an button with an id:
<input id='someButton' />
I want to attach an event listener on this button:
$('#form').on('click', '#someButton', function() {
alert("My listener called");
});
However, unbeknownst to me, someone previously wrote an event listener for this very same button:
$('#form').on('click', '#someButton', function() {
alert("Some other listener called");
});
I encountered some code that effectively does the same thing as above, and it seems like the first listener registered is the one that is used. Am I correct in assuming jQuery will always call the first event listener registered on a specific id (and only that listener)?
Incorrect. jQuery will call ALL event listeners bound to an element, in the order they were bound.
To remove an existing event handler, use .off():
$('#form').off('click'); // click event handler(s) removed
$('#form').off(); // all event handler(s) removed
Be aware that events delegated from ancestor DOM elements won't be removed this way, though.
you could use mousedown:
$('#form').on('mousedown', '#someButton', function() {
alert("My listener called");
});
Hope this help.

Categories

Resources