Second jQuery button click isn't firing - javascript

I am trying to do something ostensibly simple in jsfiddle and it is not working. Essentially I have an h1 html tag with class "me" and a button with class "poo". The first click works and my css color changes, however the second click does not work?
$(".poo").click(function(e){
e.preventDefault();
$(".me").css("color","green");
var haha = $("<button>Click Me!!!</button>");
$(this).after(haha);
$(haha).addClass("changer");
$(this).hide();
});
$(".changer").click(function(e){
e.preventDefault();
$(".me").css("color","black");
$(this).hide();
});

Bind the second click to the parent element:
$(document).on('click', '.changer', function() {
//function here
});

The changer click handler is bound before the element exists. Try using the $.on method instead.
http://api.jquery.com/on/
$('body').on('click', '.changer', function() {...})
This works because the event handler is bound to the document body, which already exists on the page. When there is a click anywhere in the body, jQuery will check if the clicked element matches the selector .changer and execute the callback if so.
Alternatively, you could just bind the $('.changer').click event within the first callback.

Update fiddle: http://jsfiddle.net/0yodg7gb/7/
$(".poo").click(function(e){
e.preventDefault();
$(".me").css("color","green");
var haha = $("<button>Click Me!!!</button>").addClass('changer');
$(this).after(haha);
$(haha).addClass("changer");
$(this).hide();
bindClick();
});
function bindClick(){
$(".changer").bind('click',function(e){
e.preventDefault();
$(".me").css("color","black");
$(this).hide();
});
}

Related

listening event after id changing

I want to modify an Id of button 'B' when button 'A' is clicked, and listen to the click event of of 'B' using Jquery but my code doesn't work,
this is an example of my code:
$(function() {
$(".nuttonA").click(
function() {
$("#buttonB").attr("id","notButtonB");
});
$("#notButtonB").click(function(){
console.log(" notButtonB is clicked "); //show nothing
});
});
i think you need event delegation. try this:
$(function() {
$(".buttonA").click(
function() {
$("#buttonB").attr("id","notButtonB");
});
$( "body" ).on( "click", "#notButtonB",function(){
console.log(" notButtonB is clicked "); //show nothing
});
});
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using delegated-events approach when manipulation properties.
General Syntax
$(document).on('event','selector',callback_function)
Example
$(document).on('click', ".nuttonA", function(){
$("#buttonB").attr("id","notButtonB");
});
$(document).on('click', "#notButtonB", function(){
//Your code
});
In place of document you should use closest static container.

Jquery appending with styling and functions

i appending buttons with some IDs and i use those IDs to make on click stuff
when it appending didn't take button() effect
and on click it don't take the function that I created it for this button id
$("button#edit-doc").each(function() {
$(this).button();
$(this).on("click", function(){
alert("clicked");
});
});
append button
$("#append").on("click", function(){
$('div#container').append("<button id='edit-doc'> Edit </button>");
});
container
<div id="container"></div>
This seems to be what you're after:
function handler() { alert('clicked'); }
$("#append").on("click", appendButton);
function appendButton(){
$('#container').append(function() {
return $("<button id='edit-doc'> Edit </button>").on("click", handler);
})
}
http://jsfiddle.net/PF8xY/
See jQuery how to bind onclick event to dynamically added HTML element for more information on this behavior.
$(document).on("click", "#selector", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/
The first code-block attaches an event listner to all buttons with class='edit-doc', use classes instead of an id since an id's name may only exist once per page. So I was saying, when your browser reaches this code an event listner is added to all available buttons in your document at that moment. It doesn't add an event listner to buttons you will be adding later onclick of some element, because it doesn't know. You will have to explicitly execute the code again for the buttons that you append. But what you don't want is to add a new event listner to the original buttons, causing two events being called.
Something like:
// Load all buttons with class=edit-doc and add event listner
$(function() {
$("button.edit-doc").button().on("click", function(){
alert("clicked");
});
});
// Append button if button with id=append is clicked
$("#append").on("click", function(){
var button = $.parseHTML("<button class='edit-doc'>Edit</button>");
$('div#container').append(button);
$(button).button().on("click", function(){
alert("clicked");
});
});
Working example:
http://jsfiddle.net/RC9Vg/

jQuery event handler not working on object inserted with jQuery

<button id="first">Click me first</button>
$('#first').click(function(){
$('body').append('<button id="second">Now click me</button>');
});
$('#second').click(function(){
$(this).hide();
});
jsFiddle
When #first is clicked, #second gets appended. When #second gets clicked, I want it to
hide itself.
Why isn't this working?
When you initiate this event handler
$('#second').click(function(){
$(this).hide();
});
'#second' element doesn't exist yet. Later you add the element but that element doesn't initiated with any event handler.
You can try this
$('#first').click(function(){
$('body').append('<button id="second">Now click me</button>');
// event handler will attached for already exist '#second' element
// attach event if only #second doesn't have event yet
if(!($('#second').data('events') != null && $('#second').data('events').click != undefined && $('#second').data('events').click.length == 1))
$('#second').click(function(){
$(this).hide();
});
});
Use jQuery on function.
$(document).on('click', '#second', function(){
$(this).hide();
});
It's not working because $('#second') does not match anything when it gets executed.
Try assigning the click handler to the element before adding to the DOM:
$('#first').click(function(){
var $button = $('<button id="second">Now click me</button>');
$button.click(function() {
// handler
});
$('body').append($button);
});
You can also use on to delegate the event if you need to 'attach' the event handler before the element exists.
use on()
$(document).on('click', '#second', function(){
$(this).hide();
})
refer
http://api.jquery.com/on/
try
$('#second').on("click",function(){
$(this).hide();
});
To clarify why your code is not working : During the definition of the event handling of #second that div doesn't exist. You should define the event handling after you are sure that the DOM element $("#second") is present in the page.

Image not clickable after loaded via AJAX

I have a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks

Why doesn't this jQuery code work?

I have this jQuery code:
$(".topic_form").hide();
$("#edit_topics_link").click(function(e) {
e.preventDefault();
$(".topic_form").show();
$(this).hide();
$("<a href='#' id='done_link'>Done</a>").insertBefore(".topic_form");
});
$("#done_link").click(function(e) {
e.preventDefault();
$(this).remove();
$(".topic_form").hide();
$("#edit_topics_link").show();
});
The first half of the code does this: it hides a form when the page loads. Then when you click a link, it shows the form, hides the clicked link, and adds a new link. This works 100% fine.
The 2nd half of the code doesn't work. When you click the newly added link, it should remove it, show the old link, and re-hide the form. Nothing happens when I click the newly added link. Why is this? How can I fix it?
Because the element to which you're attaching the click-handler to doesn't exist at the time of the document's loading, there are no events attached. You should be able to use live() to fix this:
$("#done_link").live('click', function(e) {
e.preventDefault();
$(this).remove();
$(".topic_form").hide();
$("#edit_topics_link").show();
});
The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants.
You could also use delegate() on the ancestor element of the #done_link element:
$("#parentElementSelector').delegate('#done_link', 'click', function(e) {
e.preventDefault();
$(this).remove();
$(".topic_form").hide();
$("#edit_topics_link").show();
});
References:
live().
delegate().
The reason it doesn't work is that when you call the second part of the script the link doesn't exist yet. There are 2 ways to solve it. Either move the second part into the first part. That way the attachment of the event handler happens when the link exists:
$(".topic_form").hide();
$("#edit_topics_link").click(function(e) {
e.preventDefault();
$(".topic_form").show();
$(this).hide();
$("<a href='#' id='done_link'>Done</a>").insertBefore(".topic_form")
.click(function(e) {
e.preventDefault();
$(this).remove();
$(".topic_form").hide();
$("#edit_topics_link").show();
});
});
Or use the live method to assign the handler. The live method will watch the dom and whenever something with the selector you specified (in this case .topic_form) appears it will attach the event to it:
$(".topic_form").hide();
$("#edit_topics_link").click(function(e) {
e.preventDefault();
$(".topic_form").show();
$(this).hide();
$("<a href='#' id='done_link'>Done</a>").insertBefore(".topic_form");
});
$("#done_link").live('click', function(e) {
e.preventDefault();
$(this).remove();
$(".topic_form").hide();
$("#edit_topics_link").show();
});

Categories

Resources