Why doesn't this jQuery code work? - javascript

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

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.

Click action doesn't work with dialog

I have problem with dialog and click action.
$("a[data-file]").click(function(e){
e.preventDefault();
getXML($(this).attr('data-file'));
});
This code works correctly with constant anchors but doesn't works with anchors in jQuery dialog. I have tried also:
$("document").on( "click", "a[data-file]", function() {
e.preventDefault();
getXML($(this).attr('data-file'));
});
But it doesn't work. How I should resolve this issue?
You have wrapped document in quotes, which looks for element with tagname document. which do not exists.
You need to use document object here while using event delegation:
$(document).on( "click", "a[data-file]", function() {
e.preventDefault();
getXML($(this).attr('data-file'));
});

Second jQuery button click isn't firing

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

Using "on" for response for desired elements only:

JS Fiddle Link
I am dynamically adding some elements and my div looks like:
<div class="knock" href="#">
<!-- Do Something if links are not clicked -->
Google
Facebook
</div>
And my on script is:
$(".knock").on("click", function(){
console.log("Link not clicked");
alert("Link not Clicked");
});
My Problem, I do not want to fire the alert when the links are clicked. Is there a way out?
You can write anchor tag event and stop event Propagation of the event to upper DOM elements so that alert only comes up when the div is actually clicked, but not when some anchor tag inside div is clicked:
$(".knock").on('click',"a",function(event){
event.stopPropagation();
})
FIDDLE:
http://jsfiddle.net/hbac7vbh/2/
event.stopPropagation:
The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.
See details here on jquery official page
Just determine if the a is clicked based on the event that is passed.
Updated Example
$(".knock").on("click", function(e){
if(!$(e.target).is('a')){
console.log("Link not clicked");
alert("Link not Clicked");
}
});
Add this to your js:
$(".knock a").on("click", function(e) {
return false;
});
Why not add another method as
$('a').on('click',function(e){
e.stopPropagation();
});
This will stop porpagation of the chaininvocation of events on parent elements.
See updated Fiddle

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

Categories

Resources