JQuery - change class when entering div area (but not with mouse)

I came across great sites that had a great feature that I will try to explain here.

I tried to study the sources of .js, but since I am a beginner, I could not decrypt the mini versions. :(

Say I have the following markup:

<ul id="posts">

<li id="photo"> Lorem ipsum </li>

<ii id="quote"> Lorem ipsum dolor </li>

</ul>

<div id="logo">My Logo</div>

What I want to do: when a user enters the li # photo area, jQuery will change the background color of #navigator, say blue. If the user keeps scrolling down, he enters the quote li #, and when he enters the area, jQuery will change the color of #navigator bg to red.

When I say enter region, I mean scrolling, not mouse hovering.

There's a Tumblr theme that does what I'm trying to explain:

http://www.figueric.com/ (scroll down and see the navigator on the right)

, , .addclass, , , , , , li #.

, , ?

+3
2

jQuery scroll(), . , .

, : http://jsfiddle.net/BKnzr/1/

CSS

html,body {
    padding:0;
    margin:0;
    clip: auto;
    overflow: hidden;
}

#navigator {
    text-align: center;
    background: green;
    color: white;
    position: absolute;
    top: 150px;
    right: 50px;
    overflow: hidden;
    width: 60px;
    height: 250px;
}
#posts {
    position:absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    overflow: auto;
}
#photo,#quote {
    margin-top: 800px;
    height: 300px;
}
โ€‹

HTML

<div id="navigator">Scroll down to change background</div>

<ul id="posts">
    <li id="photo">photo section</li>
    <li id="quote">quote section</li>
</ul>โ€‹

JQuery

    // cache the elements
var $nav = $('#navigator');
var $photo = $('#photo');
var $quote = $('#quote');
var $posts = $('#posts');

   // get the view area of #posts
var top = $posts.offset().top;
var bottom = top + $posts.height();

   // run code when #posts is scrolled
$posts.scroll(function() {
    if($quote.offset().top < bottom) {
        $nav.css('backgroundColor', 'red');
    } else if ($photo.offset().top < bottom) {
        $nav.css('backgroundColor', 'blue');
    } else {
        $nav.css('backgroundColor', 'green');
    }
});

+3

jsbin: http://jsbin.com/ewuti4/edit

document window.scroll() .scrollTop(), .height() , - .offoff(). top. / .

$(window).scroll(function(){
  if ($(window).scrollTop() + $(window).height() >= $('#quote').offset().top)
  {
    $('#nav').css({
      'backgroundColor': 'blue',
      'border': '5px solid black',
      'top': $(window).scrollTop(),
      'left': 0
    });
  }
0

Source: https://habr.com/ru/post/1752487/


All Articles