event.toElement.id always undefined when I trigger event click - javascript

I am newbie to html and java-script ,trying to fire a click event when page load finished
$(document).ready(function(event){
$("#london").click(function(event){
openCity(event,'London');
});
$("#london").trigger('click'); //this is automatic click
});
This click is working.But in my function
function openCity(evt, cityName) {
var id = evt.toElement.id; //id is undefined only when click event triggered
}
id is undefined only when click event triggered,when normal click it contains value.

Instead of toElement you need to use target.
For more info I'd suggest to read What is the difference between Event.target, Event.toElement and Event.srcElement?
function openCity(evt, cityName) {
var id = evt.target.id; //id is undefined only when click event triggered
console.log('id: ' + id);
}
$("#london").click(function(event){
openCity(event,'London');
});
$("#london").trigger('click'); //this is automatic click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="london">london</button>

Use evt.target.id instead of toElement - see demo below:
$(document).ready(function(event) {
$("#london").click(function(event) {
openCity(event, 'London');
});
$("#london").trigger('click'); //this is automatic click
});
function openCity(evt, cityName) {
var id = evt.target.id;
console.log(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='london'>London</div>

You can use this keyword for your function like following.
function openCity(element, cityName) {
var id = element.id;
console.log('id: ' + id);
}
$("#london").click(function(event){
openCity(this,'London');
});
$("#london").trigger('click'); //this is automatic click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="london">london</button>

You better use this inside the function, and then attr('id') to get the relevant attribute:
function openCity(el, cityName) {
var id = $(el).attr('id');
console.log(id);
}
$(document).ready(function(event){
$("#london").click(function(event) {
openCity(this, 'London');
});
$("#london").trigger('click'); //this is automatic click
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="london">London</div>
this in your context is the relevant elements that was clicked.

Use event.currentTarget to get the bound element.
function openCity(evt, cityName) {
var id = evt.currentTarget.id;
}
This is a standard property of the event object. It yields the same value as this would in the handler. That way you can still just pass around the event object and have the target, the currentTarget and all the other event data as well.
Keep in mind that the target and currentTarget may be two different elements. The target is the most deeply nested element clicked, whereas the currentTarget is always the bound element.
Since you want the element that has the id, using currentTarget will be safer. Doesn't matter for the .trigger() call, but may for the actual, human clicks if you have nested elements.

Related

Bind to jquery function issue

I'm using JQuery inside EcmaScript 6 class, and I have an event function which fires on instantiation of the class and the event contains different JQuery events which need to interact with the Class , so I do .bind() to achieve that, all works ok except one event which for some reason overrides this that belongs to jquery element "this" with "that" which I passed with .bind(that) method, here is my code (everything works exept for this event) :
var that = this;
$(document).on('click', '[select-file]' , function(event) {
event.preventDefault();
console.log(this);
}.bind(that));
so the console log gives me the parent class instead of jquery element
where as this works as expected:
$(document).on('click', '[open-file-dialoge]', function(event) {
event.preventDefault();
$('[file-dialoge]').modal('show');
if ($(this).attr('mitiupload') == 'false') {
// check if multiple upload is disabled
that.multiUpload = false;
$(this).removeAttr('multiple');
}
that.insertFiles();
}.bind(that));
Pleas help , I can't understand what is going on here one does not work as expected even though there is no big difference between them ;(
Function#bind() changes the context of this in a function. If you want the current element you can use event.currentTarget
var that = {};
$(document).on('click', 'button', function(event) {
event.preventDefault();
var el = event.currentTarget;
console.log('this=', this);
console.log('el=', el)
}.bind(that));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Click me</button>

click function triggered from div

I have got a button wrapped inside a div.
The problem is that if I click the button, somehow the click function is triggered from the div instead of the button.
Thats the function I have for the click event:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
Thats my HTML (after is is created dynamically!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
So now myVariable from the click function is 'Line1Software' because the event is fired from the div instead of the button.
My click function hast to look like this because I am creating buttons dynamically.
Edit:
This is how I create my buttons and wrapp them inside the div
var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you are trying to add an event listener to the button you should probably be using $('#Software') instead of $('#ButtonDiv')
The real problem is that neither the div nor the button have an id.
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you only want it to match the innermost element, then use return false to stop the bubbling.
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ButtonDiv">
</div>
Your question is a bit odd because you give yourself the answer... Look at your code, you are explicitly using event delegation:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
This code means that, for each click on a .Line1 element, the event will be delegated to the #ButtonDiv element (thanks to bubbling).
If you do not want this behavior, just do that:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
This is also correct:
$('.Line1').click(function () {
var myVariable = this.id;
});

get object containing dynamic button jQuery

I have some dynamically created objects from a jade template which contain buttons. I would like to be able to get the object when the button inside it is clicked. Here is what I currently have
mixin ad(name,media,payout)
.box.box-primary
.box-header.with-border
h3.box-title=name
.box-body
img(src=media, style='width:130px;height:100px;')
p.text-muted.text-center="$"+payout
p.text-muted.text-center preview
.box-footer.text-right
button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf()') Share
and the jQuery
var getSelf = function() {
var clickedBtnID = $(this).parent();
alert('you clicked on button #' + clickedBtnID.name);
}
I know my jQuery is incorrect because It just prints "undefined" but how would I print the name?
Thanks.
As of now, this doesn't refer to the button element, it refers to window object.
You can pass the this reference to the function
button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf(this)')
Modify your function to accept the reference, which can be used later.
var getSelf = function(elem) {
var clickedBtnID = $(elem).parent();
alert('you clicked on button #' + clickedBtnID.name);
}
However I would recommend you to use unobtrusive event handler instead of ugly inline click handler(get rid of it).
$(function(){
$("#share").on('click', function(){
var clickedBtnID = $(this).parent();
alert('you clicked on button #' + clickedBtnID.name);
});
})
You can reference to the element which triggered the event using the event.target property. The event information is passed as the first parameter to the event handler.
Complete working code.
$('div').click(function(event){
console.log(event.target.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<div id="div5">div5</div>

Binding click function to dynamic divs

There will be number of such div created with unique div id,
when i click on click me it should show an alert for that productid,
i am doing it like
<div id="xyz{productid}">
Click Me
</div>
.....
<script type="text/javascript">
var uuid="{productid}"
</script>
<script src="file1.js">
code from file1.js
$(function () {
var d = "#xyz" + uuid;
$(d).click(function () {
alert("Hello" + uuid);
return false;
});
alert(d);
});
So code is also ok,but the basic problem with it is,
since i m doing it on category page where we have number of products,this function is getting bound to last product tile only,
I want it to be bound to that specific div only where it is been called
..............................
got a solution
sorry for late reply,was on weekend holiday, but i solved it by class type of architecture, where we create an object with each tile on page,and at page loading time we initialize all its class vars,so you can get seperate div id and when bind a function to it, can still use the data from its class variables, i m posting my code here so if any one want can use it,
UniqeDiv= new function()
{
var _this = this;
var _divParams = null;
var _uuid=null;
//constructor
new function(){
//$(document).bind("ready", initialize);
//$(window).bind("unload", dispose);
_uuid=pUUID;
initialize();
$('#abcd_'+_uuid).bind("click",showRatingsMe)
dispose();
}
function initialize(){
}
function showRatingsMe(){
alert(_uuid);
}
function dispose(){
_this = _divParams = null
}
}
//In a target file, im including this js file as below
<script type="text/javascript">
var pUUID="${uuid}";
</script>
<script type="text/javascript" src="http://localhost:8080/..../abc.js"></script>
You can use attribute selector with starts with wild card with jQuery on() to bind the click event for dynamically added elements.
$(document).on("click", "[id^=xyz]", function(){
//your code here
alert("Hello"+this.id);
return false;
});
I would add a class to each of your dynamic divs so that they are easier to query. In the following example, I'm using the class dynamic to tag the div's that are added dynamically and should have this click listener applied.
To attach the event, you can use delegated events with jQuery's on() function. Delegated events will fire for current and future elements in the DOM:
$(function() {
var d="#xyz"+uuid;
$(document).on('click', 'div.dynamic', function() {
alert("Hello"+uuid);
return false;
});
});
You can read more about event delegation here.
You can use
$("[id*='divid_']").click(function(){
});
but for this you need to make sure that all div IDs start with "divid_".

How to execute a function using the value of a textbox Onclick of a DIV instead of a Onclick of a textbox

I have this function:
$("#border-radius").click(function(){
var value = $("#border-radius").attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, '2', this.id)
$(this).css({
"-webkit-border-radius": value
});
});
});
It reads the value of a textbox,
input type="text" id="border-radius" value="20px"
...and does a few things with it that are not relevant to my problem.
The textbox has the id="border-radius", and when it is clicked (and has a value) the function executes, as shown: $("#border-radius").click(function(){ ...do some stuff...
Basically, I want to be able to type a value into the textbox, and then click an object (submit button or div, preferably a div) and have it execute the function after: $("#border-radius").click(function(){ ...do some stuff... Instead of having to click the textbox itself
What can I add/change to enable this?
I think you need to identify the event target.
that you can do it by
event target property
example
$(document).ready(function() {
$("#border-radius").click(function(event) {
alert(event.target.id);
//match target id and than proceed futher
});
});
Put the click handler on #my-button or whatever your button is.
$("#my-button").click(function(){
var value = ... /* your original code */
});
It will still work because you are getting the value like $("#border-radius").attr("value"); and not $(this).attr("value");. So you all you need to change is which element you attach the click function to.
Alternatively, if you want to keep both handlers, you can just use it for both elements like this:
var commonHandler = function(){
var value = ... /* your original code */
};
$("#border-radius").click(commonHandler);
$("#my-button").click(commonHandler);
You can also trigger the click event of #border-radius, but this will execute all the event handlers attached on it:
$("#my-button").click(function () {
$("#border-radius").click();
// or $("#border-radius").trigger('click');
});

Categories