how make a .click() function reusable

Essentially, i have been unable to find a way to make the following .click() work more than once. My intent is to make is so that repeating clicks of the .gen2 class will continually .remove() the current .gen2 image and replace it with a randomly selected image from myArray.

$(document).ready(function(){
  $('.gen2').click(function(){
    $('.gen2').remove();
    var myArray = ['<img class="gen2" src="images/bottom/chinchilla.png" />', 
    '<img class="gen2" src="images/bottom/bird.png" />', 
    '<img class="gen2" src="images/bottom/bluejay.png" />',  
    '<img class="gen2" src="images/bottom/walrus.png" />'];
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
    $('.change').append(rand);
});
  $('.gen1').click(function(){
    $('.gen1').remove();
    var array = ['<img class="gen1" src="images/top/raven.png" />', 
    '<img class="gen1" src="images/top/boar.png" />', 
    '<img class="gen1" src="images/top/trex.png" />'];
    var rand = array[Math.floor(Math.random() * array.length)];
    $('.change').append(rand);
});});

HTML is as follows. because the positions of both .gen1 and .gen2 are set to absolute, they overlap so that as each is removeed and proceedurally replaced with .append(), a new image is formed.

<body>
    <div class="change">
        <img class="gen1" src="images/top/raven.png" />
        <img class="gen2" src="images/bottom/chinchilla.png" />
    </div>

the problem is that after the first click(); the function no longer runs. I can't figure how..

Thanks!

Upvotes: 4

Views: 159

Answers (4)

Tushar
Tushar

Reputation: 87203

  1. Use Object to store the images sources
  2. Store only images source URL in object of arrays. Don't add HTML
  3. Use data- custom attribute on the image to store custom data
  4. Don't remove and add HTML elements in DOM. Update the src value of the element.
  5. Add Common class to bind events on elements

Note: As the image is picked randomly, there are chances when the image may not change on click i.e. image is changed but next image is same as previous.

var obj = {
  'gen1': ['',
    'images/top/boar.png',
    'images/top/trex.png'
  ],
  'gen2': ['http://www.ggdesignsembroidery.com/store/images/uploads/Chubby1.jpg',
    'http://www.ggdesignsembroidery.com/store/images/uploads/Chubby2.jpg',
    'http://www.ggdesignsembroidery.com/store/images/uploads/Chubby3.jpg',
    'http://www.ggdesignsembroidery.com/store/images/uploads/Chubby4.jpg'
  ]
};

$('.change').on('click', '.gen', function() {
  var myArray = obj[$(this).data('target')];
  var rand = myArray[Math.floor(Math.random() * myArray.length)];

  $(this).attr('src', rand);
});
img {
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="change">
  <img class="gen1 gen" src="images/top/raven.png" data-target="gen1" />
  <!--             ^^^: Common Class               ^^^^^^^^^^^: Custom Attribute -->
  <img class="gen2 gen" src="http://www.ggdesignsembroidery.com/store/images/uploads/Chubby1.jpg" data-target="gen2" />
  <!--             ^^^: Common Class                                                              ^^^^^^^^^^^: Custom Attribute -->
</div>

Images taken from http://www.ggdesignsembroidery.com/

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115232

You want to listen dynamically added elements , so you need to use event delegation

$(document).ready(function() {
  var myArray = ['<img class="gen2" src="images/bottom/chinchilla.png" />',
      '<img class="gen2" src="images/bottom/bird.png" />',
      '<img class="gen2" src="images/bottom/bluejay.png" />',
      '<img class="gen2" src="images/bottom/walrus.png" />'
    ],
    array = ['<img class="gen1" src="images/top/raven.png" />',
      '<img class="gen1" src="images/top/boar.png" />',
      '<img class="gen1" src="images/top/trex.png" />'
    ];

  $('.change').on('click', '.gen2', function() {
    $('.gen2').remove();
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
    $('.change').append(rand);
  }).on('click', '.gen1', function() {
    $('.gen1').remove();
    var rand = array[Math.floor(Math.random() * array.length)];
    $('.change').append(rand);
  });
});

Upvotes: 0

SlOtErJaCk
SlOtErJaCk

Reputation: 13

I think this is a better approach and may be you can combine the two with more generic selector like $('.change>img')

$(document).ready(function(){
  $('.gen2').click(function(){
    var myArray = ["images/bottom/chinchilla.png" ,"images/bottom/bird.png" ,"images/bottom/bluejay.png","images/bottom/walrus.png" ];
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
     $(this).attr("src",rand);
});
  $('.gen1').click(function(){
    var array = ["images/top/raven.png" ,"images/top/boar.png","images/top/trex.png"];
    var rand = array[Math.floor(Math.random() * array.length)];
     $(this).attr("src",rand);
});});

Upvotes: 0

Muhammad Atif
Muhammad Atif

Reputation: 1102

Try this:

$(document).ready(function(){
    $(document.body).on('click','.gen2',function(){
      //your code here
    });
    $(document.body).on('click','.gen1',function(){
      //your code here
    });
});

Upvotes: 0

Related Questions