1

I have 5 divisions in the html code and after the first division a button "show more" has been placed. I want to fire a jquery command which shows the second division on clicking the button "show more" once and the third division on again clicking the button and so on.

The problem is that i am only able to show the second division and not able to fire the jquery script the second time to show the third division.

below is my Jquery and html.

$(document).ready(function(){
		for(i=2;i<=5;i++)
		{
			$("#"+i).hide();
		}
		i=2; /* degrade the value of i */

		$("button").on("click",function(){
			//alert(i);
			$("#button").remove();
			$("#"+i).show();
			var button="<button id='button' class='btn btn-primary'>show  more</button>";
			$("#"+i).after(button);
			i=i+1;
		});
	});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<!-- Optional theme -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="container">
	<div class="row">
		<div class="col-md-4 col-sm-6 col-xs-12" id="1" style="border:1px solid red; height:200px; width:300px;"></div>
		<button id='button' class='btn btn-primary'>show more</button>
		<div class="col-md-4 col-sm-6 col-xs-12" id="2" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="3" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="4" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="5" style="border:1px solid red; height:200px; width:300px;"></div>
	
  </div><!-- .row -->
</div><!-- .container -->

4
  • 1
    Why are you destroying your button, then trying to re-create it immediately after? Just use the same button. Otherwise you'll need delegation for dynamically added elements. Commented Jun 9, 2017 at 9:31
  • 1
    i am removing and recreating my button so that the "show more" option remains at the bottom of the page and the new division is placed before or above the button. Commented Jun 9, 2017 at 9:34
  • 1
    @rishabhjain The way I have approached is much better compared to yours. Would that work by any chance or do you have any restrictions? Commented Jun 9, 2017 at 9:35
  • 1
    @rishabb Just place your button after the hidden elements?? Commented Jun 9, 2017 at 9:36

7 Answers 7

6

You can do this way. The trick is:

$(":hidden").first().show()

Snippet

$(function () {
  $("p:not(:first)").hide();
  $("a").click(function (e) {
    e.preventDefault();
    $("p:hidden").first().show();
  });
});
* {margin: 0; padding: 0; list-style: none; line-height: 1;}
p {display: inline-block; padding: 5px; border: 1px solid #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<a href="#">Show</a>

Also, you can add one more check to find if there are any more hidden <p> and then you can remove the link too:

$(function () {
  $("p:not(:first)").hide();
  $("a").click(function (e) {
    e.preventDefault();
    $("p:hidden").first().show();
    if (!$("p:hidden").length)
      $(this).hide();
  });
});
* {margin: 0; padding: 0; list-style: none; line-height: 1;}
p {display: inline-block; padding: 5px; border: 1px solid #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<a href="#">Show</a>

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

10 Comments

Would only suggest to be more specific about selector
@Raimonds Sorry, didn't understand. Can you please kindly clarify?
Your main trick here is that you put the show button all the way at the end. You should clarify that in your answer. Not sure if that works for OP, but it's definitely a nice approach.
@Praveen Kumar Nice solution, but I would just stick with the detach() function like I mentioned in my answer. This way you do not have to deal with compoarisons for hidden elements and stuff. Have a look, what do you think? jsfiddle.net/hallleron/h6huonub/1
@hallleron Very much agree. I see the problem and derive the solution. So I thought of suggesting this way. I should have started by saying, if I were you... So... I would do this way...
|
3

Well I guess a very short and clean solution is this: https://jsfiddle.net/hallleron/h6huonub/1/

Use the detach() function to handle the button. This way you DO NOT lose the event delegation of the button and it is way less resource intensive.

The key part is this line:

var el = $('#button').detach();

$(document).ready(function(){
		for(i=2;i<=5;i++)
		{
			$("#"+i).hide();
		}
		i=2;

		$("button").on("click",function(){

            var el = $('#button').detach();
            
			$("#"+i).show();
			$("#"+i).after(el);
			i=i+1;
		});
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
	<div class="row">
		<div class="col-md-4 col-sm-6 col-xs-12" id="1" style="border:1px solid red; height:200px; width:300px;"></div>
		<button id='button' class='btn btn-primary'>show more</button>
		<div class="col-md-4 col-sm-6 col-xs-12" id="2" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="3" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="4" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="5" style="border:1px solid red; height:200px; width:300px;"></div>
	
  </div><!-- .row -->
</div><!-- .container -->

EDIT: Added working code snippet.

4 Comments

Nice solution. Almost the same as mine, only making the detaching and reinserting explicit. I'd upvote your answer if you'd include your code as a snippet. This'll help preserve the answer in case JSFiddle would go down in the future.
There you go ;-)
There you go ;-)
This is the sweetest and shortest solution. Sir! Thanks a lot.
2

It's because your second button is not in the DOM when you initialize your function.

Instead use this:

    $('body').on('click', 'button', function(){
       // Your code
    });

http://api.jquery.com/on/

$(document).ready(function(){
		for(i=2;i<=5;i++)
		{
			$("#"+i).hide();
		}
		i=2; /* degrade the value of i */

		$("body").on("click", "button" ,function(){
			//alert(i);
			$("#button").remove();
			$("#"+i).show();
			var button="<button id='button' class='btn btn-primary'>show  more</button>";
			$("#"+i).after(button);
			i=i+1;
		});
	});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<!-- Optional theme -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="container">
	<div class="row">
		<div class="col-md-4 col-sm-6 col-xs-12" id="1" style="border:1px solid red; height:200px; width:300px;"></div>
		<button id='button' class='btn btn-primary'>show more</button>
		<div class="col-md-4 col-sm-6 col-xs-12" id="2" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="3" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="4" style="border:1px solid red; height:200px; width:300px;"></div>
		<div class="col-md-4 col-sm-6 col-xs-12" id="5" style="border:1px solid red; height:200px; width:300px;"></div>
	
  </div><!-- .row -->
</div><!-- .container -->

5 Comments

I'd like to know why this has been downvoted, because event delegation is one way to solve the problem
I'm curious to know it too because this is working with a simple modification :-)
@Jeremy It was downvoted when the answer did not include the snippet, maybe that's why? Downvotes are random sometimes, I've given up on trying to understand them. One downvote is already retracted.
I thought my answer was clear enough without a snippet
Silent downvoters are a pain and don't bring anything. We should always say why we downvote, so people can understand their mistakes and get better. For that matter, I think Stackoverflow should force downvoters to write a justification.
2

Why are you destroying your button, then trying to re-create it immediately after? Just use the same button. Otherwise you'll need delegation for dynamically added elements.

$("#button").click( () => $(`#${++i}`).show())

Or in ES5:

$("#button").click( function(){ $("#" + (++i) }).show())

You say that you're destroying the button and re-creating it so it's always after the last shown element, well, place the button directly after all hidden elements and leave it here...

2 Comments

Uh! ES6. I don't know when I am gonna master this art... :(
Are you kidding? Basically it's replacing function(){} with () => {}
0

When you remove the button and insert a new one, it does not have your click handler attached to it. What you can do instead is move the existing button, which will retain the click handler.

$(document).ready(function() {
  var i, $button = $('#button');
  for (i = 2; i <= 5; i++) {
    $("#" + i).hide();
  }
  i = 2; /* degrade the value of i */

  $("button").on("click", function() {
    var $i = $("#" + i);
    $button.insertAfter($i);
    $i.show();
    i = i + 1;
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-4 col-sm-6 col-xs-12" id="1" style="border:1px solid red; height:200px; width:300px;"></div>
    <button id='button' class='btn btn-primary'>show more</button>
    <div class="col-md-4 col-sm-6 col-xs-12" id="2" style="border:1px solid red; height:200px; width:300px;"></div>
    <div class="col-md-4 col-sm-6 col-xs-12" id="3" style="border:1px solid red; height:200px; width:300px;"></div>
    <div class="col-md-4 col-sm-6 col-xs-12" id="4" style="border:1px solid red; height:200px; width:300px;"></div>
    <div class="col-md-4 col-sm-6 col-xs-12" id="5" style="border:1px solid red; height:200px; width:300px;"></div>

  </div>
  <!-- .row -->
</div>
<!-- .container -->

Indeed, the documentation of insertAfter mentions that

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved after the target (not cloned) and a new set consisting of the inserted element is returned:

(Emphasis mine.)

Comments

0

I think you are looking for

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    </head>
    <div class="container">
        <div class="row">
            <div class="col-md-4 col-sm-6 col-xs-12" id="ID_1" style="border:1px solid red; height:200px; width:300px;"></div>
            <button id='button' class='btn btn-primary'>show more</button>


      </div><!-- .row -->
    </div><!-- .container -->

<!-- end snippet -->

<script>

    var id=1;
        $(document).ready(function(){

                $("body").on("click", "button" ,function(){
                id++;

                var div='<div class="col-md-4 col-sm-6 col-xs-12" id="ID_'+id+'" style="border:1px solid red; height:200px; width:300px;"></div>';
                    var button="<button id='button' class='btn btn-primary'>show more</button>";
                $("#button").remove();
                $(".row").append(div);
                    $(".row").append(button);
                });
            });

</script>

Comments

-2

Try to do this:

$(document).ready(function() {
    for (var i = 2; i <= 5; i++) {
        $("#" + i).hide();
    }
    var i = 2; /* degrade the value of i */

    $("button").on("click", function() {
        $("#" + i).show();
        i = i + 1;
    });
});

1 Comment

1) The click handler is outside the document.ready so it won't work. 2) The dynamically added button still won't have any click event attached to it so it won't work... Downvoted

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.