Paul
Paul

Reputation: 3368

Adding a div at a certain point

I am trying to show an id at a certain point. I looked at other examples from here and modeled mine just like one. However, my id is not displaying once I get to the scroll point and I am not sure. The id I want to show mobile-transparent, I have set the position to absolute and added a z-index to try to troubleshoot that.

Does anyone see what I am doing wrong?

$(document).ready(function() {
    $("#mobile-transparent").hide(); //hide your div initially
    var topOfOthDiv = $("#green").offset().top;
    $(window).scroll(function() {
        if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
            $("#mobile-transparent").show(200); //reached the desired point -- show div
        }
    });
});
#blue, #red, #green {
  height: 500px;
  width: 100%;
}
#blue {
  background: blue;
}
#red {
  background: red;
}
#green {
  background: green;
}
#mobile-transparent {
  padding: 10px;
  background-color: #000;
  opacity: 0.7;
  width: 40px;
  z-index: 1;
  position: absolute;
  top: 20%;
  right: 5%;
}

.mobile-down-button {
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blue"></div>
<div id="red"></div>
<div id="green"></div>
<div id="mobile-transparent">
  <img src="http://optimumwebdesigns.com/icons/mobile_menu_white.png" class="mobile-down-button" alt="menu" height="35px" width="35px">
</div>

Upvotes: 0

Views: 251

Answers (1)

ketan
ketan

Reputation: 19341

Give position:fixed instead position:absolute;.

Because position:absolute set it to particular position given. Not display when you scroll.

$(document).ready(function() {
    $("#mobile-transparent").hide(); //hide your div initially
    var topOfOthDiv = $("#green").offset().top;
    $(window).scroll(function() {
  
    if ($(this).scrollTop() > topOfOthDiv) {
       $('#mobile-transparent').fadeIn();
     } else {
       $('#mobile-transparent').fadeOut();
     }
       
    });
});
#blue, #red, #green {
  height: 500px;
  width: 100%;
}
#blue {
  background: blue;
}
#red {
  background: red;
}
#green {
  background: green;
}
#mobile-transparent {
  padding: 10px;
  background-color: #000;
  opacity: 0.7;
  width: 40px;
  z-index: 1;
  position: fixed;
  top: 20%;
  right: 5%;
}

.mobile-down-button {
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blue"></div>
<div id="red"></div>
<div id="green"></div>
<div id="mobile-transparent">
  <img src="http://optimumwebdesigns.com/icons/mobile_menu_white.png" class="mobile-down-button" alt="menu" height="35px" width="35px">
</div>

Upvotes: 1

Related Questions