Showing posts with label media queries. Show all posts
Showing posts with label media queries. Show all posts

Tuesday 12 February 2019

Vanilla JS component

I'm creating a number of elements using Vanilla JavaScript. They will use :

  • HTML5
  • SASS
  • CSS grid
  • BEM
  • Media queries
  • ES6

In order to put these elements together more efficiently, I have put together a small framework, from which I will fork.
It lies at https://github.com/guitarbeerchocolate/vanilla-js-component

Tuesday 28 March 2017

jQuery media queries plugin

Media queries are really useful in CSS, but what if you could use them to control page events and content using jQuery. I have created the beginnings of a solution below.

Here we have 2 files:
  • index.html
  • mediaquery.plugin.js

index.html is a very basic page which passes the window object to mediaquery.plugin.js.

mediaquery.plugin.js listens for changes in the window width and reacts accordingly.

In this case it simply changes the background colour of the body which calls the plugin, but of course, this is only the start. In place of changing the page colour, you could do all sorts of useful things. For example, you could pass the identifier of a div the plugin and add external content to it. The list is endless. Have fun!


index.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery media queries</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="mediaquery.plugin.js"></script>
<script>
(function()
{
    $(window).mediaquery();
})();
</script>
</body>
</html>

mediaquery.plugin.js

(function($)
{
    $.fn.mediaquery = function(options)
    {
        var defaults =
        {
            phone:'blue',
            tablet:'red',
            desktop:'green'
        };
        options = $.extend(defaults, options);

        $(this).handleWidths(options);
        $(this).resize(function()
        {
            $(this).handleWidths(options);
        });
    }
})(jQuery);

$.fn.handleWidths = function(opt)
{
    if($(this).width() < 481)
    {
        $(this).phoneFunc(opt.phone);
    }
    else if($(this).width() < 769)
    {
        $(this).tabletFunc(opt.tablet);
    }
    else
    {
        $(this).desktopFunc(opt.desktop);
    }
}

$.fn.phoneFunc = function(str)
{
    $('body').css('background-color', str);
};

$.fn.tabletFunc = function(str)
{
    $('body').css('background-color', str);
};

$.fn.desktopFunc = function(str)
{
    $('body').css('background-color', str);
};