How do I make the logo disappear when I roll the page?

Asked

Viewed 1,856 times

4

I am creating a menu with version 4.1.3 of Bootstrap and would like to know how I can do when scrolling the page to soon disappear? In this case, only the menu should be.

Obs.: When returning the initial position to soon should reappear.

The menu is already set

<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <a class="navbar-brand" href="#">
    <img id="brand-image" alt="Website Logo" src="img/logo.png" />
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
      <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
      <a class="nav-item nav-link" href="#">Features</a>
      <a class="nav-item nav-link" href="#">Pricing</a>
      <a class="nav-item nav-link disabled" href="#">Disabled</a>
    </div>
  </div>
</nav>

CSS

#brand-image {
  height: 100px;
  float: center;
}

.navbar {
  position: fixed;
  padding-top: 15px;
  top: 0;
  z-index: 2;
  width: 100%;
}

.navbar-brand {
  position: absolute;
  left: 50%;
  margin-left: -50px;
  display: block;
  margin-top: 18px;
}
  • First: what version of bootstrap are you using?

  • The latest version 4.1.3

3 answers

4

First to be valid for this purpose it would be interesting to leave your menu always fixed at the top of the page. For this you need to use the class .fixed-top in navbar (see at official documentation).

Then as a simple jQuery (jQuery is already part of Bootstrap so it’s okay to use it) it is possible to make a fadeOut and fadeIn at the event scroll.

To see the result see the example below. I left commented the place where you control the "distance" of scroll before the logo fades.

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 140) { // 140 é a distancia que vc rola antes da logo sumir
    $("#brand-image").fadeOut();
  } else {
    $("#brand-image").fadeIn();
  }
});
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
  <a class="navbar-brand" href="#">
    <img id="brand-image" alt="Website Logo" src="https://placecage.com/50/50" />
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
      <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
      <a class="nav-item nav-link" href="#">Features</a>
      <a class="nav-item nav-link" href="#">Pricing</a>
      <a class="nav-item nav-link disabled" href="#">Disabled</a>
    </div>
  </div>
</nav>

<div style="height:1000px; width: 100ps;"></div>

  • it wouldn’t be interesting to have a little explanation of how to make a Throttle or debauchery event Handler? For if you put a console.log in event Handler will see that the function performs many times and can slow down the page.

  • And leave the $("#brand-image") out of Handler too, for reasons of performance.

  • @fernandosavio has how to make a debauch simply? just use one _.debounce before Function and at the end put the value of the "range"? I will test here... I do not understand much of jQuery :)

  • I think the easiest way is to use the mockery of the lodash. So the code is short and does not escape much of the scope of the question. Anything I make a fiddle in the early afternoon and comment here for you to analyze

  • @fernandosavio I found this material, it looks very interesting! https://www.origamid.com/codex/diminur-o-menu-fixo-ao-scroll/ _.debounce

  • That’s right! I think it’s important to talk about these techniques when we talk about events that are repeated many times a second like scroll or dragover

  • @fernandosavio I am few who have this concern is true... I myself do not have enough knowledge to use these techniques in my answer. But I will give a studied in the subject! I think the fault of Chrome consume so much memory many times and because the dev itself that did not optimize the code... But there is talk to Chat STOF

  • I posted an answer as a complement. It will be good to leave together in case someone falls here.

Show 3 more comments

3


This answer is merely a complement to reply from @hugocsl.

When it comes to events like scroll, resize or mousemove It is always important to remember that they are launched several times per second as the user interacts with the page. That is, depending on what you do within the function Handler of the event, you can slow down your page (e.g., access the DOM).

If there is no need to perform this function so repeatedly you can use the techniques debounce and throttle, which serve to limit the execution of a function over a period of time.

The debounce will wait for the event to stop launching for X seconds before activating the function Handler.

The throttle will only allow the function Handler run every X seconds.

Example:

// Só vai executar quando o usuário para de digitar por 1 segundo
$elemento.on('keyup', _.debounce(function() {
    console.log('debounce');
}, 1000));


// Enquanto o usuário seguir digitando, vai executar a cada segundo
$elemento.on('keyup', _.throttle(function() {
    console.log('throttle');
}, 1000));

Another optimization, much simpler, is to save the DOM element in a variable to use later, since access to the DOM is costly in terms of performance.

Instead of:

$(window).scroll(function() {
    // é executado cada vez que 'scroll' é lançado
    $("#brand-image").fadeOut();
});

It’s more performative to use:

// É executado apenas uma vez
var $brandImage = $("#brand-image");

$(window).scroll(function() {
    // Usa a refêrencia salva anteriormente
    $brandImage.fadeOut();
});

And the last and least impactful is that when you do:

$(window).scrollTop()

You are converting a Domelement into a jQuery object, it is not as expensive as accessing the DOM, but it can still be easily replaced by the property window.pageYOffset which is native and compatibility is acceptable (IE 9+).


Below follows the code of @hugocsl with the Handler of normal events, with debauch and with Throttle to illustrate the importance of these techniques.

PS: In the examples I am using the methods _.debounce() and _.throttle() library lodash.


Normal

var $brandImage = $("#brand-image");
var $scrollHelper = $("#scroll-helper");
var count_scroll = 0;

$(window).scroll(function() {
  $scrollHelper.html("scroll triggered: " + ++count_scroll);
  if (this.pageYOffset >= 140) { // 140 é a distancia que vc rola antes da logo sumir
    $brandImage.fadeOut();
  } else {
    $brandImage.fadeIn();
  }
});
#scroll-helper {
  position: fixed;
  top: 80px;
  left: 10px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
  <a class="navbar-brand" href="#">
    <img id="brand-image"src="https://placecage.com/50/50" />
  </a>
  <button class="navbar-toggler">
    <span class="navbar-toggler-icon"></span>
  </button>
</nav>

<div style="height:1000px; width: 100ps;"></div>
<span id="scroll-helper">scroll triggered: 0</span>


Debauchery

var $brandImage = $("#brand-image");
var $scrollHelper = $("#scroll-helper");
var count_scroll = 0;

$(window).scroll(_.debounce(function() {
  $scrollHelper.html("scroll triggered: " + ++count_scroll);
  if (this.pageYOffset >= 140) { // 140 é a distancia que vc rola antes da logo sumir
    $brandImage.fadeOut();
  } else {
    $brandImage.fadeIn();
  }
}, 300));
#scroll-helper {
  position: fixed;
  top: 80px;
  left: 10px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
  <a class="navbar-brand" href="#">
    <img id="brand-image"src="https://placecage.com/50/50" />
  </a>
  <button class="navbar-toggler">
    <span class="navbar-toggler-icon"></span>
  </button>
</nav>

<div style="height:1000px; width: 100ps;"></div>
<span id="scroll-helper">scroll triggered: 0</span>


Throttle

var $brandImage = $("#brand-image");
var $scrollHelper = $("#scroll-helper");
var count_scroll = 0;

$(window).scroll(_.throttle(function() {
  $scrollHelper.html("scroll triggered: " + ++count_scroll);
  if (this.pageYOffset >= 140) { // 140 é a distancia que vc rola antes da logo sumir
    $brandImage.fadeOut();
  } else {
    $brandImage.fadeIn();
  }
}, 300));
#scroll-helper {
  position: fixed;
  top: 80px;
  left: 10px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
  <a class="navbar-brand" href="#">
    <img id="brand-image"src="https://placecage.com/50/50" />
  </a>
  <button class="navbar-toggler">
    <span class="navbar-toggler-icon"></span>
  </button>
</nav>

<div style="height:1000px; width: 100ps;"></div>
<span id="scroll-helper">scroll triggered: 0</span>

  • 1

    Face this answer is so interesting that it deserved a question just for it rss. Thank you very much for the clarification!

  • 1

    Thanks! Glad you could help!

  • Excellent answer. : ) +1

3

1: You did not inform which version of bootstrap are using.

2: You did not inform if you have already managed to leave the fixed menu.

With the absence of this information, I made an example using the version 4.1 of bootstrap .

Note that I added the class .sticky-topin the navbar to stay fixed. It is worth remembering that this class uses a position sticky, what is not yet supported in IE 11. To access the full list of supported browsers, see here. If you prefer, use the class fixed-top.

Basically you’ll need to stay escultando the event of scroll and check when it arrives at a certain value you set, after that you hide and show the image as needed.

The variable length has been declared for you to test with other values.

I recommend taking the comment from console.log() to see how the scroll.

$(document).on('scroll', function() {
  let scroll = $(document).scrollTop();
  let length = 100;
  //console.log('scroll: '+ scroll);

  if (scroll > length) {
    $('#brand-image').hide();
  } else {
    $('#brand-image').show();
  }
});
.main {
  height: 1000px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg sticky-top navbar-dark bg-primary">
  <a class="navbar-brand" href="#">
    <img id="brand-image" alt="Website Logo" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgZ_2jtGVpp0G-t966PJgbdGVgJ71RFXH7_5syQEl3WNaPBUmr" />
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
      <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
      <a class="nav-item nav-link" href="#">Features</a>
      <a class="nav-item nav-link" href="#">Pricing</a>
      <a class="nav-item nav-link disabled" href="#">Disabled</a>
    </div>
  </div>
</nav>
<div class="main">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.