javascript - targetting just one image under a div jQuery -


i trying show different image based on random number. if number not 2 want change image box-lose on box user clicked on.

unfortunately, not able target image. want change image user clicked on lose image. see jsfiddle here may make question clearer. have tried use closest , find cannot seem target element.

js

$('.box').click(function(){      var randomnumber = 1;     var thisbox = $(this);      if(randomnumber === 2){        alert('number 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> 

if want coinflip win , lose , display picture on result create random number , define context selectors. jsfiddle

you should avoid using functions such .closest(). there 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();   } }); 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -