0

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')
 }
})
asked Apr 30, 2020 at 17:48

2 Answers 2

1

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')
 }
})
answered Apr 30, 2020 at 17:51
Sign up to request clarification or add additional context in comments.

Comments

0

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;
 }
})

answered Apr 30, 2020 at 18:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.