AllisonC
AllisonC

Reputation: 3099

Why isn't addEventListener click working?

This is the code, I can't get the click event listener to fire

Javascript:

var cid = 1721;
var alt = "4x6_" + cid;
var thumb = "168c619a1d1743bd4f3aba9d69a8c3ce";
var mattes_selected_type = "182";
var i = 0;
function common_get_site_url()
{
  return "https://jsfiddle.net/img/logo.png";
}

//
var thumb_img = new Image();
thumb_img.id = 'cid_' + cid;
thumb_img.alt = alt;
thumb_img.src = ""; 
thumb_img.addEventListener('load', function() {
   alert("LOAD");
}, false);
thumb_img.addEventListener('click', function() {
  alert("CLICK");
}, false);
thumb_img.src = common_get_site_url();

$('#matte_designs_strip_wrapper').append('<span class="matte_design_image_name"><img id="cid_' + cid + '" src="' + thumb_img.src +'" /></span>'); 

HTML:

<div id="matte_designs_strip_wrapper"></div>    

https://jsfiddle.net/allisonc/yoq4Lotx/1/

Upvotes: 0

Views: 182

Answers (3)

Tareq
Tareq

Reputation: 5363

var cid = 1721;
var alt = "4x6_" + cid;
var thumb = "168c619a1d1743bd4f3aba9d69a8c3ce";
var mattes_selected_type = "182";
var i = 0;
function common_get_site_url()
{
  return "https://jsfiddle.net/img/logo.png";
}

//
var thumb_img = new Image();
thumb_img.id = 'cid_' + cid;
thumb_img.alt = alt;
thumb_img.src = ""; 
thumb_img.addEventListener('load', function() {
   alert("LOAD");
}, false);
thumb_img.addEventListener('click', function() {
  alert("CLICK");
}, false);
thumb_img.src = common_get_site_url();

var span = $('<span class="matte_design_image_name"></span>')

span.append(thumb_img)

$('#matte_designs_strip_wrapper').append(span);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="matte_designs_strip_wrapper"></div>

Upvotes: 0

Philipp Meissner
Philipp Meissner

Reputation: 5482

You reference an Image object, not the actual HTML element you expect. Once you appended and added the HTML dynamically you want to run

$('#cid_' + cid).on('click', function(e) {
  // Your code here
});

Then your event listener will target the proper HTML, not just any object :)

Upvotes: 0

FieryCat
FieryCat

Reputation: 1885

Try to change the last line to:

$('#matte_designs_strip_wrapper').append($('<span class="matte_design_image_name"/>').append(thumb_img));

Otherwise you're using addEventListener to an element that will never appear

Upvotes: 9

Related Questions