1

Well the thing is really simple, I'm a newbi on Js and know almost nothing, the thing is that I want to change a navbar's style but I just can do it when it reaches a specific amount of pixels, I would like to make it change when it reaches the next div id of the page, this is the code:

$(window).scroll(function() {    
  var scroll = $(window).scrollTop();

  if (scroll >= 500) {
    $(".fondoa").addClass("fondoazul");
  } else {
    $(".fondoa").removeClass("fondoazul");
  }
});

Thank you so much for your help

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56

2 Answers2

2

You can find out the the distance from the top of the div element using:

$("#divid").offset().top

You can use it to add classes when you reach the element:

$(window).scroll(function() {
  var idLocation = $("#divid").offset().top
  var scroll = $(window).scrollTop();

  if (scroll >= idLocation) {
    $(".fondoa").addClass("fondoazul");
  } else {
    $(".fondoa").removeClass("fondoazul");
  }
});
Deep
  • 9,594
  • 2
  • 21
  • 33
0

you can do this with javascript and jquery below are examples

//for getting window height

var win_height = $(window).height();
//if(win_height)
console.log(win_height)

//for getting window id and scrolling to it via javascript
function scrollWin() {
    document.getElementById('five').scrollIntoView()
}


//for getting window id and scrolling to it using jquery
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( window ).scroll(function() {
  $( "#five" ).css( "display", "inline" ).fadeOut( "slow" );
});
body {
    width: 6000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="scrollWin()">Click me to scroll</button>
<br>
<br>

<p></p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p></p>

<br>
<br>
<br>
<p >500 500 500 500 500 500 500 500 500 500 500 500 500 500 <span id="five">Scroll happened!</span></p><br>
<br>
<br>
<br>
<br>
<br>

<br>
<br>
<br>
<br>
<br>
<br>
<br>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>