Attach one time event to dynamically added elements - javascript

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

Related

JQuery duplicate events when create element and set events to class

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

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

Jquery - Differentiate between 'click' and 'focus' on same input when using both

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.
The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:
HTML:
<body>
<input type="textbox" name="tb1" class="input1"></input>
<label> box 1 </label>
<input type="textbox" name="tb2" class="input2"></input>
<label> box 2 </label>
</body>
JQuery
$(function () {
$('.input2').click(function() {
alert("click");
});
$('.input2').focus(function() {
alert("focus");
});
});
JSFiddle: http://jsfiddle.net/XALSn/2/
You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.
Thanks in advance for any advice.
How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.
I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:
$(function () {
$('.input2').on("click focus blur", function(e) {
e.stopPropagation();
if(e.type=="click"){
if($(this).data("justfocussed")){
$(this).data("justfocussed",false);
} else {
//I have been clicked on whilst in focus
console.log("click");
}
} else if(e.type=="focus"){
//I have been focussed on (either by clicking on whilst blurred or by tabbing to)
console.log("focus");
$(this).data("justfocussed",true);
} else {
//I no longer have focus
console.log("blur");
$(this).data("justfocussed",false);
}
});
});
http://jsfiddle.net/XALSn/12/
This probably won't be the best answer, but this is a way of doing it. I would suggest adding tab indexes to your inputs and firing the focus event when you blur from another input.
I've added that to this fiddle:
http://jsfiddle.net/XALSn/9/
$(function () {
$('.input2').click(function(e) {
alert("click");
e.preventDefault();
});
});
$('input').blur(function(){
$('input').focus(function() {
alert("focus");
});
});
You can use one thing I am using very often in JS
var doSomething = true;
$(function () {
$('.input2').click(function(e) {
if (doSomething) {
// do something :)
}
doSomething = false;
});
$('.input2').focus(function() {
if (doSomething) {
// do something :)
}
doSomething = false;
});
});
But You have to change value of doSomething on mouseout or foucs over etc. :)
$(function () {
var hasFocus = false;
$("body")
.off()
.on({
click : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("click");
}
},
focus : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("focus");
}
}
},".input2");
});
try setting a flag hasFocus and act accordingly
http://jsfiddle.net/AEVTQ/2/
just add e.preventDefault() on the click event
$(function () {
$('.input2').click(function(e) {
console.log("click");
e.preventDefault();
e.stopPropagation();
});
$('.input2').focus(function() {
console.log("focus");
});
});
If I understand your question right, the e.prevnetDefault() will prevent the browser from automatically focusing on click. Then you can do something different with the click than would with the focus

Capturing an event with jquery

I got a double event to manage. The two events are both "click" and they're handled with jquery. The html is the following:
<div class="siteMap" style="width:23%;">
<h5>Divisione Anticontraffazione</h5>
<span class="menufooter">
<span class="link1">Introduzione</span><br>
<span class="link2">Filosofia</span><br>
<span class="link3">Negozio online</span></span><br>
</div>
Then i have my click events which fires inside the menufooter span and inside every single link span. The code is like this:
$(document).ready(function() {
$('span.menufooter').click(function() {
//my code here
});
$("span.link1").click(function() {
//my code here
});
});
I need an event capturing action, the click on the span menufooter has to fire the event before the click on the span link1 fires. At this point, none of the two events is firing. Any hint?
How about only fire event on .menufooter
$(document).ready(function() {
$('span.menufooter').click(function(e) {
//my code here 1
// Capture Event Propagation
if ( $("span .link1").find(e.target).length>0 ){
//my code here 2
};
});
});
http://jsfiddle.net/9QLtG/
You could prevent the click from bubbling, and then trigger the click on the parent element so whatever is in that handler executes first (unless it's async)
$(document).ready(function () {
$('.menufooter').click(function () {
// fires before ....
});
$("span.link1").click(function (e) {
e.stopPropagation();
$('.menufooter').trigger('click');
// .... this fires, as it's triggered above
});
});
FIDDLE
I would have 1 click listener that listens to the wrapper. You can check the event's target to see if they actually clicked on a link and run code accordingly.
For example:
$(document).ready(function() {
$('.container').click(function(e) {
// Perform action when they clicked in the main wrapper,
// regardless of whether or not it was a link.
console.log("I clicked in the wrapper...");
if ($(e.target).hasClass('link')) {
// Perform action if they clicked on a link.
console.log("...but more specifically, on a link.");
}
});
});
Here's a fiddle that demonstrates this: http://jsfiddle.net/WaYFr/
Try this event.stopPropagation();
$("span.link1").click(function(event) {
event.stopPropagation();
...
});

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

Categories

Resources