jQuery trigger events stack over time - javascript

I have a generall question about define customer events and trigger then:
jQuery(document).on('btn.hover', function () {
jQuery('.orange_bubble').hover(function () {
jQuery(this).addClass('hover');
}, function () {
jQuery(this).removeClass('hover');
});
});
Now i can call the trigger event to fire this event one time.
jQuery(document).trigger('btn.hover');
If i generate content over ajax or via js i need to get rebind the event on new elements:
so i trigger it again:
$.ajax{
bla
success: {
jQuery(document).trigger('btn.hover');
}
}
How can i do this without stacking the events. I have this problem right now.
I am useing some customer events and sometimes they have to reinitate on all elements, but just onetime and not stacking.
What is the bestpractice to firing events once time ?
If they are set to some elements in the dom?
Thx for help

.hover() is a shortcut for using mouseenter and mouseleave events, but one drawback is it cannot be used for registering delegated handlers, so instead of using .hover() use the events directly.
So try
jQuery(document).on({
mouseenter: function () {
jQuery(this).addClass('hover');
},
mouseleave: function () {
jQuery(this).removeClass('hover');
}
}, '.orange_bubble')

First of all you don't have to rebind the event to newly added elements if you use event delegation.
From JQuery page
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
you could use something like:
$( "//container of .orange_bubble elements" ).on( "hover", ".orange_bubble", function() {
//your content
});
This will also prevent you from "stacking" the events

Related

js stop click function subsequent execution after call back in ajax of itself

On the first click myClick() has been called again in itself of myLoad() then at the second click, this myClick() will execute two times
=> The following causes two subsequent execution of
click event of #myBtn by one click
How to avoid or stop this? Please anybody suggest me new logical method or which way to stop this.
$(function() {
myLoad()
})
function myClick() {
$("#myBtn").click(function() {
myLoad(); //load new every click
});
}
function myLoad() {
$("#myCnt").load('ajax.php', {
"data": "some"
}, function() {
myClick() //to live the click event works after ajax load
})
}
Problem with your implementation is that in each call to myClick() an new event handler is attached to button.
You can use .off() to remove existing event handler attached using .on().
function myClick(){
$("#myBtn").off('click').on('click', function(){
myLoad();//load new every click
});
}
A better approach would be to use .on() method with Event Delegation approach, when generating elements dynamically.
General Syntax
$(document).on('event','selector',callback_function)
In place of document you should use closest static container.
The 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, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
A good read Direct and delegated events
Modify you code as
$(function() {
myLoad();
$(document).on("click", "#myBtn", function() {
myLoad(); //load new every click
});
})
function myLoad() {
$("#myCnt").load('ajax.php', { "data": "some"}, function() {
//No need to call my click
})
}
Issues is in the flow of your code
First time when you call myClick() it binds the click event with #myBtn,
On second time it binds that event again , so it will be called twice , remove that event binding from there,
Or else $("#myBtn").click will be bind each time you call the myClick function.
As solution please try this code :
$(function(){
myLoad()
})
$("body").on( "click" , "#myBtn" , function(){
myLoad();//load new every click
});
function myLoad(){
$("#myCnt").load('ajax.php', {"data":"some"}, function(){
$("#myBtn").trigger("click");
})
}

.on() event handler inside ajaxComplete()?

I have this:
$('.task').on('click', function()
{
task_id = $(this).data('id');
console.log('Task id: ' + task_id);
});
But this doesn't work as it should when the content is reloaded via ajax. task_id value stays the same even after clicking different elements after the ajax reload. Apparently I have to bind it to the body first.
This is how it is in my code right now though (it works as expected):
$(document).ajaxComplete(function(event, xhr, settings) {
$('.task').on('click', function()
{
task_id = $(this).data('id');
console.log('Task id: ' + task_id);
});
});
But I've been told this duplicates/doubles the trigger for the .on('click') event? Is this true? How do I know then when to bind to the direct selector or bind to the document.body instead?
Which would be more efficient? Binding to body or putting the event delegation inside ajaxComplete()?
I'm a little confused too since I have other event handlers inside the same .js file but outside ajaxComplete() that seem to work just fine even after an ajax reload?
You should use .on() method with Event Delegation approach, when generating elements dynamically(content is updated via $.ajax())/manipulating selectors. then you won't need to attach event handler in ajaxComplete()
General Syntax
$(document).on('event','selector',callback_function)
Example
$(document).on('click', '.task', function(){
//Rest of your code
});
In place of document you should use closest static container.
The 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, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Document click fire after control click

I have created a common click function in jquery which fires every time when clicked any where on document. If control has click event then that event fires first and document click fires after that but i want to fire document click event before control click event. please suggest how to fix this.
Two options for you:
You can do that on modern browsers by using the capturing phase of an event rather than the bubbling phase. This diagram from the DOM events specification helps with understanding the various phases of an event:
IE doesn't support event capture until IE9 in standards mode (IE8 and earlier simply do not have it).
jQuery doesn't provide an API for using event capture, so you'd have to use addEventListener instead:
document.querySelector("selector for the control").addEventListener("click", function(e) {
// Control code here
}, true);
document.addEventListener("click", function(e) {
// Document code here
}, true);
The true at the end means you want to use the capturing phase, rather than the bubbling phase.
Don't handle clicks on controls directly, use event delegation, handling clicks on the document and, if the click came through a control, calling your control-specific handling from the document click handler:
$(document).on("click", handleDocumentClick);
function handleDocumentClick(e) {
// On the next line, use whatever selector matches your controls
var input = $(e.target).closest("input")[0];
display("document click received");
if (input) {
handleControlClick.call(input, e);
}
}
function handleControlClick(e) {
display("control click received");
}
Live Example
You can use live(). live() binds the click event to the DOM's document element. As browser events bubble up through the DOM tree, the click event is triggered for any matching elements.
$(document).click(function() {
alert('document');
});
$(document).live('click', 'div', function() {
alert('div');
});
DEMO

Jquery action event after DOM creation not working

I have a button being created after the DOM is created. That button has an action. What I'm having trouble is binding that action to the button. I have researched and people said to us the .on() function but it doesn't seem to be working. What am I missing?
http://jsfiddle.net/e7a4X/
HTML
<button id="firstClick">Click me to create another button</button>
<div id="container"></div>
Javascript
$('#firstClick').click(function() {
$('#container').append('<button class="second-button">Button after DOM</button>');
});
$('.second-button').on('click', function () {
alert("Success");
})
Working demoL http://jsfiddle.net/Metsx/ or http://jsfiddle.net/ZB2Ns/
API : .on http://api.jquery.com/on/
Now to make your event know about the click event you need .on at document or at #container level, which attaches event handlers to the currently selected set of elements in the jQuery object.
Rest should fit your need :)
Code
$('#firstClick').click(function() {
$('#container').append('<button class="second-button">Button after DOM</button>');
});
$(document).on('click', '.second-button', function () {
alert("Success");
})
You will need to tell the DOM, parent to listen to its child.
The issue is that Your new .second-button is a new element, and you have defined your .click function before the DOM actually exists.
But all DOM interactions will trigger a event propagations(bubbling), therefore you can tell #container to listen for click events coming from .second-button
Or use $(document).on to listen, since the bubbling will go all the way to the document root.
If you are a performance minimalist than you would just do #container .on, and stop the propagation from that point, since theres no need to travel to every parent node, but you might eventually need to listen it from the parent of the #container, who knows

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