user3648416
user3648416

Reputation: 87

Want JavaScript script to run when the Div is in the viewport

I want to run a JS script when a particular div comes into the viewport/is visible.

The div will always be visible, but when the user scrolls it in to view.

I have created a JSFiddle with the example:

Example http://jsfiddle.net/sv8boe9u/21/

JS

consoleText(['HELLO,', 'HERE IS A BIT ABOUT ME,', 'ENJOY!'], 'text', ['#333', '#333', '#333']);

function consoleText(words, id, colors) {

  "use strict";
  if (colors === undefined) {
    colors = ['#fff'];
  }
  var visible = true;
  var con = document.getElementById('console');
  var letterCount = 1;
  var x = 1;
  var waiting = false;
  var target = document.getElementById(id);
  target.setAttribute('style', 'color:' + colors[0]);
  window.setInterval(function() {

    if (letterCount === 0 && waiting === false) {
      waiting = true;
      target.innerHTML = words[0].substring(0, letterCount);
      window.setTimeout(function() {
        var usedColor = colors.shift();
        colors.push(usedColor);
        var usedWord = words.shift();
        words.push(usedWord);
        x = 1;
        target.setAttribute('style', 'color:' + colors[0]);
        letterCount += x;
        waiting = false;
      }, 1000);
    } else if (letterCount === words[0].length + 1 && waiting === false) {
      waiting = true;
      window.setTimeout(function() {
        x = -1;
        letterCount += x;
        waiting = false;
      }, 1000);
    } else if (waiting === false) {
      target.innerHTML = words[0].substring(0, letterCount);
      letterCount += x;
    }
  }, 120);
  window.setInterval(function() {
    if (visible === true) {
      con.className = 'console-underscore hidden';
      visible = false;

    } else {
      con.className = 'console-underscore';

      visible = true;
    }
  }, 400);
}

To clarify, I want it to start at 'Hello' when it is actually in viewport. Any ideas?

Thanks.

Upvotes: 0

Views: 1014

Answers (2)

scotty3
scotty3

Reputation: 153

Using the jQuery scroll() and scrollTop() functions you can specify a height in px that triggers another function when reached such as:

$(window).scroll(function () {
    if ($(this).scrollTop() >= 50) {   // If page is scrolled more than 50px
        doSomething();                // call this function
    } 
});

jQuery Scroll and Scroll Top

Upvotes: 3

Newtorn Moses
Newtorn Moses

Reputation: 531

you can use the scroll function ..like create a function that runs until wen you reach that element u are targeting.. then call the alert('hello');

window.addEventListener('scroll', (e) => {

        console.log(window.scrollY)
        if (window.scrollY == 705) {
            alert('got ya')
            // do your stuff here boss
        }
    })

you should make sure to find that scroll position wen yo element comes into view and then put it wr 705 is.. hope this helps ya

Upvotes: 0

Related Questions