digglemister digglemister - 6 months ago 19
jQuery Question

Increase counter value upon button click, then re-use value

I've got three photos showing, "photo0", "photo1", "photo2", and I'm trying to make it so that clicking the middle photo will change the photos showing to "photo1", "photo2", "photo3". I'm not sure why this code isn't doing the trick.

I've added a Textbox just to show what's happening to my counter. After I click the middle photo once everything works fine, the photos change and the counter's value changes to 2, but then nothing happens when I click the middle photo again.

var counter = $('#TextBox').val(); //Initial value of TextBox is 1

$("#middle_photo").click(function() {
$("#left_photo").replaceWith('<img id="left_photo" src="photo'+counter+'.jpeg" />');
counter++;

$("#middle_photo").replaceWith('<img id="middle_photo" src="photo'+counter+'.jpeg" />');
counter++;

$("#right_photo").replaceWith('<img id="right_photo" src="photo'+counter+'.jpeg" />');
counter--;

$('#TextBox').val(counter);

});

Answer

On First Click:

Everything works fine because your code work and the event trigger on click.

After That:

The click event is not bind to the newly replaced elements, so you should .on like

$(document).on("click", "#middle_photo", function() {
    $("#left_photo").replaceWith('<img id="left_photo" src="photo'+counter+'.jpeg" />');
    counter++;

    $("#middle_photo").replaceWith('<img id="middle_photo" src="photo'+counter+'.jpeg" />');
    counter++;

    $("#right_photo").replaceWith('<img id="right_photo" src="photo'+counter+'.jpeg" />');
    counter--;

    $('#TextBox').val(counter);
});

But instead you should do

$("#middle_photo").click(function() {
    $("#left_photo").attr("src", 'photo'+ ++counter +'.jpeg');
    $("#middle_photo").attr("src", 'photo'+ ++counter +'.jpeg');
    $("#right_photo").attr("src", 'photo'+ ++counter +'.jpeg');
    $('#TextBox').val(--counter);
});

In this implementation you are not adding and removing any elements in DOM so more efficient and its short and it looks pretty to me!