Click doesn't work correctly after append - javascript

My code generates an infinite scroll but when I touch each one it appears alerts many times and that isn't right.
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
var variable = "<div class='corazon'>hi</div>";
$(".hola").append(variable);
$('.corazon').on('click', function() {
alert("hola");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Thank you.

$('.corazon').on('click', function() {
alert("hola");
});
You're adding a new click listener to all the elements with class "corazon" every time you reach the scroll limit.
You should add the click listener on the created element instead of performing a new query $(".corazon") .
Try this:
var variable = $("<div class='corazon'>hi</div>");
$(".hola").append(variable);
variable.on('click', function() {
alert("hola");
});

This has already been asked, use jquery clone to clone an existing element with listener.
.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )
Provide both with true.
And yes
$('.corazon').on('click', function(){
alert("hola");
});
Should not be in the scoll listener
Full documentation: https://api.jquery.com/clone/

Instead of:
$('.corazon').on('click', function() {
you shuld have:
$(variable ).on('click', function() {
Now the clickhandler is only added to the new element.

Related

Adding an on event to an e.currentTarget?

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.

jQuery doesn't recognize a class change

Ok, I have a edit button, when I press on it, it changes to "done" button.
It's all done by jQuery.
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.attr('class', 'icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});
When I press on a "edit" (".icon-pencil") button, its classes change to .icon-ok-sign (I can see in chrome console),
but when I click on it, no alert shown.
When I create a <span class="icon-ok-sign">press</span> and press on it, a alert displays.
How to solve it?
Try using $( document ).on( "click", ".icon-ok-sign", function() {...
Thats because you can not register click-events for future elements, you have to do it like this:
$(document).on('click', '.icon-ok-sign', function() {
alert('hey');
});
This method provides a means to attach delegated event handlers to the
document element of a page, which simplifies the use of event handlers
when content is dynamically added to a page.
Use following script:
$(document).on('click','.icon-ok-sign',function(){
alert("hey");
});
Try this:
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.removeAttr('class').addClass('icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});

Jquery append input element and send data from that input element

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/

How to dynamically add html elements with jquery?

My goal is to have one element on initial load, this element should have id="something_O", when a add link is clicked, underneath already existing element, new, the same html element should be added,not with id="something_o", but with id="something_1", or last element + 1, to be specific. The user should be able to add these elements infinitely. When the user clicks deleted, element should disappear.
Any ideas?
Here is prepared fiddle for easier help...
var counter = 1;
$('.AddEl').live('click', function () {
var el = $('#element_1').clone().attr('id', 'element_' + ++counter).appendTo('body');
});
$('.RemoveEl').live('click', function () {
var el = $(this).parents('.elem')
if (el.get(0).id !== 'element_1') el.remove();
});
Check this here
One means to do this is:
$(document).ready(function() {
$('body').on('click', '.AddEl', function() {
$('.actions:first')
.parent()
.clone()
.attr('id', 'element_' + $('.actions').length)
.insertAfter($('.actions:last').parent());
});
$('body').on('click', '.RemoveEl', function() {
$(this).closest('.actions').parent().remove();
});
});
JS Fiddle demo.
Please note that I've amended your html so that the first element to be cloned is now id="element_0", and targeted that, and all subsequently-created elements, with the CSS selector:
div[id^=element] {
/* css */
}
This could be simplified, but these are simply my first thoughts.
Edited to offer a slightly improved version, in that the initial addition is slightly, or seems a little, more concise, and also features a means to prevent duplicate ids being generated if elements are added/removed:
$(document).ready(function() {
$('body').on('click', '.AddEl', function() {
var $elems = $('.actions').parent();
$elems
.first()
.clone()
.insertAfter($elems.last());
$('div[id^="element_"]').each(
function(i){
$(this).attr('id','element_' + i);
});
});
$('body').on('click', '.RemoveEl', function() {
$(this).closest('.actions').parent().remove();
});
});
JS Fiddle demo.
I just overwrite to your code.
You can try this, may something you want.
http://jsfiddle.net/kongkannika/QeSPP/34/

optimization jQuery for IE

I have function:
function doBlamingItem($cell, showEditMark) {
$cell.hover(function () {
$cell.toggleClass('clickable-cell', showEditMark).toggleClass('editing-cell', !showEditMark);
}, function() {
$cell.removeClass('clickable-cell editing-cell');
} );};
in $(document).ready() I apply this function for some cells in my table (~500) and when I move my mouse upon it - in FF or Chrome all is okay, but IE7-9 starts lagging and I don't know how to fix it :(
and code from $(document).ready():
var i = firstRowOnPage();
while (table.GetRow(i) != null) {
if (condition) {
var row = table.GetRow(i);
var elementInCellId = column.fieldName + '_' + rowKey;
var $cell = $(row.cells[realIndex]).attr('id',elementInCellId);
doBlamingItem($cell, true);
setClickable(editInfo, $cell);
}
i++;
}
I use doBlamingItem for every cell because for some of them showEditMark=true, for other showEditMark=false
Your code basically (1) finds those ~500 elements, (2) iterates them to (3) assign hover events (consisting of mouseenter and mouseleave). Have you heard of delegated events?
The setup time is virtually none (only 2 event handlers, instead of 1000 are registered). No elements are selected and traversed.
(function($, undefined){
// if you want it global
var showEditMark = true;
// otherwise save that state to some element's data()
$(function(){
$(document.body).delegate('.your-table-selector td', {
mousenter: function(e){
$(this)
.toggleClass('clickable-cell', showEditMark)
.toggleClass('editing-cell', !showEditMark);
},
mouseleave: function(e){
$(this).removeClass('clickable-cell editing-cell');
}
});
});
})(jQuery);
Thanks to all who answered my question, but as I realized problem was not in javascript... My page has big DOM-tree of elements and many CSS-styles, so IE has problems with rendering of it

Categories

Resources