Media queries based javascript

3:20 AM 9/2/2018

(a continuance of development work I posted at Javascript Break Point Help)

It's the media queries which is a part of CSS technology that enables web page to adapt to its currently used, containing device. I'm only familiar enough with the screen device, but this could be anything like print, projection, etc etc.

In some situations, we sometimes need web page to execute particular javascript to run; that's when some conditionals of CSS media queries are met.

A few years ago, there was no way for CSS to tell javascript about anything by itself, directly. In front-end (client-side) coding, Javascript was always on topmost in command hierarchy.

This has changed. Now CSS can speak up through event object and javascript will listen to it and and act, accordingly. In this page, we are going to use one of this event channel called transition, or specifically the transitionend event.

Let us test this: following paragraph will print 5 floating, random numbers between 0 and 1. These numbers should have no problem with wide screens as there is enough space to the right to show all of the digits.

On narrow screens however, we allow precision lost by limiting digits after decimal point to say, only 3.

Source

Here's the HTML:

<p id="test"></p>
		

The CSS, as follows:

	p#test{
		position: relative;/*as reference to absolute pseudo element of #test*/
		font-size: 3em;
	}
	p#test:before{
		position: absolute;
		z-index: -1;/*this will change to different value on narrow screens*/
		content: '';
		color: wheat;/*for demo only; this should have transparent value*/
		transition: z-index 1ms;
	}
@media screen and (max-width: 30em){
	p#test:before{
		z-index: -2;/*value on narrow screens is different than on wider screens*/
	}
	p#test:before{
		content: 'narrow';
	}
}
		

And the javascript:

'use strict';

function printNumbers(){
	var w = getComputedStyle(test, ':before').content.slice(1, -1);
	if(w !== currentWidth){
		currentWidth = w;
		test.innerHTML = '';
		count = 0;
	}
}

var test = document.getElementById('test'),
	count = 0,
	currentWidth = '';
	
test.addEventListener('transitionend', function(){
	printNumbers();
});

setInterval(function(){
	if(count < 5){
		var n = (currentWidth === 'narrow') ? Math.random().toFixed(3) : Math.random();
		test.innerHTML += n + '<br>';
		count++;
	}
}, 100);

printNumbers();