targetting just one image under a div jQuery

user6002037

I am trying to show a different image based on a random number. If the number is not two I want to change the image to box-lose on the box that the user clicked on.

Unfortunately, I am not able to target this image. I want to change just the image that the user clicked on to the lose image. see jsfiddle here which may make the question clearer. I have tried to use closest and find however I cannot seem to target the element.

js

$('.box').click(function(){

    var randomNumber = 1;
    var thisBox = $(this);

    if(randomNumber === 2){
       alert('number is 2');
   } else {                 
       thisBox.closest('img').find('.box-img').css('display', 'none');
       thisBox.closest('img').find('.box-lose').css('display', 'block');
   }
});

html

<div class="box">
   <img class="box-img" src="http://assets.nydailynews.com/polopoly_fs/1.986006.1336765559!/img/httpImage/image.jpg_gen/derivatives/gallery_1200/hulk-hogan-pastamania.jpg">
   <img class="box-win" src="http://www.profightdb.com/img/wrestlers/thumbs-600/1414330df8brethart.jpg">
   <img class="box-lose" src="http://images.huffingtonpost.com/2014-12-11-Hulk.jpg">
</div>

<div class="box">
  <img class="box-img" src="http://assets.nydailynews.com/polopoly_fs/1.986006.1336765559!/img/httpImage/image.jpg_gen/derivatives/gallery_1200/hulk-hogan-pastamania.jpg">
  <img class="box-win" src="http://www.profightdb.com/img/wrestlers/thumbs-600/1414330df8brethart.jpg">
  <img class="box-lose" src="http://images.huffingtonpost.com/2014-12-11-Hulk.jpg">
</div>

<div class="box">
  <img class="box-img" src="http://assets.nydailynews.com/polopoly_fs/1.986006.1336765559!/img/httpImage/image.jpg_gen/derivatives/gallery_1200/hulk-hogan-pastamania.jpg">
  <img class="box-win" src="http://www.profightdb.com/img/wrestlers/thumbs-600/1414330df8brethart.jpg">
  <img class="box-lose" src="http://images.huffingtonpost.com/2014-12-11-Hulk.jpg">
</div>
oshell

If you want a coinflip for win and lose and to display a certain picture on the result you would just create a random number and define a context for your selectors. JSFiddle

You should avoid using functions such as .closest(). There are always better options.

$('.box').on('click', function() {
  var randomNumber = Math.floor(Math.random() * 2) + 1;
    $('.box-img', $(this)).hide();
  if (randomNumber === 2) {
    $('.box-win', $(this)).show();
  } else {
    $('.box-lose', $(this)).show();
  }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related