capture onClick with if else

0

I have this JQuery (thanks to the help of a colleague here) in which when I scroll upwards the header appears and when I scroll downwards it disappears.

The thing is that I want to click on a certain link also , but my still ignorance can not get it out.

How do I get the click on the link? My intention is that whether you click on it or if you scroll up, the header appears.

$(document).ready(function() {


  var lastScrollTop = 0;

  $(window).scroll(function(event) {

    var st = $(this).scrollTop();

    if (st < lastScrollTop || $('#Conoceme').click(function());) {
      document.getElementById("Cabecera").style.display = "block"
    } else {
      document.getElementById("Cabecera").style.display = "none"
    }

    lastScrollTop = st;
  });
});
    
asked by NEA 20.09.2017 в 10:51
source

2 answers

2

You can create a function mostrarCabecera to show or hide the header and that you can call from the two event handlers: scroll and click :

$(document).ready(function() {


  var lastScrollTop = 0;
  
  function mostrarCabecera(mostrar){
    document.getElementById('Cabecera').style.display =
      mostrar ? 'block' : 'none';
  }

  $(window).scroll(function(event) {

    var st = $(this).scrollTop();
    
    mostrarCabecera(st < lastScrollTop);

    lastScrollTop = st;
  });
  
  $('#Conoceme').click(function(e) {
    e.preventDefault();
    mostrarCabecera(true);
  });
});
body{
  padding-top: 400px;
}

#Cabecera{
  height: 100px;
  width: 100%;
  background-color: #cccccc;
  display: none;
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Cabecera">Cabecera</div>
<a id="Conoceme" href="#">Conóceme</a>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
    
answered by 20.09.2017 в 11:03
0

The code you have put contains the scroll event as you say. To know when they click, you need .click . Put it before or after the $(window).scroll(function(event) , not inside.

$( "#target" ).click(function() {
  document.getElementById("Cabecera").style.display = "block"
});

Replace #target with the link in question you want to control.

    
answered by 20.09.2017 в 10:58