Virgo Web Design Blog

A Screensaver Built in Pure Javascript, HTML, and CSS – Finished Example

A Screensaver Built in Pure Javascript, HTML, and CSS – Finished Example

There seem to be a few other javascript based screensavers out there, but not really a huge selection. I recently got the opportunity to build a screensaver for a hybrid mobile application, so I figured I would take it a step further and add some documentation and allow for parameters to be passed through so that it could be used as a plugin.

The screensaver is built for responsive scaling, so it uses REMs instead of pixels, and takes the base font size to calculate element positioning. I also added CSS transitions to allow for your image to fade in and fade out as it randomly positions itself across the screen on a 6 second timer. Event listeners are also added for detecting touches or clicks so that it can restart the timeout to initiate the screensaver again. I added a parameter to pass through which will stop the screensaver after a set time, which can be useful to trigger other functions after the screensaver is completed.

Click the link below to try out a demo (wait a few seconds for the animation to start)

Demo the screensaver

Parameter documentation

There are 4 different configuration options for the screensaver plugin. All of these values are optional, if none are set the defaults will be used.

  • timeout: Accepts a numeric value in milliseconds. This sets how long to wait until the screensaver is activated. The default value is 60000 (10 minutes)
  • width: Accepts a numeric value in REMs which sets the width of your element. The default value for this is 25.
  • height: Accepts a numeric value in REMs which sets the height of your element. The default value for this is 25.
  • exitTimeout: Accepts a numeric value in milliseconds. This sets how long to wait after the screensaver is initiated to exit the screensaver. The default for this option is disabled, so it will only activate if you provide a value.

Here is an example of usage:



    startScreenSaver({
        timeout: 5000,
        width: 30,
        height: 30,
        exitTimeout: 1000,
    }); 

To get the screensaver up and running all you need is to add the CSS and javascript, and change the background image of the badge element to one in your environment. This is not reliant on any frameworks like jQuery, so it should easily integrate with any project.

Download the plugin files

Here is the javascript being used in the screensaver:



var screenSaver = {};


function startScreenSaver(options) {

  //* attach event listeners to exit screensaver
  attachScreenSaverEventListeners();

  if(!screenSaver.initiated) {

    //* set screensaver options
    screenSaver.options = {

       timeout: options.timeout || 60000, //* default timer to start screensaver is 10 minutes

        width: options.width || 25,   //* default width is 25rem

        height: options.height || 25, //* default height is 25rem

        exitTimeout: options.exitTimeout || null, //* default timer to exit screensaver is disabled

    }

    //* create elements
    var overlay = document.createElement("div");

    overlay.setAttribute('class', 'screensaver-overlay');

    document.body.appendChild(overlay);

    var createBadge = document.createElement("div");

    createBadge.setAttribute('id', 'saver-badge');

    document.body.appendChild(createBadge);

    createBadge.style.width = screenSaver.options.width + 'rem';

     createBadge.style.height = screenSaver.options.height + 'rem';

  }

  document.getElementsByTagName("body")[0].classList.remove('screensaver');

  screenSaver.initiated = true;

  screenSaver.setTimeoutValue = screenSaver.options.timeout; 

  screenSaver.setTimeoutExit = screenSaver.options.timeoutExit; 

  screenSaver.setTimeout = null; //* clear timeout

  screenSaver.inProgress = false;

  screenSaver.timerStarted = false;

  clearTimeout(screenSaver.setTimeout);

  screenSaver.setTimeout = setTimeout(function() {
    
    document.getElementsByTagName("body")[0].classList.add('screensaver');

      screenSaver.inProgress = true;

      var saverBadge = document.getElementById("saver-badge");

      clearInterval(screenSaver.setInterval); //* clear badge display interval

      screenSaver.setInterval = null;

      //* get dimensions in em
      var windowHeight = window.outerHeight / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size'));

      var windowWidth = window.outerWidth / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size'));

      screenSaver.setInterval = setInterval(function() {

        if (screenSaver.inProgress === true) {

          saverBadge.classList.remove('visible');

          setTimeout(function() {

            saverBadge.offsetWidth = saverBadge.offsetWidth;

            saverBadge.classList.add('visible');

          },1);

          var saverTopValue = Math.floor(Math.random() * windowHeight) - screenSaver.options.width;

          var saverLeftValue = Math.floor(Math.random() * windowWidth) - screenSaver.options.height;

          if (saverTopValue <= 0) { //* make sure the badge doesn't go off the screen

            saverTopValue = saverTopValue + 15;

          }

          if (saverLeftValue <= 0) {

            saverLeftValue = saverLeftValue + 15;

          }

          saverBadge.style.top = saverTopValue + 'rem';

          saverBadge.style.left = saverLeftValue + 'rem';

          if(screenSaver.timerStarted === false && screenSaver.options.exitTimeout != null) {

            startScreenSaverTimer();

          }
        }
      }, 6000);

    }, screenSaver.setTimeoutValue);
}

function startScreenSaverTimer() {

  screenSaver.timerStarted = true;

  setTimeout(function() {

    stopScreenSaver();

  }, screenSaver.setTimeoutExit);

}

function stopScreenSaver() {

  startScreenSaver();

  clearInterval(screenSaver.setInterval);

  document.getElementsByTagName("body")[0].classList.remove('screensaver');

  screenSaver.timerStarted = false;

}

function attachScreenSaverEventListeners() {

  var events = ['touchstart', 'mousedown', 'mousemove', 'touchmove', 'keypress' 'scroll'];

  var resetScreenSaver = function(e) {

    if (screenSaver.inProgress) {

      e.stopPropagation();

      e.preventDefault();

    }

    clearTimeout(screenSaver.setTimeout);

    clearInterval(screenSaver.setInterval);

    document.getElementsByTagName("body")[0].classList.remove('screensaver');

    startScreenSaver();

  }

  var checkClick = function(e) {

    if (screenSaver.inProgress) {

      startScreenSaver();

    }

  }

  var bindEvents = function(eventName) {

    document.addEventListener(eventName, screenSaver.initialize);

    //* bind click as fallback for touchstart and mousedown
    document.addEventListener('click', checkClick);

  }

  var unbindEvents = function(eventName) {

    document.removeEventListener(eventName, screenSaver.initialize);

  }

}    

Free Plugin! Adaptive Images Plugin for Joomla 2.5...
Checklist of Important Things to Consider When Red...
 

Comments

No comments made yet. Be the first to submit a comment
Guest
Saturday, 09 December 2023

LATEST ON OUR BLOG

OUR YELP REVIEWS

  • Virgo Web Design recently completed my website MeetPeopleChicago.com. Jerry was easy to work with, was attentive to my questions and was on top of things from start to finish. In addition he was very knowledgable and up to date on the latest technologies. I am very pleased with the final product and I will surely use him again for future enhancements. Thank you Jerry for the great work you have done!

    PETER S.

    Meet People Chicago

  • As a marketing communications person who knew my company needed an up-to-date website built in Joomla, I was very happy we found [Virgo Web Design]. I understood things from a content perspective, but when it came to back-end design and architecture, my hands were tied. [Virgo Web Design] was so knowledgeable and easy to work with, and was always available to answer questions, make tweaks, walk me through front-end editing tasks...you name it. [Virgo Web Design]'s accessibility and can-do attitude made such a difference to our entire team, and I hope I always thanked [them] enough for helping me through the client-side part of the web redesign process.

    CORRIE M.

    Aptude

  • "[Virgo Web Design] did an amazing job on my non-profit's website, ghhaven.org. [They] put our site together quickly and with all of the elements we requested - plus, [they] had a lot of great recommendations for things that we hadn't even considered for the site. [They were] very helpful throughout the process of getting our site launched and I found [them] to be quick in responding to all of my questions/requests as well. [They] even helped us get our business emails set up!

    I would definitely recommend Virgo Web Design as a go-to for all of your web design/development needs. I will definitely be using [them] again in the near future!"

    FRITZIE S.

    Genesis Hopeful Haven

  • [Virgo Web Design] has developed and designed multiple websites for me over the years. [Their] team are exceptionally skilled technicians. Their communication is easy to understand, and they are very proficient - even when near-end deadlines are demanding. Hiring Jerry Virgo and his team is one of the best decisions I have made for my company.

    Michael W

    One Chicago Realty

  • I've used Yahoo sitebuilder for several years and my e-commerce website was due for an overhaul. I asked around & received several recommendations from friends & other small businesses.

    Many of the other referrals came from Web design firms & had significantly higher overheads/billing rates...We had a tight timeline & [they were] very diligent at following up to avoid production delays at time when I was extremely busy. [They] did a nice all around job improving my SEO optimization, creating a polished final product, and documenting the back end with an easy to use manual.

    After the site when live, [they] stood by & helped me troubleshoot unanticipated events & helped me create work arounds.

    Chris H.

    City Tree Delivery

  • [Virgo Web Design] knocked out a full rebuild of our site in a few weeks, guided us through things we didn't understand with ease and calm and gave great advice, training and follow up service

    Nicholle D.

    DANK Haus

5000 characters left

LATEST ON OUR BLOG

OUR YELP REVIEWS

  • Virgo Web Design recently completed my website MeetPeopleChicago.com. Jerry was easy to work with, was attentive to my questions and was on top of things from start to finish. In addition he was very knowledgable and up to date on the latest technologies. I am very pleased with the final product and I will surely use him again for future enhancements. Thank you Jerry for the great work you have done!

    PETER S.

    Meet People Chicago

  • As a marketing communications person who knew my company needed an up-to-date website built in Joomla, I was very happy we found [Virgo Web Design]. I understood things from a content perspective, but when it came to back-end design and architecture, my hands were tied. [Virgo Web Design] was so knowledgeable and easy to work with, and was always available to answer questions, make tweaks, walk me through front-end editing tasks...you name it. [Virgo Web Design]'s accessibility and can-do attitude made such a difference to our entire team, and I hope I always thanked [them] enough for helping me through the client-side part of the web redesign process.

    CORRIE M.

    Aptude

  • "[Virgo Web Design] did an amazing job on my non-profit's website, ghhaven.org. [They] put our site together quickly and with all of the elements we requested - plus, [they] had a lot of great recommendations for things that we hadn't even considered for the site. [They were] very helpful throughout the process of getting our site launched and I found [them] to be quick in responding to all of my questions/requests as well. [They] even helped us get our business emails set up!

    I would definitely recommend Virgo Web Design as a go-to for all of your web design/development needs. I will definitely be using [them] again in the near future!"

    FRITZIE S.

    Genesis Hopeful Haven

  • [Virgo Web Design] has developed and designed multiple websites for me over the years. [Their] team are exceptionally skilled technicians. Their communication is easy to understand, and they are very proficient - even when near-end deadlines are demanding. Hiring Jerry Virgo and his team is one of the best decisions I have made for my company.

    Michael W

    One Chicago Realty

  • I've used Yahoo sitebuilder for several years and my e-commerce website was due for an overhaul. I asked around & received several recommendations from friends & other small businesses.

    Many of the other referrals came from Web design firms & had significantly higher overheads/billing rates...We had a tight timeline & [they were] very diligent at following up to avoid production delays at time when I was extremely busy. [They] did a nice all around job improving my SEO optimization, creating a polished final product, and documenting the back end with an easy to use manual.

    After the site when live, [they] stood by & helped me troubleshoot unanticipated events & helped me create work arounds.

    Chris H.

    City Tree Delivery

  • [Virgo Web Design] knocked out a full rebuild of our site in a few weeks, guided us through things we didn't understand with ease and calm and gave great advice, training and follow up service

    Nicholle D.

    DANK Haus

Contact

  • Phone:
    ‪(786)322-6784
  • E-Mail:
    This email address is being protected from spambots. You need JavaScript enabled to view it.

SUBSCRIBE TO OUR NEWSLETTER

© Copyright Virgo Web Design. All right reserved. Build software faster with AI.

Signup for our newsletter!