How to make this function run more than once JavaScript/jQuery -


i need code run more once. runs when click button append images, , click button remove them. third click doesn't append images again

<button class="" onclick="showimages(this,'100000,jpg','1111111.jpg','5');"></button> <div id="5" class=""> ... //when run function appends <img> tag here </div>  function showimages(button, image1, image2, id) { //user clicks button "show"     if (image2 == "") { //if there 1 image         $('#show' + id + '').append('<img class=\"one\" src=\"images/' + image1 + '\" />'); //creates div 1 image         button.onclick = function () { //clicks second time             $('#show' + id + '').empty(); //removes div image         };     } else { //if there 2 images         $('#show' + id + '').append('<img class=\"two\" src=\"images/' + image1 + '\" /><img src=\"images/' + image2 + '\" />'); //div 2 images         button.onclick = function () { //...             $('#show' + id + '').empty(); //...         };     } } 

well, since edited post better way give answer. onclick="showimages(this,'100000,jpg','1111111.jpg','5');" attached 1 handler on button click. later in button.onclick = function () { $('#show' + id + '').empty(); }; gave 1 more handler. have 2 handlers: 1 of them show images , 1 kills immediately. why code works once (until second handler not binded).

lets fix it. html:

<button id="my_button" image_1="10000.jpg" image_2="1111111.jpg" target_id="5"></button> <!-- move away javascript html; put necessary data in button attributes --> <div id="5"> ... </div> 

and javascript:

var toggleimages = function( event ){    /* retrieve clicked button , needed attributes */   var button = $( event.target ),       image_1 = "images/" + button.attr( 'image_1' ),       image_2 = "images/" + button.attr( 'image_2' ),       target = $( '#' + button.attr( 'target_id' ) );    /* if no images shown – show */   if( 0 == target.find( 'img' ).length ){     target.append( '<img src="' + image_1 + '" />' );     if( 'undefined' != typeof image_2 ){       target.append( '<img src="' + image_2 + '" />' );     }   /* if images shown – remove */   } else {     target.empty();   } } $( '#my_button' ).on( 'click', toggleimages ); /* bind click handler 1 time */ 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -