1

in my code i have applied click event on an img tag and it is not working at all but when i applied the same code for onclick on same tag it started working perfectly . following is the code :-

   // closing div with click on img .
   $('img.close_url').click(function(){
       alert('close');
       $('div.urlResult').hide();
       $('input#hidden_url_title').val();
       $('input#hidden_url_content').val();
       $('input#hidden_is_url').val(0);
   });

   // closing div by applying onclick on img tag 
   function closeUrl()
   {
       $('div.urlResult').hide();
       $('input#hidden_url_title').val();
       $('input#hidden_url_content').val();
       $('input#hidden_is_url').val(0);
    }

Html:

//content to be loaded in #results element

var content = '<div class = "extracted_url">'+ inc_image +'<div class="extracted_content"><h4><a href="'+extracted_url+'" target="_blank">'+data.title+'</a><img class = "close_url"  src ="'+IMAGE_PATH+'/cross-grey.png"/></h4><p>'+data.content+'</p><div class="thumb_sel"><span class="prev_thumb" id="thumb_prev">&nbsp;</span><span class="next_thumb" id="thumb_next">&nbsp;</span> </div><span class="small_text" id="total_imgs">'+img_arr_pos+' of '+total_images+'</span><span class="small_text">&nbsp;&nbsp;Choose a Thumbnail</span></div></div>';

/* above is the html that I am adding with javascript function . And this is not inside .ready */

Always_a_learner
  • 4,585
  • 13
  • 63
  • 112

1 Answers1

1

Sounds like you are running the .click code before the <a> tag is in the DOM (i.e. before the DOM ready event.

Make sure that code is wrapped in an on ready event, like this:

$( document ).ready( function() {

  // closing div with click on img .
  $('img.close_url').click(function(){
    ..
  });

});
Nick B
  • 7,639
  • 2
  • 32
  • 28
  • I have put it inside $( document ).ready( function() {}); but even then its not working . where as its working for other tags which are placed nearby this img tag . I am referring http://api.jquery.com/on/ . – Always_a_learner Feb 17 '14 at 08:56
  • Please check the edited part of my question . thanks for the help @nick – Always_a_learner Feb 17 '14 at 09:00
  • In order to help further I would need to see all the code that is going on. Where is that "content" variable being declared, and how is it being used.. can you post all the code in a jsfiddle? – Nick B Feb 17 '14 at 15:45
  • thanks @nick .It now started working when i wrote it like this $('div.viewed-profile-outer').on( "click","img.close_url",function(){ $('div.urlResult').hide(); $('input#hidden_url_title').val(); $('input#hidden_url_content').val(); $('input#hidden_is_url').val(0); $('textarea#post_box').val(); }); – Always_a_learner Feb 18 '14 at 04:36