0

On my page I have articles with dynamic content.

And I use two jQuery scripts to filter them

//Load more // less
  $(document).ready(function () {
  $('#article-list article:gt(10)').hide();
  $('#loadMore').click(function () {
  $('#article-list article:hidden:lt(2)').show();
      });
    });
    //hide articles with no image
  $('.myClass').each(function(){
       if($(this).attr('src') === ""){
          $(this).closest('article').hide();
       }
    });

On the first load it's okay I see 10 articles all with images.

But when I click load more it loads 2 more articles but I see articles with no image.

How can I combine those two codes so when I click load more to hide the articles with no image

3
  • src attribute may not exists Commented Feb 10, 2015 at 23:48
  • it exists, if i remove the load more script it it will hide the articles without image. Commented Feb 10, 2015 at 23:50
  • Had you indented your code, you would have seen that the last piece of code with the each loop, is outside the DOM ready handler. Is this code in the head, if so you have to place the loop inside the DOM ready handler Commented Feb 10, 2015 at 23:52

2 Answers 2

1

You can give the articles without images a class and filter on that

  $(document).ready(function () {
    $('#article-list article:gt(10)').hide();
    $('#loadMore').click(function () {
      $('#article-list article:not(.noimg):hidden:lt(2)').show();
    });
  //hide articles with no image
    $('.myClass').each(function(){
      if($(this).attr('src') === ""){
        $(this).closest('article').addClass('noimg').hide();
      }
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

1

You know you'll need to reuse it, so write a function:

function hideArticlesWithNoImages(){ 
   $('.myClass').each(function(){
      if($(this).attr('src') === undefined || $(this).attr('src') === ''){
         $(this).closest('article').hide();
      }
   });
}

Then reference it:

$(document).ready(function () { 
   $('#article-list article:gt(10)').hide();
   $('#loadMore').click(function () {
      $('#article-list article:hidden:lt(2)').show();
      hideArticlesWithNoImages();
    });
   hideArticlesWithNoImages();
});

Comments

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.