Mootools - how to refer local 'this' and class 'this' in an Event? - javascript

There are 10 li elements and 5 of those have a element inside. And I'd like to add an event on the li elements using Mootools.
A class has few variables and method including the event for the li elements and my problem comes from here. please see the event for li below,
li.addEvents({
mouseover: function(e){
console.log(this.id + ' / ' + this.classVar);
}.bind(this)
});
In the event I need to refer li itself and a class variable because each li has unique id and the classVar has also information. But problem is if I use bind(this) to the event, this.id won't work or if not using it, *this.classVar' won't work.
If I use e.target.id instead of this.id, it returns correct id IF ONLY the li doesn't have a element. Otherwise e.target refers the a element.
Can anyone help me on this please? Many thanks in advance

The simplest way is to use the self or me workaround, like so...
function myClass()
{
var self = this;
this.classVar = 'foo';
// some other code
li.addEvents({
mouseover: function(e){
console.log(this.id + ' / ' + self.classVar);
}
});
}

Related

How to go to the parent of an element in if

Hello I've got a little problem with this code:
if($(actualFilter + ' .select2-container ul .select2-search-choice div').html() === data) {
$(this).parent() // and now I want to search for "a"
});
Is it possible to somehow set this code in if as this?
Because if I want to go up with parent() and then when I am in .select2-search-choice in this I want to search for a to do click().
I believe what you are looking for is the jquery next and trigger functions.
if($(actualFilter + ' .select2-container ul .select2-search-choice div').html() === data) {
$(this).parent().next("a").trigger( "click" );
});
this or $(this) is available in events like
$('div').click(function(){
alert(this.tageName); //will print DIV for you
});
In if statement you have to simply reuse the selector like
var yourElement = $(actualFilter + '.select2-container ul .select2-search-choice div');
if(yourElement.html() === data) {
var parentEl = yourElement.parent();
});

Javascript - arrow functions this in event handler?

I'm new to ES6, and can't quite get this to work:
$(this) returns undefined on click?
dom.videoLinks.click((e) => {
e.preventDefault();
console.log($(this));
var self = $(this),
url = self.attr(configuration.attribute);
eventHandlers.showVideo(url);
// Deactivate any active video thumbs
dom.videoLinks.filter('.video-selected').removeClass('video-selected');
// Activate selected video thumb
self.addClass('video-selected');
});
However if I change it so not be an arrow function like so, it works as expected?:
dom.videoLinks.click(function(e) {
e.preventDefault();
console.log(this);
console.log($(this));
var self = e.this,
url = self.attr(configuration.attribute);
eventHandlers.showVideo(url);
// Deactivate any active video thumbs
dom.videoLinks.filter('.video-selected').removeClass('video-selected');
// Activate selected video thumb
self.addClass('video-selected');
});
So how would I go about it if I use an arrow function in the callback?
With arrow function as a callback, instead of using this to get the element to which the handler is bound, you should use event.currentTarget.
Value of this inside an arrow function is determined by where the arrow function is defined, not where it is used.So from now on, keep in mind that
event.currentTarget always refers to the DOM element whose EventListeners are currently being processed.
.currentTarget vs .target
Use event.currentTarget instead of event.target because of event bubbling/capturing:
event.currentTarget- is the element that has the event listener attached to.
event.target- is the element that triggered the event.
From the documentation:
currentTarget of type EventTarget, readonly Used to indicate the
EventTarget whose EventListeners are currently being processed. This
is particularly useful during capturing and bubbling.
Check the basic example in the below snippet
var parent = document.getElementById('parent');
parent.addEventListener('click', function(e) {
document.getElementById('msg').innerHTML = "this: " + this.id +
"<br> currentTarget: " + e.currentTarget.id +
"<br>target: " + e.target.id;
});
$('#parent').on('click', function(e) {
$('#jQmsg').html("*jQuery<br>this: " + $(this).prop('id')
+ "<br>currenTarget: " + $(e.currentTarget).prop('id')
+ "<br>target: " + $(e.target).prop('id'));
});
$('#parent').on('click', e => $('#arrmsg').html('*Arrow function <br> currentTarget: ' + e.currentTarget.id));
#parent {background-color:red; width:250px; height:220px;}
#child {background-color:yellow;height:120px;width:120px;margin:0 auto;}
#grand-child {background-color:blue;height:50px;width:50px;margin:0 auto;}
#msg, #jQmsg, #arrmsg {font-size:16px;font-weight:600;background-color:#eee;font-family:sans-serif;color:navy;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">Parent-(attached event handler)<br><br>
<div id="child"> Child<br><br>
<p id="grand-child">Grand Child</p>
</div>
</div>
<div id="msg"></div><br>
<div id="jQmsg"></div><br>
<div id="arrmsg"></div>
You wouldn't.
Changing the value of this is the primary point of using an arrow function.
If you don't want to do that then an arrow function is the wrong tool for the job.
You can use $(event.target) instead of $(this) even inside of an arrow function. Arrow functions are preserving this of the scope where they were defined. In your case it is undefined.
arrow functions and this selector?
Arrow functions retain this from enclosing context.
Eg.
obj.method = function(){
console.log(this);
$('a').click(e=>{
console.log(this);
})
};
obj.method(); // logs obj
$('a').click(); // logs obj
So how would I go about it if I use an arrow function in the callback?
You already can - to access event target you can use something like $(e.target), but beware of bubbling. So I recommend to use normal functions instead as callbacks.

jquery: how to add event handler to dynamically added element without adding it to existing element again

I'll try to explain my problem:
I have a website where the user dynamically adds elements. They all belong to the "toBuy" class. Whenever a new element is added to this class I need to attach a click-handler to only this element but not to all others. To keep my code clean I want to have a function that does this work. Here is what i've tried:
this is how the stuff is added:
$("#addItemButton").click(function(){
var item= $('#item').val();
$('#item').val("");
var quantity= $('#quantity').val();
$('#quantity').val("");
var comment=$('#addComment').val();
$('#addComment').val("");
//construct new html
var newitem="<div class='toBuyItem'><div class='item'>";
newitem+=item;
newitem+="</div><div class='quantity'>";
newitem+=quantity;
newitem+="</div><div class='comment'><img src='img/comment";
if(comment==""){
newitem+="_none"
}
newitem+=".png' alt='Comment'></div><div class='itemComment'>"
newitem+=comment;
newitem+="</div></div>";
$("#toBuyItems" ).prepend( newitem );
toggle("#addItemClicked");
initializeEventListeners();
});
then this is the initializeEventListeners function (which I also run when the page loads so that the existing elements have the event handlers already:
function initializeEventListeners(){
$(".toBuyItem").click(function(){
console.log($(this).html());
console.log($(this).has('.itemComment').length);
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
}
function toggle(item){
$( item ).slideToggle(500);
}
now apparently what happens is that when a new element is added the existing elements get a new event handler for clicking (so they have it twice). Meaning that they toggle on and off with just one click. Probably it's damn simple but I cannot wrap my head around it....
EDIT:
so this works:
$(document).on('click', '.toBuyItem', function(){
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
Use jquery's on method. This way you have to add event only once. This will be added automatically to dynamically added elements.
$(document/parentSelector).on('click', '.toBuyItem', function() {
// Event handler code here
});
If you are using parentSelector in the above syntax, it has to be present at the time of adding event.
Docs: https://api.jquery.com/on
You can use jQuery.on method. It can attach handlers to all existing in the DOM and created in future tags of the selector. Syntax is as follows:
$(document).on('click', '.toBuyItem', function(){
//do onClick stuff
})
As others have suggested, you can delegate click handling to document or some suitable container element, and that's probably what I would do.
But you could alternatively define a named click handler, which would be available to be attached to elements already present on page load, and (scope permitting) to elements added later.
You might choose to write ...
function buy() {
if($(this).has('.itemComment').length != 0) {
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
}
function initializeEventListeners() {
$(".toBuyItem").on('click', buy);
}
$("#addItemButton").on('click', function() {
var item = $('#item').val(),
quantity = $('#quantity').val(),
comment = $('#addComment').val();
$('#item', '#quantity', '#addComment').val("");
//construct and append a new item
var $newitem = $('<div class="toBuyItem"><div class="item">' + item + '</div><div class="quantity">' + quantity + '</div><div class="comment"><img alt="Comment"></div><div class="itemComment">' + comment + '</div></div>').prependTo("#toBuyItems").on('click', buy);// <<<<< here, you benefit from having named the click handler
$newitem.find(".comment img").attr('src', comment ? 'img/comment.png' : 'img/comment_none.png');
toggle("#addItemClicked");
});

get clicked element ID or Name jquery or javascript

I wants to get the ID or the name of the clicked elemt by using the following code. this code is working fine if i have only one element.
$(window).mousedown( function(e) {
mouseTracker.clickState = true;
console.log( "id:" + e.target.id + " name:" + e.target.name );
}).mouseup( function() {
mouseTracker.clickObject = '';
});
but if element is wrapped up in other elements then i am unable to get the ID. for example:
<div id="main">
<div id="subDiv">
<span id="spID" onClick="alert ('hello world')"> Click Me </span>
</div>
</div>
in the above case, it is return the ID of the main div. how can i get the clicked element.
The most secure way to do this is to add an event listener to each element. There are different ways to do that:
First as you have coded in your HTML:
var testfunction = function(event){
// Do something
};
<span id="spID" onclick="testfunction(event)"></span>
Or nicer:
<span id="spID"></span>
var element = document.getElementById('spID');
element.addEventListener('click', function(event){
// do something
})
Best regards
Dustin
I wouldn't use inline scripting if it was me. The bigger a project gets, the messier this becomes. I tend to have all my event listeners tucked away together in an init function that you can just add to as you need more event listeners:
In the head of your HTML:
<script src="global.js"></script>
<script>
$(document).ready(function() {
global.init();
});
</script>
In a separate js file, linked to your HTML (e.g. global.js):
(function (global, $, undefined) {
global.init = function() {
//bind your event listeners in here
};
})(window.global = window.global || {}, jQuery));
In terms of using this for the purposes of what you are trying to do, if you have a series of these clickable spans, I would use a class selector, so you only have to bind the click event once, otherwise if you are binding to only one span as above then you already know the ID anyway as you had to use it in the bind.
Using class:
global.init = function() {
//assuming you have applied the class "clickable-span" to all the spans you want to be clickable
$('.clickable-span').on('click', function(evt) {
var id = $(this).attr('id'),
name = $(this).attr('name');
console.log( "id:" + id + " name:" + name );
});
//add more event listeners here
};

calling javascript function too many times

I'm just getting into Javascript and I've run into the same problem a number of times with different pieces of code: I have a function that creates a type of element and a function that does something with that type of element. It seems obvious to me that I need to call the "do something" function after the element has been created, but when I do, it ends up running more times than I'd like.
Here's an example of my problem:
function rightClick(){
$(".element").mousedown(function(e){
switch (e.which){case 3: alert( $(this).attr("id") )};
});
};
function doubleClick(){
var counter = 0;
$(document).dblclick(function(e){
counter++;
elementId = "element" + counter;
$("#new_elements").append("<div class='element'" +
"id='" + elementId + "'" +
"style='position:absolute;" +
"top:" + e.pageY + ";" +
"left:" + e.pageX + ";'>" +
elementId+ "</div>");
rightClick();
});
In this example, if I create 4 elements and I right-click on the first one I created, I end up getting 4 alert boxes instead of one. If I right-click on the second element I created, I get three alerts; the third: 2 alerts; the fourth: one alert.
Can anyone explain to me why this is happening, and how to fix it so that I only get one alert each time I right-click on an element?
Binding is the act of associating an event with a DOM element. The .mousedown and similar events only bind on elements that already exist.
Each time you call rightClick() you bind a new event to all current .element elements.
You can bind functions to the same element as much as you'd like, which is why you see the function being called many times.
For dynamic elements should checkout .on or .delegate which work like this:
Example of jQuery.fn.on
$(document.body).on("mousedown", ".element", function(e) {
if (e.which === 3) alert($(this).attr("id"));
});
Example of jQuery.fn.delegate
$(document.body).delegate(".element", "mousedown", function(e) {
if (e.which === 3) alert($(this).attr("id"));
});
Only call this once and you should be pretty much okay. If you're not using jQuery 1.7 or higher you will want to use .delegate() instead of .on.
You do not need to bind the event everytime you insert and element into the DOM. You can use .on to attach event handlers for elements that are dynamically inserted.
$(document).on('mousedown','.element', (function(e){
switch (e.which){
case 3: alert( $(this).attr("id") );
break;
};
});
var counter = 0;
$(document).dblclick(function(e){
counter++;
elementId = "element" + counter;
$("#new_elements").append("<div class='element'" +
"id='" + elementId + "'" +
"style='position:absolute;" +
"top:" + e.pageY + ";" +
"left:" + e.pageX + ";'>" +
elementId+ "</div>");
});
I believe you are adding the same handler several times, meaning that when you click a button you are re-binding the action to the same function.
You've bound your event handler to the class '.element'. This means that every element with the class '.element' on your page will fire that event when the right click occurs.

Categories