samedi 1 août 2015

jQuery - How to .show() & .hide() an element based on variable value?

I am creating a image slider from scratch as a bit of practice but I can't seem to overcome this problem. My four images are lined up next to each other and all .animate() to move to the next image using button clicks for forward and back.

Of course I don't want the user to press the forward & back buttons more than 4 times because they will then be presented with an empty slot where an image is supposed to be. I have a variable that increments/decrements each time I click and when it gets to more than or equal to 3/-3 I want the button to .hide() so it can't be clicked, and reappear once the value decreases/increases by the opposite button click. My code:

<code>$(document).ready(function() {
    var $clickcount = 0;    //clicks of forward/prev counter

 $('#forwardbtn').click(function() {        //forward button clicked..

    $clickcount ++;     //increment clickcount +1
    $('#sliderimg1, #sliderimg2, #sliderimg3, #sliderimg4').animate(
    {left:'+=950px'}, 800,'easeInOutQuad');   

    if($clickcount >= 3 ) {     //if clickcount = 3
        $('#forwardbtn').hide();    //hide button so it cant be clicked
    } else {
        $('#forwardbtn').show(); }  //otherwise keep it shown..
 });

 $('#prevbtn').click(function() {   //function opposite of one above

    $clickcount --;
    $('#sliderimg1, #sliderimg2, #sliderimg3, #sliderimg4').animate(
    {left:'-=950px'}, 800,'easeInOutQuad');

    if($clickcount >= -3 ) {
        $('#prevbtn').hide();
    } else {
        $('#prevbtn').show(); }
 });    
 });</code>

Any help appriciated, thanks for your time :)

Aucun commentaire:

Enregistrer un commentaire