jQuery setInterval for next element

Nimitz E.

I have a working html code here:

<div class="monitoring-icons">
    <div class="mon-img hovicon effect-1 sub-a mon-active">
    <img class="icon-active" src="http://placehold.it/125X125&text=Blood" width="100px" data-info="blood">
    </div>

    <div class="mon-img hovicon effect-1 sub-a">
    <img class="icon-inactive" src="http://placehold.it/125X125&text=Weight" width="100px" data-info="weight">
    </div>

    <div class="mon-img hovicon effect-1 sub-a">
    <img class="icon-inactive" src="http://placehold.it/125X125&text=Sleep" width="100px" data-info="sleep">
    </div>
</div>

<div class="monitoring-infor">

<div class="icon-item" id="info-blood">
<h2 class="smaller">Blood Pressure</h2>
<p>Etiam sed velit hendrerit, facilisis est sit amet, facilisis orci. Vestibulum et risus condimentum, tristique purus sit amet, placerat sem. Ut blandit lorem id sem iaculis, et consequat lorem vestibulum. </p>
</div>

<div class="icon-item monitoring-info-item" id="info-weight">
<h2 class="smaller">Weight </h2>
<p>Cras malesuada lacinia libero a maximus. Cras ullamcorper tellus in ante laoreet eleifend. Donec tincidunt libero nec tellus placerat pretium.</p>
</div>


<div class="icon-item monitoring-info-item" id="info-sleep">
<h2 class="smaller">Sleep </h2>
<p>Fusce nunc arcu, ultrices vel odio at, vulputate pulvinar nunc. Sed placerat, lorem ac consequat lobortis, turpis lacus interdum nibh, vel ultricies urna felis vel neque. Nunc pharetra laoreet ante, eu pulvinar est. Nullam sollicitudin ultricies enim at aliquet. Nulla pharetra nulla in sem viverra consectetur. Fusce quis turpis tristique, hendrerit neque ut, facilisis eros.</p>
</div>

</div>

Now, what I am trying to do is to go to the next mon-img and add mon-active and I have a successful jquery here:

setInterval(function(){                
        $('.mon-active').removeClass(function(){
            $(this).next().addClass('mon-active');
            return 'mon-active';
            $(this+'img').trigger('click');
        }); 
    }, 10000);

Its working but what I wanted is to loop it. When its the last mon-img then I wanted it to add the css mon-active to the first mon-img.

Also, at the same time I want to trigger click event so that the relevant information for the image button should be displayed.

here is my complete code in fiddle.

Martin Ernst

I refer to the whole code given in your fiddle. There are some points to note that will simplify the code.

1) The switching of class mon-active is done inside the click-handler of the images. There's no need to do it again in the interval: each time you trigger a click the class-switching is done automatically.

2) Don't create a jQuery-object with same selector multiple times. It's much to write and takes much time to execute. Create it once, store it in a variable and refer to it by the var name.

3) If you perform multiple actions on the same object use chaining of the actions.

So your code may look like this:

jQuery(function($) {

var timer = myInterval(), // EDIT
    delay;

// variables for often used jQuery objects:
var imgs = $('.monitoring-icons img'),
    mons = $('.mon-img'),
    info = $('.monitoring-infor div.icon-item');
// no need for '.each()', jQuery's '.on()' does the 'each' internally
imgs.on("click", function(ev, i){

    var ths = $(this), // 'this' refers to the clicked image
        par = ths.parent(), // get the parent div of the clicked image
        infoid = '#info-' + ths.data('info'), // get the associated id from data
        infoshow = $(infoid); // get the associated info-element with that id

    par.addClass('mon-active'); // make parent-div of clicked image active
    // use '.not()' to select all the other mon-divs that are not this parent
    mons.not(par).removeClass('mon-active'); // make all others inactive

    // here use chaining of two actions 'removeClass()' and 'addClass()'
    ths.removeClass('icon-inactive').addClass('icon-active'); // make clicked img active
    // '.not()' selects all imgs that are not this clicked image
    imgs.not(this).removeClass('icon-active').addClass('icon-inactive'); // make them inactive

    // do the same with the associated info-text-divs
    infoshow.removeClass('monitoring-info-item').addClass('mon-info');
    info.not(infoshow).removeClass('mon-info').addClass('monitoring-info-item');

    clearInterval(timer); clearTimeout(delay); // EDIT
    delay = setTimeout(function() {timer = myInterval();}, 20000); // EDIT

});

function myInterval() { // EDIT
    return setInterval(function(){ //EDIT: return added           
        var act = $('.mon-active'), // get the active div
            // get the index of active div and add one to have index of the next
            // with 'modulo' we get '0' when active is the last one, so we start from beginning
            i = (mons.index(act) + 1) % mons.length;
        // trigger the next image, all needed actions are done in the click-handler above
        imgs.eq(i).trigger('click');
    }, 10000);
} // EDIT

});

I hope this DEMO does all you want, otherwise please post critique.

EDIT According to your last question: 1) Define variables to hold the interval and delay on top of code. 2) Wrap setInterval in a function myInterval() that returns this interval. 3) Inside the click-handler add some code that stops the interval with clearInterval(), sets a delay of 20000ms with setTimeout(), then starts the Interval again by calling myInterval(). I've added the code above and marked it with // EDIT.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related