jquery change parent html of appended element - javascript

Please help to adjust the code:
$('parent').click(function(){
$(this).html('<button> child <button/>');
$('button').click(function(){
$(this).parent().html('some new html');
});
});
I am trying to create the dynamic action conformation with jQuery. For example user clicks DELETE (parent). DELETE then is changed to YES / NO (child button). User clicks NO and parent html is becoming DELETE again.

You can try delegated event handlers like
$(document).on('click', '.delete', function () {
$(this).replaceWith($('<span />', {
html: '<button class="yes">Yes</button><button class="no">No</button>'
}))
})
$(document).on('click', '.no', function () {
$(this).parent().replaceWith($('<button />', {
text: 'Delete',
'class': 'delete'
}))
})
$(document).on('click', '.yes', function () {
console.log('delete')
})
Demo: Fiddle

You could create a new jQuery element and then append this, you can then assign the click handler to only that element.
JSFiddle
$('#parent').click(function(){
var yesBtn = $('<button type="button">Yes</button>');
var noBtn = $('<button type="button">No</button>');
$(this).html('');
$(this).append(yesBtn);
$(this).append(noBtn);
$(yesBtn).click(function(){
event.stopPropagation();
// On yes event handler
$(this).parent().html('You clicked Yes!');
});
$(noBtn).click(function(){
event.stopPropagation();
// On no event handler
$(this).parent().html('You clicked No!');
});
});
Not the event.stopPropagation(); in the child click handlers, this will stop the event bubbling up the DOM tree and re-executing the initial parent click.

Why can't you use the JavaScript confirm popup box? That way you don't need to edit the DOM at all and lives are made easier :).
$('parent').click(function(){
var blnDelete = confirm("Do you want to delete?");
if (blnDelete) {
// Delete
} else {
// Don't Delete
}
});
http://www.w3schools.com/jsref/met_win_confirm.asp

Related

Appended element click function is not working as expected?

I attach click event to appended element by $('body').on('click'). But if I click id one two times, it also alert two times when its appended element click.
If I attach like this $('body').off().on("click"), the last appended element click can alert only (if I click id one first and then click id two,then id one appended element click can't alert).
How can I attach click event for every appended element to alert once ?
$(document).ready(function(){
test.init();
})
var test = {
init : function() {
$("#one").on("click",function(){
test.appendOne();
});
$("#two").on("click",function(){
test.appendTwo();
});
},
appendOne: function() {
$("<button class='one-after'>").append("<h1>One</h1>").appendTo("body");
$('body').on("click",'.one-after',function() {
alert("clickedOne");
});
},
appendTwo: function() {
$("<button class='two-after'>").append("<h1>Two</h1>").appendTo("body");
$('body').on("click",'.two-after',function() {
alert("clickedTwo");
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="one">One</button>
<button id="two">Two</button>
You should use selector children() which is a selector on every first level children of the body element (see documentation reference at https://api.jquery.com/children/)
So your code would become :
$('body').children().on("click")
with a slight modification, add the event directly to the appended object as below:
$("<button class='one-after'>").append("<h1>One</h1>").appendTo("body")
.on("click",function() {
alert("clickedOne"); })
you can repeat this pattern for the other one
That happen since every time you click the button, you bind a new event on the body.
You already are using event delegation, you only have to bind the event once and every new element will have an event "attached" to it. Move your event binding inside your init:
$(document).ready(function(){
test.init();
})
var test = {
init : function() {
$('body').on("click",'.one-after',function() {
alert("clickedOne");
}).on("click",'.two-after',function() {
alert("clickedTwo");
});
$("#one").on("click",function(){
test.appendOne();
});
$("#two").on("click",function(){
test.appendTwo();
});
},
appendOne: function() {
$("<button class='one-after'>").append("<h1>One</h1>").appendTo("body");
},
appendTwo: function() {
$("<button class='two-after'>").append("<h1>Two</h1>").appendTo("body");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="one">One</button>
<button id="two">Two</button>
You may simply change these two lines:
$("<button class='one-after'>").append("<h1>One</h1>").appendTo("body");
$('body').on("click",'.one-after',function() {
to (chain appendTo with on. Remove the event delegation):
$("<button class='one-after'>").append("<h1>One</h1>").appendTo("body").on("click",function() {
Instead of creating a delegation click event handler on the body you can simply add the click event to each element.
$(document).ready(function(){
test.init();
})
var test = {
init : function() {
$("#one").on("click",function(){
test.appendOne();
});
$("#two").on("click",function(){
test.appendTwo();
});
},
appendOne: function() {
$("<button class='one-after'>").append("<h1>One</h1>").appendTo("body").on("click",function() {
alert("clickedOne");
});
},
appendTwo: function() {
$("<button class='two-after'>").append("<h1>Two</h1>").appendTo("body").on("click",function() {
alert("clickedTwo");
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="one">One</button>
<button id="two">Two</button>
You can use jQuery's .one() variant:
$("#one").one("click",function(){
test.appendOne();
});
This will fire only once. http://api.jquery.com/one/

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');
})
}

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");
});

my jquery event handler for a button only works once

Im making a sort of like social network website like twitter.
When the user wants to edit a post I open a div append a textarea, a "save" button and a "cancel" button with jquery.
But the cancel button only works once, the 2nd time the user clicks for editing a post, the cancel button doesn't work anymore.
$(function()
{
function edit(chirp_id)
{
var div1 = $('<div></div>');
div1.addClass('thumb2');
div1.attr('id', chirp_id);
$(div1).css('display','none');
if($(div1).is(':visible'))
{
return;
}
else
{
// Before the 'cancel' button I append the textarea and 'save' button
var cancel = $('<button></button>');
cancel.attr("id","cancelEdit");
cancel.text("Cancel");
cancel.addClass('button');
cancel.appendTo(div2);
$('#cancelEdit').click(function()
{
$(div1).fadeOut("slow");
});
}
my_edit = edit;
});
I call my function with javascript
function edit_chirp(chirp_id)
{
my_edit(chirp_id);
}
Try this .. bind event with dom not with ID ..
$(function () {
function edit(chirp_id) {
var div1 = $('<div></div>');
div1.addClass('thumb2');
div1.attr('id', chirp_id);
$(div1).css('display', 'none');
if ($(div1).is(':visible')) {
return;
} else {
//Before the 'cancel' button I append the textarea and the 'save' button
var cancel = $('<button></button>');
cancel.attr("id", "cancelEdit");
cancel.text("Cancel");
cancel.addClass('button');
cancel.appendTo(div2);
cancel.click(function () {
$(div1).fadeOut("slow");
});
}
my_edit = edit;
});
Better use delegates using .on event handler because your div1 is created dynamically
$(document).on('click', '#cancelEdit', function () {
$(div1).fadeOut("slow");
});
Missing to close edit function
probably to do with closure. try:
cancel.click(function (event) {
$(event.target).closest(".thumb2").fadeOut("slow");
});

Restore page content and retain event listeners

How would you "save" a page somewhere (on the client), then restore it, with all its event listeners intact?
I have a sample at http://jsfiddle.net/KellyCline/Fhd55/ that demonstrates how I create a "page", save it and go to a "next" page on a button click, and then restore the first page on another button click, but now the first page's click listeners are gone.
I understand that this is due to the serialization that html() performs, so, obviously, that's what I am doing wrong, but what I'd like is a clue to doing it right.
This is the code:
var history = [];
$(document).ready(function () {
var page1 = $(document.createElement('div'))
.attr({
'id': 'Page 1'
}).append("Page ONE text");
var nextButton = $(document.createElement('button'));
nextButton.append('NEXT');
nextButton.on('click', function () {
CreateNextPage();
});
page1.append(nextButton);
$("#content").append(page1);
});
function CreateNextPage() {
history.push( $("#content").html( ) );
$("#content").html( 'Click Me!');
var page1 = $(document.createElement('div'))
.attr({
'id': 'Page 2'
}).append("Page TWO text");
var nextButton = $(document.createElement('button'));
nextButton.append('NEXT');
nextButton.on('click', function () {
CreateNextPage();
});
var prevButton = $(document.createElement('button'));
prevButton.append('PREVIOUS');
prevButton.on('click', function () {
GoBack();
});
page1.append(nextButton);
page1.append(prevButton);
$("#content").append(page1);
}
function GoBack() {
$("#content").html( history[history.length - 1]);
history.pop( );
}
and this is the html:
Click Me!
I think this is best solved via event delegation. Basically, you encapsulate content that you know you are going to refresh within a wrapper element and bind your listeners to that. The jQuery .on() method allows you to pass a selector string as a filter and will only trigger the handler if the originating element matches. Give your buttons a class or something to get a handle on them and then bind them up above. This article has some examples.
$( '#content' ).on( 'click', 'button.next', createNextPage )
for instance.

Categories

Resources