1

When running this code, every time I click the '#right', the #slide gets incremented by 2 instead of just 1... so for example i get the 1st, 3rd and the 5th elements if there are a total 6 elements.

    var present=2;
    var total_slide=document.getElementById("slider").childElementCount;
    $("#right").click(function()
    {

        for(i=1;i<=total_slide;i++) {
            $("#slide"+i).css("display","none"); // hide all elements
        }
        $('#slide'+present).css("display","block"); // the problem : display 
                                                    // only the present element
                                                    // (gets incremented by 2 )
        present=(present+1)%total_slide;
    });

If however i use 1,2,3 etc for eg: ('#slide'+2) in place of ('#slide'+present), get the right results, but i wanna do this dynamically ..

thanks

1 Answer 1

2

No need to do a for loop, jQuery returns already a collection of your elements in array.
You just need to pre-increment and 'modulize' (%) your counter.

http://jsbin.com/uhiyew/1/edit

var present=2;
var $childrens = $("#slider > *");
var total_slide = $childrens.length;

$childrens.eq(present).show();


$("#right").click(function(){

     $childrens.hide() // hide all elements
        .eq(++present%total_slide).show(); // show desired

});
Sign up to request clarification or add additional context in comments.

6 Comments

this isn't working perfectly either ..var present = 1; var $childrens = $("#slider > *"); var total_slide = $childrens.length; $childrens.hide(); $childrens.eq(present).show(); $("#right").click(function(){ $childrens.hide() // hide all elements .eq(++present%total_slide).show(); // show desired }); .. its following this order : 2,4,1,3,5,2
and in the case of even number of slides .. it goes 2 4 2 4 .. so its still jumping twice :(
@btheceo than you need to show your HTML, looks like some other elements inside your #slide are messing with the index count.
<div id="slider"> <?php $gal = get_post_meta($post->ID,'gal',true); $attachments = explode(',', $gal); $j=0; foreach ( $attachments as $attachment) { $j=$j+1;?> <div id="slide<?php echo $j?>" class="slide" align="center"> <?php echo wp_get_attachment_image( $attachment, 'full' );?> </div> <?php } ?> </div>
this is the html .. its a wordpress document .. i tried to print the value of present everytime and it was going 1 3 5 and so on .. for now i have worked around it by incrementing .5 everytime .. so the problems solved but would still like to understand why its happening .. though your solution i think was perfect :D
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.