$('#A').click(function () {
$('#A1').prepend('<div class="AcL" id=' + i + '>Hello<span class="RmMe" id="' + i + '" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').click(function () {
alert("OK");
});
<div id="A1"></div>
Any idea why the click is not working?
You need to use .delegate() or .live() because you are attempting to bind a handler to an element that does not yet exist.
$('#A').click(function() {
$('#A1').prepend('<div class="AcL" id='+i+'>Hello<span class="RmMe" id="'+i+'" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').live('click', function() { alert( 'OK' ); });
Try that.
EDIT:
However, should you be using jQuery 1.7+, the .on method is the preferred approach: See post from xdazz
$('.RmMe').on('click', function () {
alert("OK");
});
Good luck!
Try use .onDoc.
$('.RmMe').on('click', function () {
alert("OK");
});
You have to use
$('.RmMe').on("click",function(){
alert("OK");
});
because this element does not exist when your DOM is created, it is inserted afterwards and you cannot bind click to the element which does not exist. .live adds an event listener for you, which makes it easy to achieve the task you want.
Related
I apologise for the description if it's not fitting. It was hard to describe what's going on.
I have set up a jsFiddle here.
function addNewForm() {
$('body').html(function () { //display log in form
return "<input type=\"text\" placeholder=\"Word or Phrase\" id=\"prompt\" />\n" +
"<textarea id=\"answer\" placeholder=\"Answer text\"></textarea>\n" +
"<input type=\"button\" id=\"addnew\" value=\"Add This!\" />\n" +
"<p> </p>";
});
}
$("#addnew").click(function () {
$("p").html("ADD NEW CLICKED<br />");
});
$("a").click(function () {
addNewForm();
});
Is my syntax correct? For some reason, $("#addnew").click works when generated outside of its own function but the button stops working since I have tidied my code and placed it within its own function. Is there a reason that jQuery may not recognise an element that has been created through a function?
Cheers!
When you are trying to attach an onclick event handler onto #addnew, the element doesn't exist at that time.
You need to attach it when you add the form into DOM or use delegated events
$(document).on("click", "#addnew", function () {
$("p").html("ADD NEW CLICKED<br />");
});
You would probably also like to prevent the page from reloading, when you click the <a> link
$("a").click(function (e) {
e.preventDefault();
addNewForm();
});
Fixed jsfiddle: https://jsfiddle.net/5rb6koog/
The solution is here :
https://jsfiddle.net/wvepd6ge/7/
When you add your button, you need to attach the event like this :
function addNewClicked() {
$('.result').html("ADD NEW CLICKED<br/>");
}
$("a").click(function () {
addNewForm();
$("#addnew").click(function () {
addNewClicked();
});
});
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");
}
});
});
I am trying to add a mouseover function to dynamically created elements using jquery
$('#schools').append(
'<div class="mediumListIconTextItem" onclick="javascript:showSchoolReport(\'' + $.trim(this.id) + '\',\'' + $.trim(this.companyID) + '\',\'' + $.trim(this.companyCode) + '\',\'' + $.trim(this.companyName) + '\');" style="padding-left: 30px;margin: 5px;">' + '<div class="icon-newspaper mediumListIconTextItem-Image"></div>' + '<div class="mediumListIconTextItem-Detail">' + '<h6 id="header" style="max-width:100px; overflow:hidden;">' + this.name + ' - ' + this.companyName + '</h6></div></div>');
code for mouseover effect
$(document).ready(function (e) {
$(".mediumListIconTextItem").mouseover(function () {
alert($(this.name));
});
});
$(".mediumListIconTextItem").on("mouseover", function () {
alert('mouseover works!!!!!!!!!');
});
});
none of the above function for mouseover works. whats wrong with my code. suggest a solution
This is the case called event delegation. In here you can't bind the direct event to a dynamically created elem. try this as below:
$(document).on("mouseover", ".mediumListIconTextItem", function() {
alert('mouseover works!!!!!!!!!');
});
You're almost there, you have to use on but in a different form. You're using direct event but you need to use delegated events
$('#schools').on("mouseover", ".mediumListIconTextItem", function() { .. }
For more details check section Direct and delegated events
Use on() for dynamically added elements like,
$(document).on("mouseover", ".mediumListIconTextItem", function() {
alert('mouseover works!!!!!!!!!');
});
Use .on()
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.
$(document).on("mouseover", ".mediumListIconTextItem", function() { .code here. }
better use
$("#schools").on("mouseover", ".mediumListIconTextItem", function() { .code here. }
Syntax
$( elements ).on( events, selector, data, handler );
Use event delegation :
$('#schools').on('mouseover', '.mediumListIconTextItem', function(){ ... })
For a clear and short explanation of how event delegation works, see this question :
Direct vs. Delegated - jQuery .on()
Is there a way to keep checking an object if it's checked after it is replaced
this illustrates the problem I'm having
http://jsfiddle.net/nr6eA/
once the element is replaced the change function is not triggered again, while I have a pretty good idea why this is happening, I'm not sure how to solve this.
I've got a lot of checkboxes, and adding a script to each when they are replaced doesn't seem to be the best idea.
Is there a way of re-initializing the jquery function ofter an ajax update?
You need event delegation. For that purpose you can use on() with jQuery 1.7+ like below:
For .on():
$(document).ready(function() {
$('#f').on('change', ' input:checkbox', function() {
$('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
$(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
});
});
But, your fiddle shows jQuery 1.6.2. In that case you can use live() or delegate().
For live():
$(document).ready(function() {
$('#f input:checkbox').live('change', function() {
$('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
$(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
});
});
And for delegate():
$(document).ready(function() {
$('#f').delegate('input:checkbox', 'change', function() {
$('#textbox1').val($(this).attr('id') + " " + $(this).is(':checked'));
$(this).replaceWith('<input type="checkbox" id="checkbox1" class="ichange"/>')
});
});
But it would be better if you can use .on() with jQuery 1.7+.
I have this simple HTML code:
<div id="new_gallery">
<p id="add_gallery">Add new gallery</p>
</div>
and jQuery code:
<script>
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
});
$("#create_new_gallery").on('click', function(){
alert('1');
});
</script>
First function is working, but second one is not. I need to create new input element, send data via ajax, and then delete the input element and append a p element once again. How can I do this?
When the second statement runs, the element #create_new_gallery does not exist yet so it does nothing.
You can do the binding to the click event after you created the element for instance, this ensures the element exists in the DOM:
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name="new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function() {
alert('1');
});
});
DEMO
Here is a little bit more optimized version. It's a bit non-sense to append an element and have to re-query for it (event though querying by id is the fastest method. Besides, it's best to use the chaining capabilities of jQuery afterall:
$("#add_gallery").click(function() {
var $gallery = $("#new_gallery");
$('<input name="new_gallery" />').appendTo($gallery);
$('Add')
.on('click', function() {
alert('1');
})
.appendTo($gallery);
$(this).remove();
});
DEMO
#create_new_gallery doesn't exist when you bind its click event.
Here is what your code should look like:
$("#add_gallery").click(function() {
var newG = $("#new_gallery");
$('<input name"new_gallery" />').appendTo(newG);
$('Add').appendTo(newG).on('click',
function() {
alert('1');
});
$(this).remove();
});
Notice that getting $("#new_gallery") into a variable avoid to look for it twice.
$(document).ready(function () {
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function(){
alert('1');
});
});
});
DEMO: http://jsfiddle.net/39E4s/2/
Try live to handle the events fired for elements added after the page has loaded.
$("#create_new_gallery").live('click', function(){
alert('1');
});
http://api.jquery.com/live/