JoshBarr / on-media-query

A neat way to trigger JS when media queries change. No jQuery required.
283 stars 33 forks source link

usage as function? #9

Closed Micsi closed 11 years ago

Micsi commented 12 years ago

Hi,

is it possible to use this in a procedural way? I want to check what context I am in in the header area of a page to generate a specified header. So that's not a callback event but a rather basic function call.

How would one do this?

mhulse commented 12 years ago

@Micsi Probably the only way you can get what you're looking for is to:

MQ.init(queries);
console.log('the current media query context:', MQ.new_context);

... Alternatively, you could write your own JS function to get the current context. Something like:

/**
 * Get the font-family style value of the passed element's style.
 *
 * @return { string } Value or empty string.
 */

function _fontFamily(el) {

    if (el) {

        // return (IE browser?) ? (Return IE fontFamily) : ((W3C browser?) ? (Return W3C font-family) : Return empty string);
        return (el.currentStyle) ? el.currentStyle['fontFamily'] : ((window.getComputedStyle) ? window.getComputedStyle(el).getPropertyValue('font-family') : '');

    }

};

//--------------------------------------------------------------------

/**
 * Get the :after content value of from the passed element's style.
 *
 * @return { string } Value or empty string.
 */

function _contentAfter(el) {

    if (el) {

        return (window.getComputedStyle) ? window.getComputedStyle(el, ':after').getPropertyValue('content') : ''; // getPropertyValue() Returns an empty string in Firefox and Opera and null in Google Chrome and Safari.

    }

};

... call like so:

var context = _contentAfter(document.body) || _fontFamily(document.documentElement);
context = context.replace(/['",]/g, '');
// do stuff with context ...

Lastly, I'm working on a fork where one could say:

var context = oMQ.getContext();

... without having to initialize anything. Basically, I'm using the code you see above.

FYI: I haven't pushed my local code to the develop branch yet, but I should have a new version pushed in the next day or so.

Hope that helps!

Micky

mhulse commented 11 years ago

Seems resolved to me. Closed.