attach event handler for dynamic element - javascript

I try to attach event handler for dynamic element but failed.
Here's some of my code. I want event can be called by dynamic element.
Maybe javascript provide function to support attach event for dynamic element automatically without bind it again such as jQuery live or on method.
I want to add functionality to load city data while state or province selected to Magento Sales > Order > Create New Order Page without have to search a correct javascript file and try to bind event on it again.
window.addEventListener('load', function(){
function getCity(){
id= this.selectedIndex;
name= this.name;
getKota(id, name);
}
billing_address_region_id= document.getElementsByName('order[billing_address][region_id]');
shipping_address_region_id= document.getElementsByName('order[shipping_address][region_id]');
var event = new Event('change');
billing_address_region_id[0].addEventListener('change', getCity, false);
shipping_address_region_id[0].addEventListener('change', getCity, false);
billing_address_region_id[0].dispatchEvent(event);
shipping_address_region_id[0].dispatchEvent(event);
});
Thanks a ton

Note: This solution is not tested.
What you could do since the target elements are added dynamically is to register a change event handler to the window, then see whether any of the target element fired the change event if so do your action.
window.addEventListener('change', function (e) {
var el = e.target;
if (el.name == 'order[billing_address][region_id]' || el.name == 'order[shipping_address][region_id]') {
getKota(el.selectedIndex, el.name);
}
});

Your code would work only for already existing elements. I recommend using jQuery.
Using jQuery, you can use "on" method.
$('#elem').on('change', function(){
// Do stuff
});

Related

EventListener not working with anchor tel:XXXXXXXXX

I have a tag with href="tel:XXXXXXXXX", and I need catch the click event.
I have tested the following code on chrome: $(document).on('click',console.log). If i click on this tag browser it calls the application, but does not trigger a click event.
$("a[href^='tel']").on('click', console.log);
This is working, but I my have a problem with content load by ajax. My code has loaded a page and after some time application added content by ajax. When i use $(document).on('click', ("a[href^='tel']", console.log), there is a problem.
$("a[href^='tel']").on("click", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
})
//or if you want to delegate your function
$(document).on('click', "a[href^='tel']", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
});
This will bind an event listener to all click on a tags with a href attribute and prevent the click itself. After click, you'll be able to use your console to see which element was click and what href was used.
Ok, i found resolve.
I use earlier event "mousedown" and change attr "href" to "only number" for disable action click.
Code:
const click2dial_Event = function(e) {
e.preventDefault();
let a = $(this), number;
if (a.attr('href') !== '#') {
number = a.attr('href');
number = number.substr(4);
a.attr('href', '#');
a.attr('data-dial', number)
a.addClass('click-to-dial');
} else {
number = a.attr('data-dial');
}
//...
};
$(document).on('mousedown', "a[href^='tel']", click2dial_Event);
$(document).on('mousedown', '.click-to-dial', click2dial_Event);
This would get the phone number from the a tag starting with a value of tel upon clicking it.
$("a[href^='tel']").on("click", function(e) {
var hrefText = this.getAttribute("href");
var str = hrefText;
var res = str.split(":");
alert(res[1]);
});
On Initial Load
I would first recommend that you wait for the initial DOM to be ready before binding any events to elements.
// DOM ready shorthand
$(function() {
$("a[href^='tel']").on('click', function(e) {
// Do work here
});
});
AJAX Content
If you are adding additional elements after the initial load you will have to bind events to those new elements as well.
You could also do something like adding a data attribute to the elements that you've bound click events to and only add to ones that don't yet have that data attribute - but that's additional unnecessary work.
Full Example Code
// DOM Ready Shorthand
$(function() {
// Click Handler
function clickEvent(e) {
// Do work here
}
// Bind click event to initial tels
$("a[href^='tel']").on('click', clickEvent);
// Arbitrary AJAX request for demonstration (wherever yours may be)
$.ajax('/newContent')
.done(function(html) {
// Adding our response HTML to the page within #someElement
$('#someElement').append(html);
// Bind click event to the new tel elements scoped to the returned html
$("a[href^='tel']", html).on('click', clickEvent);
});
});

How to determine which widget was clicked? Dojo

Is there a way to observe the mouse click event and determine which widget was clicked?
So basically I wish I could do something like this (on mouse click anywhere on the page)
on("click", function (e) {
//var aWidget = dijit.getEnclosingWidget(e.target);
//var id = aWidget.id
//do something based on the widget id
});
You can but it will requires some extra steps.
Basically, the logic is:
- When you click on a node, you have to go up in the DOM until you find a node with the attribute widgetId
- When you have it, use dijit/registry::byNode to fetch the widget.
If you skip the node traversing, you will find the widget only if the main domNode of the widget was clicked.
require(['dojo/on', 'dijit/registry'], function(on, registry){
on(document, 'click', function(event){
var target = event.target,
widget;
while(!target.getAttribute('widgetId') && target.parentNode) {
target = target.parentNode;
}
widget = registry.byNode(target);
console.warn(widget);
});
});
Be aware, this method will work ONLY if you have 1 dojo instance loaded on in the page.
If you page have more than one dojo instance then the document click event must be attached by every dojo instances.
Might be a lot of overhead but yes you can
require(["dojox/mobile/deviceTheme","dojo/on","dijit/registry"],function(theme,on,reg){
on(document,'click', function(e){
console.log(e.target);
var widget = reg.byNode(e.target);
console.log("foundWidget::" + widget.id);
});
});

Get href of dynamically created bound link

I have some links that are dynamically created within a table and the href of those links sends a GET request to delete a user. I have the listener bound like so:
var $usersTableBody = $('#table-users tbody');
var $deleteUserBtn = $('.delete-user-btn');
$usersTableBody.on('click', $deleteUserBtn, deleteConfirm);
I need to get the href of $deleteUserBtn, the problem is that now I cannot get the link of the <a> that I am clicking since the event is bound to the table body. So... how do I go about doing this?
Making it easy for you
// this argument should be a string
// ↓
$('#table-users tbody').on('click', '.delete-user-btn', function(e) {
alert(this.href); // "this" is the event target / source
});
See http://api.jquery.com/on/#on-events-selector-data-handler
selector
Type: String
A selector string to filter the descendants of the selected elements that trigger the event.
$(document).on("click", "a.delete-user-btn", function(event) {
// prevent default action, to not affect any other
// event handlers attached to `a.delete-user-btn`
event.preventDefault();
// do stuff with `this` : `a.delete-user-btn` `href` property
console.log(this.href)
})
First, please see the documentation for jQuery's on because you are not using the correct parameters.
I don't know the exact nature of your HTML, but you can use the target property of the event callback object to determine the href:
$usersTableBody.on('click', function(e) {
var $target = jQuery(e.target);
alert('clicked: ' + $target.attr('href'));
deleteConfirm();
// delete action
});
See this jsbin for another example: https://jsbin.com/huzegufihe/edit?html,output

JQuery Onchange Event Not Working on production but working on my local instance

$("#time-popup").change(function (event) {
if (document.getElementById("time-popup") != null) {
document.getElementById("popup_Billed_").value = document.getElementById("time-popup").value;
}
});
While clik on time-popup textbox feild no event fired.
even no alert for
alert($("#time-popup"));
please suggest
First you can write all in jQuery like below (commented code is not required)
$(document).ready(function(){
$("#time-popup").change(function (event) {
/*if ($("#time-popup").length > 0) { */
$("#popup_Billed_").val($("#time-popup").val());
/*}*/
// above if condition not required because you are
//running this code for onchange event of time-popup
// only so no need to check if it exist or not.
});
});
Check console error for your html and be sure that there should not be any duplicate Id for time-popup or popup_Billed is present in view source of the page.
Also if time-popup is getting created dynamically then you should bind change event using .on()
$(document).ready(function(){
$(document).on("change","#time-popup",function (event) {
$("#popup_Billed_").val($("#time-popup").val());
});
});
Try Event Delegation:
$(document).on('change', "#time-popup", function (event) {
...
From the docs:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
Try this way:
$(document).ready(function(){
$("#time-popup").on('change',function () {
document.getElementById("popup_Billed_").value = document.getElementById("time-popup").value;
});
});

Trapping all `a` clicks including ones added dynamcally

I know you can bind to click events with jQuery like so:
$('a').click(function(){});
But what about html elements that are added dynamically? Lets say I have a div with the following contents:
<div>
<a href='location.html'>location</a>
</div>
Now I call:
$('a').click(
function(){
console.log("going to " + $(this).attr('href'));
return true;
});
And that will work fine. But if somewhere along the line I call
$('div').("<a href='location2.html'>location2</a>");
without explicitly binding that event handler to that event then the event handler will pick up on it.
Is it possible to rebind when ever a new a element is added. Or even better, when ever the location.href property is changing so I can add a get parameter to it every time.
For example if I was binding to a click event on an a element the event handler would be:
function(){
var newid = parseInt(Obj.Request('pageid'), 10) + 1;
location.href = $(this).attr('href') + '?pageid=' + newid.toString();
return false;
}
Assuming the Obj.Request is a function that returns a get parameter. (I already have this in place).
Use it in this manner:
$(document).on( 'click', 'a', function() {
console.log("going to " + $(this).attr('href'));
return true;
});
Working on your fiddle link.
You want to use the function .on.
$('a').on('click', function() {
//works on non dynamic elements present at page load
});
$('#some_non_dynamic_parent_ID').on('click', 'a', function() {
//works on dynamic elements added later
});
You want to use .on(), but as a delegation method.
Bind it to the closest static parent - for this example I'll just use body.
$('body').on('click', 'a', function(e){
e.preventDefault();
});
This will wait until the event bubbles up to the body element and check what the original target of the event was - if it was an a element, it'll fire the handler.
You can use .on() or live() functions if you use jquery upper then 1.7 version. About the difference of these functions you can read in this article

Categories