4
\$\begingroup\$

I have a list of 6 items, and each one on click reveals a div that runs 100% wide under the row of list items. The code works, but the div opens very slowly and kind of choppy. Is there anything I can do to help it run more smoothly?

My HTML is set up as such:

 <ul>           
    <li><a class="artist-logo" href="#artist-1"><img src="images/looka-black-circle.png"></a></li>
    <div id="artist-1" class="artist-box">
    </div>
    <li><a class="artist-logo" href="#artist-2"><img src="images/looka-black-circle.png"></a></li>
    <div id="artist-2" class="artist-box">
    </div>
    <li><a class="artist-logo" href="#artist-3"><img src="images/looka-black-circle.png"></a></li>
    <div id="artist-3" class="artist-box">
    </div>
 </ul>

Here is my jscript:

 $(document).ready(function(){
 $(".artist-box").hide();
$(".artist-logo").click(function(e) {
e.preventDefault();
// get the clicked element
var clicked = $(this);

// get the selected element
var taggedWithSelect = $('.selected-artist');  
// get the corresponding divs
var clickPartner = $(clicked.attr('href'));
var selectPartner = $(taggedWithSelect.attr('href'));
var notClicked = $('.artist-logo').not(clicked);


        // we either want to close this one or open this one and close any others
        // if this one is open, it should be tagged with select
if( clicked.hasClass('selected-artist') ) {
    clicked.removeClass('selected-artist');
    notClicked.removeClass('blur-logo');
} else {                
  clicked.addClass('selected-artist');
  taggedWithSelect.removeClass('selected-artist');
  selectPartner.slideToggle();
  notClicked.addClass('blur-logo');
  clicked.removeClass('blur-logo');
}

clickPartner.slideToggle();

});

});
\$\endgroup\$
1
\$\begingroup\$

All this adding/removing classes are too much for this functionality. This makes it also very slow.

You can iterate over all div elements, and say if div is !== hidden, than hide it.

After that, you get the clicked element with $(this), and just say

$(this).next().slideToggle();

This is not proper code, but since you don't have thousands of divs to iterate over, just hide every open div, and open the clicked one.

Maybe you have the problem of you want to close the already open one, so just make two if's. The first one should be like:

if($(this).next().style.visible === "true"), hide it, if not, hide every visbile div and make just the next to the clicked one visible.

This should be much faster, because you don't add/remove/readd classes.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.