Javascript Mootools click event and his caller? - javascript

I have this little script:
var moolang = new Class({
initialize: function(element) {
this.el = $(element);
this.el.addEvent('click', this.popup);
},
popup: function()
{
//this.id = the id of the element.
}
});
And I want to know "this" in the popup function, but if I try something like alert(this.el.id) it says there is no this.el.
Is there a way to know which class adds the event?

Change the attach event so the callee has the proper context. Otherwise the context of an event listener will be the target element.
// Change this line
this.el.addEvent('click', this.popup);
//To this
this.el.addEvent('click', this.popup.bind(this)); // popup->this == this
jsfiddle here
See mootools documentation. Binding the context of a function.

Related

Firing a function with a newly added class

I've tried to simplify it, simple enough to make my question clearer.
The alert 'I am a boy' didn't popup with even after the addClass has been executed.
Here is my code:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
$(".second").click(function () {
alert('I am a boy');
});
<button class="first">On</button>
This behavior is because you are apply a class to an element after the DOM has loaded, in other words dynamically. Because of this, your event listener attached to the control for '.second' isn't aware of the newly added class and doesn't fire when you click on that control.
To fix this, you simply need to apply your event listener to a parent DOM object, typically $(document) or $('body'), this will ensure it is aware of any children with dynamically added classes.
As George Bailey said, you can refer here for a in depth explanation.
In regards to your specific code, the fix is to simply adjust it as so:
$(".first").click(function () {
var a = $(this).html();
if (a=='On') {
$(this).removeClass('first').unbind().addClass('second');
$(this).html('Off');
}
});
/* Changed this:
$(".second").click(function () {
alert('I am a boy');
});
*/
// To this:
$(document).on('click', '.second', function () {
console.log('I am a boy');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first">On</button>
The function you pass to $.post doesn’t run until later (a callback). So the class is added after you try to select it. Do it inside the callback, the same way you added the class (and you don’t need to select that class, just use $this)

.class selector not working

I'm working in a card game system that the player can select the card by clicking on it and then select the place to put it on. My problem is that when the player click on the target place, nothing happens.
This is my try: http://jsfiddle.net/5qMHz/
And this is my code:
function target() {
$(".target").on("click", function() {
$("#"+x).appendTo(this);
console.log(x);
});
};
What's wrong?
Try binding with document, since you change the class during document ready and there was no element with the class target initially
$(document).on("click",".target", function() {
$("#" + x).appendTo(this);
console.log(x);
}
WORKING FIDDLE
Firstly, your practice of putting function references in to jQuery objects is rather odd. The problem however is that because the .target class is applied after DOM load you need to use a delegate selector. Try this:
var $card
$(".card").on("click", function () {
$card = $(this);
if ($(".myslot").length) {
if ($(".myslot").is(':empty')) {
$(".myslot:empty").addClass("target");
} else {
alert('No empty slots');
}
}
});
$('.field').on('click', ".target", function () {
$card.appendTo(this);
$card = $();
});
Example fiddle
At the moment you are trying to bind the event handler, the elements don't have a class target yet. From the documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
(Technically the elements exist, but they are not (yet) addressable by the class target)
You have three options to solve this:
Add the class to your HTML markup.
Bind the handler after you added the class to the elements.
Use event delegation.
The first two don't really fit to your use case, since your are adding the class target in response to an other event and the number of elements with the class target changes over time. This is a good use case for event delegation though:
$('.field').on('click', '.target', function() {
// ...
});

How to get click event object data from dynamically created button using jQuery or JavaScript

I am collecting page button click events. Normally I am collecting the objects from statically created DOM elements. By using:
$('input[type=button]').each(function () {
$(this).bind('click', function () {
Console.log(this);
});
});
But when I add a new button dynamically like:
vvar newBtn = document.createElement('input');
newBtn.type = 'button';
newBtn.setAttribute('id', 'JgenerateBtn');
newBtn.setAttribute('value', 'JgenerateBtn');
newBtn.onclick = function () { alert('javascript dynamically created button'); };
var holderDiv = document.getElementById('holder');
holderDiv.appendChild(newBtn);
after this code, New Button is created and event also triggering, but I'm not able to get the Event object by using, same above code.
$('input[type=button]').each(function () {
$(this).bind('click', function () {
Console.log(this);
});
});
Please provide suggestion to get the dynamically created elements event object.
You may use on() for binding events on dynamically added elements. Like this:
$(document).on('click', 'input[type=button]', function(){
console.log(this);
});
This is just for simple example, it is better to bind it on element closer to your button that is already on page when it first loads rather than on document.
You should use the following:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#holder').on('click', ':button', function(event) {
alert('testlink');
});
This will attach your event to any button within the #holder element,
reducing the scope of having to check the whole document element tree and increasing efficiency.
More info here:-
http://api.jquery.com/on/
http://learn.jquery.com/events/event-delegation/
The event object is handed to your click handler as the first argument.
$('input[type=button]').each(function () {
$(this).bind('click', function (event) {
Console.log(event);
});
});

How can I check on which element the event was triggered?

addLBEvent : function()
{
var amount = this.imageList.length;
for(var i = 0;i < amount;i++)
{
if(this.imageList[i].addEventListener)
{
this.imageList[i].addEventListener("click",this.startLB,false);
}
/*
IE<9-part
*/
}
},
startLB : function(src)
{
}
I'd like to know which element triggered the event.
If I'd do this in the HTML-Code I'd write something like onlick="startLB(this.src)" for example. How can I do such a thing with addEventListener?
I've already tried `addEventListener("click","myobjectname.startLB(this.src)" but it didn't work.
And sorry for my bad English
An event object is passed in as the first argument to any event handler.
The event object as a target property identifying the element to which the event applies.
addLBEvent : function(event) {
console.log(event.target);
}
https://developer.mozilla.org/en/DOM/event.target
You can access a reference to the element that triggered the event...
var elementThatTriggeredEvent = e.target || e.srcElement;
...assuming that e is the reference to the event.
If you want to know which element was clicked, use event.target.
If you want to know which element you had the handler on, use event.currentTarget or, in most cases, this. addEventListener will call your handler with this set to the element on which you called addEventListener.
Note the distinction. For instance, if you had this markup:
<div id="foo"><span id="bar">Hi there</span></div>
...and this code:
document.getElementById("foo").addEventListener('click', function(event) {
alert(this.id);
alert(event.target.id)
}, false);
...then if the user clicks the text "Hi there", this will be the div but event.target will be the span.
Live example | source
See how this is the element you hooked the event on, and event.target is the element on which it fired (and then it bubbled up to the div).
Note that addEventListener isn't available on older versions of IE; you have to use attachEvent instead. attachEvent doesn't ensure that this is set to the element on which you hooked it, so beware that difference between APIs. To smooth things like that out, you might look to any decent library, like jQuery, YUI, Closure, or any of several others.
Use this:
startLB : function(src)
{
var element = src.target.tagName;
alert("element >> "+element);
}
I think it's best for you to bind it like this:
var that = this;
this.imageList[i].addEventListener("click",function() {
that.startLB(this.src);
},false);
this will become the event target, so we have to access the object somehow, I named that that
try this...
addLBEvent : function(e)
{
if (!e) e = event;
e = e.srcElement || e.target;
.......
}

Using current jQuery element in backbone.js view

Am slowing get a hang of backbone.js, but i've run into a bit of bind.
I've successfully created a view, and am able to delegate events to element in the DOM, however i can seem to be able to use the jQuery "$(this)" in the following context
Chrono.Views.Sidebar = Backbone.View.extend({
//Page wrapper
el:"#wrapper",
//Delegate events to elements
events : {
"click .push-to":"loadPage"
},
loadPage: function(event) {
var url = $(this).attr("href");
alert(url);
event.preventDefault();
}
});
The click event is intercept but this line "var url = $(this).attr("href");"
In the context of loadPage, this has been bound to your Chrono.Views.Sidebar instance. However, you can get the DOM element that the event was triggered on through event.currentTarget. If you update your function to look like this it should work:
loadPage: function(event) {
var url = $(event.currentTarget).attr("href");
alert(url);
event.preventDefault();
}
In backbone this is bound to the view, but you can still get the element that was clicked by checking the event.target or the element that the event was bound to using event.currentTarget.
Take a look at this question
Backbone.js Event Binding
this is bound to the view, so you can access the View.$el property directly.
loadPage: function(event) {
var url = this.$el.find('.push-to').attr('href');
alert(url);
event.preventDefault();
}

Categories

Resources