Detect Scroll up and Down event with jQuery

In this tutorial, we will show you how to detect whether you scroll up or down using jQuery which will allow you to perform an action based on the direction of scrolling.

Here is how you can achieve this with few very lines of jQuery:-


 $(function(){
	 var lastScrollTop = 0, delta = 5;
	 $(window).scroll(function(){
		 var nowScrollTop = $(this).scrollTop();
		 if(Math.abs(lastScrollTop - nowScrollTop) >= delta){
		 	if (nowScrollTop > lastScrollTop){
		 		// ACTION ON
		 		// SCROLLING DOWN 
		 	} else {
		 		// ACTION ON
		 		// SCROLLING UP 
			}
		 lastScrollTop = nowScrollTop;
		 }
	 });
 });

The code above is based on three variable lastScrollTop, nowScrollTop and delta.

  • lastScrollTop: This variable stores the last Y-position of website window, and by the last position we mean the number of pixels hidden from view above scrollable area. The initial value of this variable is set to 0 as the scroll bar is at the very top.
  • nowScrollTop: This variable stores the number of pixels that are hidden above the scrollable area right now as you are scrolling.
  • delta: delta is like a threshold, it is a variation by which we need scroll detection to occur. for example you might not like the scroll detection function to run when a user scrolls accidentally like around 4px. So we set delta variable to 5px which will prevent accidental or very small scrolling that usually happens on touch screens.

Now we know what the variables are, here is the code explained line by line:-

  • $(function(){…}) will run the code once document is ready.
  • var lastScrollTop = 0, delta = 5; sets the value of two variables.
  • $(window).scroll(function(){…}) runs code enclosed inside it when user scrolls window.
  • var nowScrollTop = $(this).scrollTop(); sets value of third variable, which is equal to the value of scrolling that occurred.
  • if(Math.abs(lastScrollTop – nowScrollTop) >= delta){…} runs the code inside it only if absolute difference between lastScrollTop and nowScrollTop is less than delta (i.e. 5px). We are taking positive value because the distance between to scrolling values is always positive (its scaler).
  • if (nowScrollTop > lastScrollTop){…} if current scrolling value is greater than last scroll value then downward scrolling is occurred and will run the code inside this statement.
  • else upward scrolling is occurred.
  • Finally we set the lastScrollTop = nowScrollTop; because now the last scroll value become the previous nowSrollTop value.

I hope this helps!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How To Send Google Analytics Event with PHP

Today we are going to show you a method of sending a Google Analytics Event with PHP. You might be asking yourself why you would want to do this but we came across a scenario where we wanted to send an event to Google Analytics on a WordPress user registration hook.

Sending Event using Javascript

Here is an example of how you would send a GA Event using JavaScript:


ga('send', {
    hitType: 'event',
    eventCategory: 'Registration',
    eventAction: 'Submit',
    eventLabel: 'New User Registration'
});

And here is how you would send the event using PHP

Yes, you can send the same event using PHP on the service-side by sending a POST request to Google Analytics API with the data of the event. We have used Curl to make the request as shown below:


// GA curl
$req = curl_init('https://www.google-analytics.com/collect');

curl_setopt_array($req, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_POSTFIELDS =>
    'v=1&t=event&tid=UA-XXXXXXXX-X&cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&ec=Console&ea=submit&el=Feedback%20Form%20Submission'
));
// Send the request
$response = curl_exec($req);

The overview of the POST requests

As we can see from the above post request, this is made up of 7 different parameters:


v=1&t=event&tid=UA-XXXXXXXX-X&cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&ec=Console&ea=submit&el=Feedback%20Form%20Submission

To better understand what this means, see the table below:

Param Name Meaning Value
v Version 1
t Type event
tid Tracking ID (Your Tracking ID)
cid Client ID (Your GA Client ID)
ec Event Category Registration
ea Event Action Submit
el Event Label New%20User%20Registration

Note: The last 3 parameters (ec, ea and el) are the same ones in which you use in the JS code snippet above, however, we need to URL encode these values.

At this stage, you might be wondering how you can get the Client ID, no problem, we have you covered here too.

To get the Client ID, simply open up the website which has the Google Tracking code for Google Analytics, we did this with Google Chrome… Within the console, go to the ‘Application’ tab and click on ‘Cookies’ as shown below:

This tracking code value with become your cid or Client ID.

Once you have implemented this, you can test to see if it is working by heading over to Google Analytics, selecting the option for ‘Realtime’ and then clicking on ‘Events’, if this has worked, you should see something as shown below:

Bonus Tip

Did you know you can use events to track goals?

Well, we did this for a specific client and we can create this in Google Analytics now by heading over to the ‘Admin’ area and then clicking on the ‘Goals’ link.

When creating the goal, we selected the ‘custom’ goal setup. Now, name your goal and then select the ‘Event’ radio option. Within the Goal Details, all we have to do is set the Category to the name we defined within ec, which in our case was ‘Registration’.

Now we have a goal in place which will look as follows:

And there we have it!

Not only have we now passed an event in Google Analytics using PHP instead of JS, but we have now created a goal which is measured by the event. Pretty neat right?

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share