I want to move to the top of the content when I click to close jQuery's open and closed content.

Asked 2 years ago, Updated 2 years ago, 128 views

I would like to use jQuery to open and close the contents (text and images) on the page with slideToggle.
I would like to move it to the top of the openable content (#readmore-wrap) in animation when I click the Close button.
If it's my js, it will move to the top of #readmore-wrap even when I click [Read more].
I would like to request the following.
It may be a misguided code because it is not bright on javascript, but I would appreciate it if you could give me your opinion.

  • When you click
  • Read more, the content is displayed as slideToggle.
  • When you click the Close button, move the content to the top of the openable content (#readmore-wrap) as soon as it closes

var position=$("#readmore-btn-common").offset().top;
  jQuery( document).ready(function($){
    jQuery('#readmore-btn-common').click(function(){
      $("html,body").animate({
          scrollTop:position
      }, {
          queue —false
      });
        jQuery('#readmore-wrap').slideToggle(1000, function(){
          if(jQuery(this).is(':hidden')}{
            jQuery('#readmore-btn-common') .html('<span id="readmore-btn-open"> Read more</span>');
          } else{
            jQuery('#readmore-btn-common').html('<span id="readmore-btn-close">Close</span>');
          }
        });
    });
  });
#readmore-wrap{
      display: none;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--Openable Content-->
<divid="readmore-wrap">
  <!--Content Content-->
</div>
 <!--/Openable Content-->
<span id="readmore-btn-common"><span id="readmore-btn-open"> Read more</span>

jquery

2022-09-30 21:26

1 Answers


if you want to use the current source code as it is. The html method rewrites all the contents of the id=readmore-btn-common element, so whenever you generate the id=readmore-btn-close element, why don't you add a click event to operate the function to return to the top?

jQuery('#readmore-btn-common') .html('<spanid="readmore-btn-close">Close</span>');
jQuery("#readmore-btn-close").on("click", function(){
  console.log("click");
});

However, I don't think it's a good idea to re-declare click event triggers every time, so instead of rewriting the whole element with the html function, why don't you try to change the string with the text function and add and delete class attributes?


2022-09-30 21:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.