JQuery duplicate events when create element and set events to class - javascript

When I add an item using click event and exists another element with the same class the event is duplicated.
$(".add-first").on("click", function() {
var firstContainer='<div class="second-container"><button class="add-second">add second</button></div>';
$(this).closest(".first-container").append(firstContainer);
$(".add-second").on("click", function() {
$(this).closest(".second-container").append("<br>example");
});
});
$(".add-second").on("click", function() {
$(this).closest(".second-container").append("<br>example");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first-container">
<button class="add-first">add first</button>
<div class="second-container"><button class="add-second">add second</button></div>
</div>
Then when I press one click in add first this duplicate event in each button add second, then when I press click on the second button it has some events, the issue is duplicated event.

Try to implement event-delegation instead of binding an event event every time when you are creating a new button,
$(".add-first").on("click", function() {
var firstContainer = '<div class="second-container"><button class="add-second">add second</button></div>';
$(this).closest(".first-container").append(firstContainer);
});
$(".first-container").on("click", ".add-second", function() {
$(this).closest(".second-container").append("<br>example");
});
DEMO

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/

Turn on() event back after apply off

How can I turn an on('click') event back on after I apply event off()?
$('#btn-aluno').on('click', function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').off();
});
$('#btn-familiar').on('click', function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').off();
});
new-step-email-familiar and new-step-email-aluno = <input>
btn-aluno and btn-familiar = <span> (used as a button)
Instead of turning off the event listener, you could do the same thing by using event delegation,
$(document).on('click',"#btn-aluno.active", function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').removeClass("active");
});
$(document).on('click',"#btn-familiar.active", function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').removeClass("active");
});
And whenever you want to activate the event listeners, just add the class active to the relevant elements. Also in the place of document try to use any closest static parent of the element on which the event gonna be bound.
As per your requirement, you have edit your logic like below,
$(document).on('click',"#btn-aluno.active", function() {
$('.new-step-email-aluno').toggle();
$('#btn-familiar').toggleClass("active");
});
$(document).on('click',"#btn-familiar.active", function() {
$('.new-step-email-familiar').toggle();
$('#btn-aluno').toggleClass("active");
});
DEMO

Duplicated button doesn't work click();

I have the code below:
$(document).ready(function(){
var counter = 0;
$("button").click(function() {
$('body').append("<button>generate new element "+(counter++)+"</button>")
});
});
JSFiddle
When you click duplicated button, it won't duplicate another button again besides the original button only works.
Why cannot listen this event to duplicated buttons?
EDITED:
//Click button event DELEGATION
$(document).on("click",".choice", function() {
var userChoice = $(this).attr("value");
//EXTERNAL SPAGUETTHI CODE
};
Need to grab "value" of this button when it's clicked.
You need delegation: catching the clicks on the parent but only those that were made on button elements. $("button") selects the existing buttons on the page, $(document) (you can replace document with your button container) will select the container and by using $(document).click("button", ...) you delegate the clicks on the buttons.
$(document).ready(function() {
var counter = 0;
$(document).click("button", function(e) {
var value = $(e.target).attr("data-value"); // or .data("value")
alert(value);
$('body').append("<button data-value=\"" + ++counter + "\">generate new element " + counter + "</button>")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-value="initial-button">generate new element</button>
Here are some other similar answers I posted:
Direct and delegated events
Delete dynamic elements
Function not working second time

Attach one time event to dynamically added elements

I have a web page where there is a button, when the button is clicked a Textbox is added to a DIV. Here is a similar code that I'm working with:
HTML
<button class="addText">Add Textbox</button>
<div class="textCont">
</div>
JavaScript
$(document).on("click", ".addText", function() {
var textarea = $("<textarea/>", {class: "newText"});
$(".textCont").append(textarea);
});
$(document).one("focus", ".newText", function() {
alert("Great");
});
Fiddle: http://jsfiddle.net/ErRohitAgg/g3A7T/
What I'm trying to do is to show an alert for first focus of every textbox that is added. But, instead the focus event is executing only once, and not once for each Textbox.
Is there any way the event behaves according to the functionality I need??
Add the event handler to each textarea instead
$(document).on("click", ".addText", function() {
$("<textarea/>", {
'class': 'newText',
one : {
focus: function() {
alert("Great");
}
}
}).appendTo(".textCont");
});
FIDDLE
I would rather do it by adding newclass on first focus:
$(document).on("focus", ".newText", function() {
if(!$(this).hasClass('focused')){
$(this).addClass('focused')
alert("Great");
}});
Working Demo

jquery Trigger delegate event for nth element onload

In my page i have 10 images all are have the same class "select-option"
My html is
<div class="select-option swatch-wrapper selected" data-name="A Very Scary Monster" data-value="a-very-scary-monster">
<a href="#" style="width:120px;height:120px;" title="" class="swatch-anchor">
<img src="image ur1" alt="" class="" width="120" height="120"></a></div>
Similarly i have 10 images.
function init_swatches() {
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
}
I want to preselect the 3rd image. Thew selected image has the class 'selected', others are not. How do i trigger this for 3rd or 4th element on load. How to manually trigger this delegate event for nth element.
Here i want to trigger this click event
First bind click event on anchor tag
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
then manuaaly trigger click event of 3rd element like given below
$('.select-option a').eq(2).click()
or
$('.select-option a').eq(2).trigger("click")
you can use jquery's trigger method
function init_swatches() {
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
$('.select-option a').eq(2).trigger("click");
}
I'm not sure you're wanting to trigger the click event, but rather use the click event to set the selected class. Something like this might be more suitable:
$(document).ready(function() {
$(document).delegate(".select-option", "click", function(e) {
if ($(this).hasClass("selected") == false) {
$(".select-option.selected").removeClass("selected");
$(this).addClass("selected");
}
});
selectNthImage(3);
});
function selectNthImage(n) {
$(".select-option.selected").removeClass("selected");
$(".select-option:nth-child(" + n + ")").addClass("selected");
};
See a jsfiddle here

Categories

Resources