How to call media query using jQuery - javascript

I am trying to call media queries through document.ready method. Here my aim is to call a media query after HTML content got loaded. Can anyone help? On this.
Example:
#media only screen and (min-width: 1200px){
.main_container {
width: 1200px;
}
}

You can use
$windowWidth = $(window).width();
This will give you size of the current screen. Then use conditions to add your css
if ($windowWidth >= 1200) {
$('.main_container').css('width', '1200px');
} else {
$('.main_container').css('width', 'auto');
}

Related

JavaScript if statement alternative syntax

I want to check the size of the screen and toggle a class depending on the size of the screen.
Html
<div id="item" class="test"></div>
Script
window.addEventListener("load", toggleClass);
window.addEventListener("resize", toggleClass);
function toggleClass() {
var w = window.innerWidth;
item = document.getElementById("item");
if ( w > 700 ) {
item.classList.remove("test");
}else {
if ( item.classList.contains("test")) {
}else {
item.classList.add("test");
}
}
}
You don't need to test for whether test is included in the classList first - you can just add it unconditionally. Also, avoid implicitly creating global variables - always declare a new variable name with var (or, preferably, const, or let):
function toggleClass() {
var w = window.innerWidth;
var item = document.getElementById("item");
if ( w > 700 ) {
item.classList.remove("test");
}else {
item.classList.add("test");
}
}
You can also use the Conditional (ternary) operator
function toggleClass() {
var item = document.getElementById("item");
(window.innerWidth > 700) ? item.classList.remove("test") : item.classList.add("test");
}
A different approach - rather than adding a class on the smaller size - use a media query to apply the styling that you want - obviously if you are using the class for a purpose other than styling - this approach may not work - but if all you are doing is styling an element based on the width of the screen - then a media query is your friend.
The benefit of this approach (if its purely styling changes you are doing) is that there is no js required - the browser will automatically use whatever styling the media query matches. This is better for performance because the re is no js to run.
#media screen and (max-width: 699px) {
p {
font-size: 14px
}
}
#media screen and (min-width: 700px) {
p {
font-size: 16px
}
}

Add/Remove CSS id based on screen width

Have been trying to get $("#id1").add(); and $("#id2").remove(); to work inside the following function taken from this post. I am getting the $("#id2").remove(); to work from the console and I would like to get them both to work from inside this function as well.
(function($) {
var $window = $(window),
function resize() {
if ($window.width() < 801) {
$("#id1").add();
$("#id2").remove();
}
else {
$("#id2").add();
$("#id1").remove();
}
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);
Alternately, is could get it to work using .addClass/.removeClass, but then it has to target all sub classes as well..
Media queries can be used to toggle the elements' visibility:
CSS
/* show id1, hide id2, when screen resolution is 800px or less */
#media screen and (max-width: 800px) {
#id1 {
display:block; /*or inline, or whatever */
}
#id2 {
display:none;
}
}
/* show id2, hide id1, when screen resolution is greater than 800px */
#media screen and (min-width: 801px) {
#id1 {
display:none;
}
#id2 {
display:block; /*or inline, or whatever */
}
}
But if they need to actually be added and removed from the DOM, then how about this
(function($) {
var $id1=$('#id1');
var $id1Parent=$id1.parent();
var $id2==$('#id2');
var $id2Parent=$id2.parent();
var $window = $(window),
function resize() {
$('#id1,#id2').remove();
if ($window.width() < 801) {
$id1Parent.append($id1);
}
else {
$id2Parent.append($id2);
}
}
$window
.resize(resize)
.trigger('resize');
})(jQuery);
display none is the way to go for these kind of situations.
The other way is to use JQuery but it will be quite messy if your code gets longer. Or you might want to use AJAX for loading the div part if the div codes are really long.
function resize() {
if ($window.width() < 801) {
$("<div id='1'></div>").appendTo('.container'); //add it to your container
$("#id2").remove();
}
else ......
}

How to manipulate the screen width via js?

I'll try to explain my use case here. In my site I have a break point for desktop view, and break point for tablet view (which is more compact). I'm trying to add a function to allow seeing the tablet view when browsing from desktop, cause some members prefer the compact design in their desktop as well.
For doing that, I figured I would need to trick the '#media(max-width:X)' query. I'm looking for a JS code that can manipulate the screen width value, so when the browser calculates max-width, it would be against a value that I specified.
One thing to note, this is suppose to work on desktop browsers, so the meta viewport can't be used here.
One solution is to apply a specific class (e.g: .tablet) to the body.
<body class="tablet"></body>
In your CSS:
#media screen and (/* your query */) {
.tablet .my-class {
/* tablet specific stuff */
}
}
You could then remove the .tablet class and replace it with .desktop via JavaScript
var body = document.body;
var switchToDesktop = function() {
body.className = body.className.replace('tablet', 'desktop');
}
var switchToTablet = function() {
body.className = body.className.replace('desktop', 'tablet');
}
var toggleView = function() {
(body.className.indexOf("tablet") > -1) ?
switchToDesktop() :
switchToTablet();
}
If you are using SASS or LESS, you can nest the tablet-specific styles.
#media screen and (/* your query */) {
.tablet {
h1 {
/* tablet specific h1 */
}
.my-div {
color: red;
}
/* etc... */
}
}

IFrame width change with CSS and JavaScript

I'd like the width of my IFrame to be one of two sizes, depending on the width of the browser window. Unfortunately the code below doesn't give the expected results, even on refresh. What am I doing wrong?
The HTML is as follows:
<p>A frame example:<br>
<iframe src="www.google.com">
</iframe>
</p>
At the beginning, I import a stylesheet that works in all regards except the following:
iframe
{
<script>
if (window.innerWidth<800px)
{
width="200";
}
else
{
width="400";
}
</script>
height="400";
}
Any ideas on what I can improve?
You can't use javascript inside css. Just use media queries to solve the problem
#media all and (max-width:800px) {
iframe {
width: 200px;
}
}
#media all and (min-width: 801px) {
iframe {
width: 400px;
}
}
Using css media queries is preferable but if you'd like to change the width using JavaScript, you can listen to the onresize window event and change the width inside the event handler.
Note that I added an id to the iframe so you can quickly select it in the JavaScript.
HTML
<iframe id="myIframe" src="www.google.com"></iframe>
JavaScript
(function() {
var iframe = document.getElementById('myIframe');
iframe.height = 400;
window.onresize = resizeIframe;
function resizeIframe() {
if (window.innerWidth < 800) {
iframe.width = 200;
}
else {
iframe.width = 400;
}
}
}());
Check out the jsfiddle example

Toggling text of "a href" based on screen width

Using jQuery/jQueryMobile, I have a link as follows:
<a href="index.html" id="HomeLink" data-role="button" data-mini="true" data-icon="home" data-iconpos="top" >Home</a>
I am trying to test various screen sizes, and if the screen width is less than 300px, I want to change:
data-iconpos="top"
to
data-iconpos="notext"
so I only get the icon. I have tried to do it with JavaScript:
var hl = document.querySelector('#HomeLink');
if ($(window).width() < 300) {
hl.setAttribute("data-iconpos", "notext");
} else {
hl.setAttribute("data-iconpos", "top");
}
But it won't work.
Question: can it be done in CSS instead.
If not: how can it be done in JavaScript?
You can't really set a data attribute with CSS as far as I know, but since you're already using jQuery, why not try it all the way :
$('#HomeLink').data('iconpos', ($(window).width() < 300 ? 'notext' : 'top') );
Remember to wrap that in document ready!
You can do this way altering your code:
var hl = $('#HomeLink');
if ($(window).width() < 300) {
hl.data("iconpos", "notext");
} else {
hl.data("iconpos", "top");
}
with .attr():
var hl = $('#HomeLink');
if ($(window).width() < 300) {
hl.attr("data-iconpos", "notext");
} else {
hl.data("data-iconpos", "top");
}
Try to wrap the code in window resize event, eg:
$(window).resize(function () {
check();
})
$(function () {
check();
})
function check() {
if ($(window).width() < 300) {
$('#HomeLink').attr('data-iconpos', 'notext');
} else {
$('#HomeLink').attr('data-iconpos', 'top');
}
}
I would like to suggest using a different approach.
The data-iconpos="top" looks a bit out of place to me here. I have a feeling (perhaps I'm wrong) that you're attempting to inline your styling into the HTML.
Why not try media queries?
#media screen and (max-width: 300px) {
#HomeLink {
/* styling for HomeLink when screen width is less than 300px */
}
}
This is a CSS-only solution. It works if the user decides to resize the screen after the page has loaded. Try resizing the "Result" frame in this jsfiddle and notice the color of the link changing.
Suggested reading:
http://alistapart.com/article/responsive-web-design
https://developer.mozilla.org/en-US/docs/CSS/Media_queries
And here are the docs on media queries: http://www.w3.org/TR/css3-mediaqueries/
Warning: mind ahem, IE below 9, ahem...

Categories