Adding an on event to an e.currentTarget? - javascript

A variety of elements on my page have the content editable tag.
When they are clicked I do this:
$('[contenteditable]').on('click', this.edit);
p.edit = function(e) {
console.log(e.currentTarget);
e.currentTarget.on('keydown', function() {
alert("keydown...");
});
};
I get the current target ok, but when I try to add keydown to it, I get the err:
Uncaught TypeError: undefined is not a function

It's a native DOM element, you'll have to wrap it in jQuery
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
e.currentTarget should equal this inside the event handler, which is more commonly used ?
It's a little hard to tell how this works, but I think I would do something like
$('[contenteditable]').on({
click : function() {
$(this).data('clicked', true);
},
keydown: function() {
if ($(this).data('clicked'))
alert("keydown...");
}
});
Demo

First issue is you are trying to use jQuery methods on a DOM element. Second issue is I do not think you want to bind what is clicked on, but the content editable element itself.
It also seems weird to be adding the event on click instead of a global listener. But this is the basic idea
$(this) //current content editable element
.off("keydown.cust") //remove any events that may have been added before
.on('keydown.cust', function(e) { //add new event listener [namespaced]
console.log("keydown"); //log it was pressed
});

Edited: I had a fail in code. It works fine now.
Getting your code, I improved to this one:
$(function(){
$('[contenteditable]').on('click', function(){
p.edit($(this));
});
});
var p = {
edit: function($e) {
console.log($e);
$e.on('keydown', function() {
console.log($(this));
alert("keydown...");
});
}
}
You can check it at jsFiddle

You need to wrap the e.currentTarget(which is a native DOM element) in jQuery since "on" event is a jQuery event:
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
EDIT:
$('[contenteditable]').on('click', p.edit);
p.edit = function(e) {
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
};
You're defining p.edit AFTER $('[contenteditable]').on('click', p.edit); resulting in an error since p.edit doesn't exist when declaring the on.
In case you don't know, you are defining p.edit as a function expression, meaning that you have to define it BEFORE calling it.

Related

I'm trying to attach events using on() based on changing selectors

I have a button that can be in 2 different states (lets say Lock and Unlock). When I click on the button, I update the class on the button to reflect the binary opposite state. Each class has a different event attachment function using on(string, callback). For some reason the event being triggered remains the first callback assigned based on the original class.
HTML:
<button class="lock">Lock</button>
<button class="unlock">Unlock</button>
JavaScript:
$(document).ready(function() {
$('.lock').on('click', function() {
// Perform some magic here
console.log('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$('.unlock').on('click', function() {
// Perform some magic here
console.log('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
https://jsfiddle.net/c283uaog/ for testing.
Expected console output when clicking on the same button repeatedly:
Lock!
Unlock!
Lock!
Actual console output:
Lock!
Lock!
Lock!
Any assistance would be greatly desired
use event Delegation
$(document).on('click','.lock', function() {
$(document).on('click','.unlock', function() {
updated Demo
Or use in single function with toggleClass
$(document).on('click', '.lock,.unlock', function () {
$('#output').html($(this).attr('class'));
$(this).toggleClass('lock unlock').text($(this).attr('class'));
});
ToggleClass demo
I'd do it this way, attaching only one event: http://jsfiddle.net/jozu47tv/
$(".lock").on('click', function(e) {
e.preventDefault();
if($(this).hasClass("lock")) {
$(this).removeClass("lock").addClass("unlock");
console.log("lock -> unlock");
} else {
$(this).removeClass("unlock").addClass("lock");
console.log("unlock -> lock");
}
})
Use Event Delegation method, Try this updated fiddle,
$(document).ready(function() {
$(document).on('click', '.lock', function() {
$('#output').html('Lock!');
$(this).removeClass('lock')
.addClass('unlock')
.html('Unlock');
});
$(document).on('click', '.unlock', function() {
$('#output').html('Unlock!');
$(this).removeClass('unlock')
.addClass('lock')
.html('Lock');
});
});
Probably, this question could answer you in a better way:
jQuery .on function for future elements, as .live is deprecated
$(document).on(event, selector, handler)
Change your html to this:
<button class="locker lock" >Lock</button>
<button class="locker unlock"">Unlock</button>
<div id="output">Output</div>
and your Js to this:
$(document).ready(function() {
$('.locker').on('click', function() {
if($(this).hasClass("lock")){
$(this).removeClass("lock");
$(this).addClass("unlock");
$(this).html("unlock");
}
else if($(this).hasClass("unlock")){
$(this).removeClass("unlock");
$(this).addClass("lock");
$(this).html("lock");
}
});
});

click event not working when changing id or class

I'm starting with jquery, and have an issue here:
http://jsfiddle.net/8guzD/
$('#test.off').click(function(){
$(this).removeClass('off').addClass('on');
});
$('#test.on').click(function(){
$(this).removeClass('on').addClass('off');
alert('ok');
});
the first part of the code goes well, the class is apply, but when I attach an event in this element with its new class it won't work.
Can someone explain me what is the problem exactly?
I tried with javascript,
http://jsfiddle.net/R5NRz/
var element = document.getElementById('test');
element.addEventListener('click', function() {
this.id ='test2';
alert("ok");
}, false);
var element2 = document.getElementById('test2');
element2.addEventListener('click', function() {
alert("ok2");
}, false);
and it didn't really help me, having the same issue
try
$(document).on("click",'#test.on',function(){
$(this).removeClass('off').addClass('on');
alert('ok');
});
$(document).on("click",'#test.off',function(){
$(this).removeClass('off').addClass('on');
alert('ok passs');
});
Demo
In your jQuery example you are binding to DOM elements that exist at that time. That is why you see the first fire but not the second. It is not a match for your '#test.on' selector when the code is run. What you want to do instead is use delegation:
$('#test').on('click',function() {
var ele = $(this);
if (ele.hasClass('on')) {
ele.removeClass('on').addClass('off');
} else {
ele.removeClass('off').addClass('on');
}
});
This assumes that you are doing more than just toggling classes. If you want simply toggle classes then an easier solution is to pick one as the default and use the other as a flag. For example, .on is on but without .on it's off. Then you can just use toggle:
$('#test').on('click', function() {
$(this).toggleClass('on');
});
$("#test.on")
Doesn't bind to anything. Try this:
$('#test').click(function() {
if($(this)).hasClass('off') $(this).removeClass('off').addClass('on');
else $(this).removeClass('on').addClass('off');
});
You might consider using an 'active' class instead and just toggling that, instead of have two separate on/off classes. Then you can write:
$("#test").click(function() {
$(this).toggleClass('active');
});

How we can bind event inside jquery plugin

I need to bind click event for a anchor tag which is created dynamically.
Example:
$.fn.ccfn = function(){
$(".alreadyavailabledom").click(function(){
$("<a class="dynamicallycreated"></a>");
})
//i am trying like below, but not working
$(".dynamicallycreated").click(function(){
alert("not getting alert why?")
})
}
It is written as a plugin code, i tried with on, live etc. Not working.
you should use event delegation for that
$(document).on("click",".alreadyavailabledom",function(){
//some operation
});
It helps you to attach handlers for the future elements
Use event delegation
$(document).on('click','.dynamicallycreated',function(){
alert("not getting alert why?")
})
or bind the click when creating element
$.fn.ccfn = function () {
$(".alreadyavailabledom").click(function () {
$('<a>', {
html: "anchor",
class: "dynamicallycreated",
click: function () {
alert("clicked anchor");
}
}).appendTo('#myElement');
})
}

How to apply multiple events to the same function

I'm not the best at this jquery stuff. But I'm trying to seperate the action from the function so I can apply multiple events that cause the same function. Unfortunately this isn't working. Anyone know why?
Updated Function, but still errors
$(document).ready(function() {
var $info_items = jQuery('.checkbox.has_info, .has_info');
$info_items.click(function(event) {
$(this).show_text(event);
});
// I suspect it has something to do with this initalizer of the function here
jQuery.fn.show_text = function(event){
var $info_item = jQuery(this);
$info_items.filter(function(index){
return $(".hidden_text").css("display","block");
}).not($info_item).parent().next().next().hide("slow");
$info_item.parent().next().next().show("fast");
});
});
What is e, the event? You need to name the event argument to the click() function to use it. Also, to invoke show_text such that it has a this, you need to invoke it on an element:
$info_items.click(function (event) {
// 'this' is the element in $info_items which was clicked
// invoke show_text on the element in question
$(this).show_text(event);
});
You also have an extra ) on your final }); line.
You can use jQuery bind to attach several events to a single function.
$('#whatever').bind('mouseover focus click', function() {
your_custom_function();
});
Are you looking for something like this?
var handle = function(event) {
$(event.currentTarget).show_text(event);
};
$info_items.bind('click blur', handle);

How can I bind events to the appended element?

I tried to show an error message using the jquery effect fadeTo and tried to hide the message by appending a button and using fadeout but doesn't seem to work.
What I did was:
$("#sub_error")
.fadeTo(200, 0.1, function()
{
$("#sub_error")
.html(error.join("<br/><br/>"))
.append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">')
.addClass('subboxerror')
.fadeTo(900,1);
});
$("#err_ok").click(function()
{
$("#sub_error").fadeOut("slow");
});
What am I doing wrong, could someone help me?
the #err_ok element doesn't exist at first so the .click() handler is not applied to it.
You can solve this by putting
$("#err_ok").click(function () {
$("#sub_error").fadeOut("slow");
});
in a function and call the function after creating the element in the DOM.
Edit: This should be a full solution:
$("#sub_error").fadeTo(200, 0.1, function() {
$("#sub_error")
.html(error.join("<br/><br/>"))
.append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">')
.addClass('subboxerror')
.fadeTo(900, 1);
bindEvents();
});
function bindEvents() {
$("#err_ok").click(function() {
$("#sub_error").fadeOut("slow");
});
}
There is also a "live" function that binds events to future created DOM elements too.
FWIW, there are filed tickets about fadeTo/fadeOut bugs on the JQuery bug tracker.
There are a couple of ways to do this. One, you can append the click handler to the element after it is inserted:
$("#sub_error").fadeTo(200, 0.1, function() {
$("#sub_error")
.html(error.join("<br/><br/>"))
.append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">')
.addClass('subboxerror')
.fadeTo(900, 1)
.find('#err_ok')
.click( function() {
$("#sub_error").fadeOut("slow");
});
});
Or two, you can use the live event handler so that any element with the "err_ok" id will get the click handler whenever it's created.
$('#err_ok').live('click', function() {
$('#sub_error').fadeOut('slow');
});

Categories

Resources