I have built my CMS around modules (ex: slideshow, footer, navigation,...) and I would like to track usage of those modules by using Google Analytics events.
What I have done is the following: In each PHP module, I have added a JS function that tracks the position of a given module and when the module becomes visible in the viewport, the Google Analytics part is triggered.
Here is the code:
init = 0;
$(window).scroll(function()
{
screenheight = $(window).height();
scrollposition = $(window).scrollTop()+screenheight;
divheight = $("[containername]").height();
divposition = $("[containername]").position().top;
if ((scrollposition>divposition) && (init==0))
{
ga('send', { 'hitType': 'pageview', 'page': 'blablabla', 'title': 'more blablabla' });
init = 1;
}
});
It's all working fine but... I have many modules and putting this in every module is probably not the most intelligent thing to do. So now I'm looking for a more generic solution.
Every module is encapsulated in a div with a unique ID. Each unique ID ends with -container, ex:navigation-container, slideshow-container,...
What I'd like to do is to detect if one of those -container div appears in the viewport (any of them) and if it is the case, fire the same JS. I have tried with .match and a regular expression but it doesn't look like it is able to detect individual divs.
I would also like to track clicks inside those divs in the same way. Today I have written individual JS for each module.
Any suggestions?
****** UPDATE ********** I have solved the click tracking part by using a filter + regexp:
$('div').filter(function() { return this.id.match(/container/); }).click(function()
{
// do something
});
This allows me to have one generic click tracking for all clicks in the divs I want to track.
Now I'm still looking for a solution for the other issue (detecting in viewport)
Thanks Laurent