Sanjeev K Sanjeev K - 10 days ago 6
HTML Question

Wrap/unwrap div in to another div on scroll jQuery

I am trying to wrap div in to another div using jQuery on scroll and then unwrap when scroll back, but every time I scroll its keep wrapping div, How do I make it work to once only?

This is the code I am trying

$(".scroller").scroll(function() {
if($(window).width() > 768)
{
if($(".scroller").scrollTop() > 245) {
$(".doctor_listing_wrapper").wrap("<div class='doctor_listing_wrapper_master'></div>");
}
else{
$(".doctor_listing_wrapper").unwrap("<div class='doctor_listing_wrapper_master'></div>");
}
}
});


The HTML is simple, just a div with some inner content

<div class="doctor_listing_wrapper">
<p>Content goes here</p>
<p>Content goes here</p>
<p>Content goes here</p>
</div>


Update JSfiddle Demo

Answer

you need to check, if the element already exists... the following example should resolve your problem (!$(".doctor_listing_wrapper_master").length)

$(".scroller").scroll(function() {
    if($(window).width() > 768)
    {
    if($(".scroller").scrollTop() > 245) {
      if(!$(".doctor_listing_wrapper_master").length){
           $(".doctor_listing_wrapper").wrap("<div class='doctor_listing_wrapper_master'></div>");
        }
      }   
      else{
       $(".doctor_listing_wrapper").unwrap("<div class='doctor_listing_wrapper_master'></div>");
      }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="doctor_listing_wrapper">
    <p>Content goes here</p>
    <p>Content goes here</p>
    <p>Content goes here</p>
 </div>