Cristian
Cristian

Reputation: 67

Make run javascript function just once

I'm trying to make run this script on my website. It triggers an alert when id in viewport. the problem is that the alert keeps running while id in the viewport. can't make it run just one time. How could i do this?

function inViewport( element ){
  // Get the elements position relative to the viewport
  var bb = element.getBoundingClientRect();
  // Check if the element is outside the viewport
  // Then invert the returned value because you want to know the opposite
  return !(bb.top > innerHeight || bb.bottom < 0);
}

var myElement = document.querySelector( 'holaTest' );
// Listen for the scroll event
document.addEventListener( 'scroll', event => {
  // Check the viewport status
  if( inViewport( myElement ) ){
        alert('hello there')
  }
})

Upvotes: 0

Views: 89

Answers (2)

Tony M
Tony M

Reputation: 741

Adding to Andre's answer, you can check alert only once when it's on the viewport. That way, it alerts once but every time the element is in viewport:

function inViewport( element ){
  // Get the elements position relative to the viewport
  var bb = element.getBoundingClientRect();
  // Check if the element is outside the viewport
  // Then invert the returned value because you want to know the opposite
  return !(bb.top > innerHeight || bb.bottom < 0);
}

var myElement = document.querySelector( '.holaTest' );
// Listen for the scroll event
var t = true;
document.addEventListener( 'scroll', event => {
  // Check the viewport status
  if( inViewport( myElement ) && t){
        alert('hello there');
        console.log("try");
        t = false;
  } 
  if (!inViewport(myElement)) {	
  	t = true;
  }
})

Upvotes: 0

Andr&#233; Morais
Andr&#233; Morais

Reputation: 63

you can do this: add a Boolean variable that controls the first time

var bool=true;
function inViewport( element ){
  // Get the elements position relative to the viewport
  var bb = element.getBoundingClientRect();
  // Check if the element is outside the viewport
  // Then invert the returned value because you want to know the opposite
  return !(bb.top > innerHeight || bb.bottom < 0);
}

var myElement = document.querySelector( 'holaTest' );
// Listen for the scroll event
document.addEventListener( 'scroll', event => {
  // Check the viewport status
  if( inViewport( myElement ) && bool){
    bool=false;
    alert('hello there')
  }
})

Upvotes: 1

Related Questions