3

Imagine I'm using the following code on my website

<div class="wrapper">

<nav class="main-nav">
Hello, I am navigation
</nav>

</div>

When an object with the selector "wrapper" is within the viewport, I would like to reference an additional selector in the <nav> element.

Therefore

When an element with "wrapper" is in the viewport, the HTML is

<div class="wrapper">

<nav class="main-nav in-view">
Hello, I am navigation
</nav>

</div>

Otherwise the code is

<div class="wrapper">

<nav class="main-nav">
Hello, I am navigation
</nav>

</div>
Adam Scot
  • 1,371
  • 4
  • 21
  • 41
  • You'll need to look at jQuery's `scoll()` method. This will involve calculating your current position, and the position of the wrapper element you're interested. You will also need to know the height and width of the viewport. You can use `.height()` and `width()` for that. When the wrapper element is at a position within the viewport, you can add class to your wrapper element using `.addClass(in-view)`. – An0nC0d3r Dec 14 '15 at 20:35
  • Related: [How to tell if a dom element is visible in the current viewport](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport) – Berendschot Dec 14 '15 at 20:37

1 Answers1

1

Have you tried using a jQuery function like:

if ($(".wrapper").length) {
/* Checks if wrapper exists */
  $(".main-nav").addClass("in-view");
}
.in-view {
  color: red;
}
<div class="wrapper">
  <nav class="main-nav">
    Hello, I am navigation
  </nav>
</div>

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Berendschot
  • 3,026
  • 1
  • 21
  • 43