jQuery - Get Screen Size Width - javascript

Trying to grab the screen size and add an if / else query, but for some reason I can't get it to work
What I'm looking for is if the screen width is larger / equal 480px, the following should be outputted:
{$pPage = $cWidth}
Else this:
{$pPage = 1}
This is what I have so far:
<script type="text/javascript">
(function($) {
$(document).ready(function() {
{$pPage = $cWidth}
})(jQuery);
</script>
Anybody out there with advice how to add the the query in reference to the screen.width, so that it also works?

try this:
using jquery:
if ($(window).width() < 1280) {
alert('Less than 1280');
}
else {
alert('More than 1280');
}
OR
using javascript:
var screensize = document.documentElement.clientWidth;
if (screensize < 1280) {
alert('Less than 1280');
}
else {
alert('More than 1280');
}

Related

Applying jquery code only to mobile and tablet

i want to apply this jquery code only for mobile and tablets
<script>
jQuery(window).scroll(function () {
var y = jQuery(this).scrollTop();
if (y > 440) {
jQuery('.dropdown,.navbar.fixed-top').fadeIn(600);
} else {
jQuery('.dropdown,.navbar.fixed-top').fadeOut(600);
}
});
</script>
One simple way is to grab the window width and run the function if the width is smaller than a certain width.
<script>
jQuery(window).scroll(function () {
if(jQuery(window).width() <= 1024){
var y = jQuery(this).scrollTop();
if (y > 440) {
jQuery('.dropdown,.navbar.fixed-top').fadeIn(600);
} else {
jQuery('.dropdown,.navbar.fixed-top').fadeOut(600);
}
});
}
</script>

How to Disable / Re-enable Javascript on window resize?

I need to be able to disable / re-enable Javascript on window resize?
Currently when the window is resized on the desktop, the nav bar sticks and is the only thing visible instead of the content.
<script>
if ( $(window).width() <= 1200 ) {
}else{
$('nav').addClass('original').clone().insertAfter('nav').addClass('cloned').css('position','fixed').css('top','0').css('margin- top','0').css('z-index','500').removeClass('original').hide();
scrollIntervalID = setInterval(stickIt, 10);
function stickIt() {
var orgElementPos = $('.original').offset();
orgElementTop = orgElementPos.top;
if ($(window).scrollTop() >= (orgElementTop)) {
as original element.
orgElement = $('.original');
coordsOrgElement = orgElement.offset();
leftOrgElement = coordsOrgElement.left;
widthOrgElement = orgElement.css('width');
th',widthOrgElement).show();
$('.original').css('visibility','hidden');
} else {
$('.cloned').hide();
$('.original').css('visibility','visible');
}
}
</script>
You can bind an event handler to the "resize" JavaScript event:
$(window).resize(function() {
if($(window).width() <= 1200) {
//You code here
}else {
//You code here
}
});
Your code will be executed whenever the browser window's size is changed.
$(window).resize(function() {
if($(window).width() <= 1200) {
//small screen code
}else {
//large screen code }
});
//trigger window resize event on load
$(window).trigger('resize');
you can do it by checking the window width
var winWidth = $(window).width(); // you can get the window width from this
//Then check with the condtion(compare with your need ex :)
if(winWidth <= 600)
{
//your work here
alert("window resize less than or equal to 600");
}
else
{
//your work here
alert("window resize greater than to 600");
}

Media queries and height & width defined in variable

I found this plugin online:
https://github.com/frenski/quizy-memorygame
As you can guess, it's a memory game in which you can choose the images to display on the cards. And it's great. But the thing is I'm trying to use media queries to make it more responsive, and it worked great until I realized that the width and height of the cards are defined not only in the CSS but also in a variable.
var quizyParams = {itemWidth: 156, itemHeight: 156, itemsMargin:40, colCount:3, animType:'flip' , flipAnim:'tb', animSpeed:250, resultIcons:true, randomised:true };
$('#tutorial-memorygame').quizyMemoryGame(quizyParams);
$('#restart').click(function(){
$('#tutorial-memorygame').quizyMemoryGame('restart');
return false;
});
How can I change the itemWidth and itemHeight depending on the size of the screen? Is that even possible?
I tried using a function like:
if(screen.width <= 480){
//change width and height to this
}else if (screen.width <= 780){
//change width and height to that
}else (screen.width <= 960){
//change width and height to this
}
But it didn't work...
All ideas are welcome! And thank you for your help.
Using if (screen.width <= 480) might not work onload, try use window.matchMedia() to match your CSS media queries:
if (window.matchMedia('(max-width: 480px)').matches) {
//...
} else {
//...
}
try this hope helpful you ....
$(document).ready(function() {
function checkWidth() {
var windowSize = $(window).width();
if (windowSize <= 479) {
console.log("screen width is less than 480");
}
else if (windowSize <= 719) {
console.log("screen width is less than 720 but greater than or equal to 480");
}
else if (windowSize <= 959) {
console.log("screen width is less than 960 but greater than or equal to 720");
}
else if (windowSize >= 960) {
console.log("screen width is greater than or equal to 960");
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});​

Prevent Javascript from continuing a function if the screen is lower than 480 pixels

First of all, I'm not a javascript expert. I'm going crazy on trying to figure out how to make a conditional execution of a certain javascript. I'm using JQuery to absolutely center my block in a browser page, but only if the screen size is bigger than 480px (In other meaning, I don't want this script to run on smartphones). I'm using CSS media query to indicate my request. The thing is, this script works fine on all smartphones, Safari 5+, IE10, Firefox 13. BUT IT DOESN'T WORK ON IE6-9 and Opera 12 (As far as I understand, they don't support transitions). CAN ANYONE PLEASE HELP ME FIGURE OUT WHAT I AM DOING WRONG? And if there's a better way of doing this? (I tried #media query in CSS but The script keeps on running no matter what)... I would really appreciate the help.
<script>
if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
//Absolute Content Center
function CenterItem(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
} //end of "else" (normal execution)
</script>
You can try this :-
<script>
var screenWidth = screen.width;
if (screenWidth > 480 ) {
//Absolute Content Center
function CenterItem(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
}
</script>
To get exact Height and Width in all browser is quite big deal because of IE, But no worries is the solution for all Browser including IE 6 to latest.
Here are those 2 function:
if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
//Absolute Content Center
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
} //end of "else" (normal execution)
function CenterItem(theItem){
var winWidth=getWindowWidth();
var winHeight=getWindowHeight();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
function getWindowHeight() {
var myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myHeight = document.body.clientHeight;
}
return myHeight;
}
function getWindowWidth() {
var myWidth = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth;
}
return myWidth;
}
This will help you to get exact height in any Browser, in that way you can apply your logic. Hope this help!!!
Simplest thing is not to attach the event handler if the media query does not match.
$.fn.extend({
centerItem: function () {
return this.each(function () {
var $this = $(this),
hCenter = ( $(window).width() - $this.width() ) / 2,
vCenter = ( $(window).height() - $this.height() ) / 2;
$this.css({
left: hCenter > 0 ? hCenter : 0,
top: vCenter > 0 ? vCenter : 0
});
});
}
});
$(function() {
var bigScreen = 'only screen and (max-device-width:800px) and (orientation: portrait)';
if ( matchMedia(bigScreen).matches ) {
$(window).resize(function() {
$('.content').centerItem();
});
}
});
Notes
$() replaces $(document).ready(). See http://api.jquery.com/ready/
By convention, only object constructors start with a capital letter, so your CenterItem() function should actually be called centerItem().
I've turned your function into a jQuery plugin. You can of course continue using your own implementation if you find that confusing.
The .css() function can take an object argument so you can set multiple CSS properties in one step.
I've used the ternary operator (expression ? ifTrue : ifFalse) to replace the if.
You can do
window.innerHeight
window.innerWidth
to get the dimensions of the viewport. Now you could do:
var width = window.innerWidth
if (width > 480){
/* do desktop stuff*/
}
As alternative, you could go for the UserAgentString and/or Operating with:
window.navigator
(more reliable Detect-script)
However, either attempt might fail in some cirumstances.
edit: would be nice if you posted your match-media function.
edit2: use the script for correct viewport detection: https://stackoverflow.com/a/2035211/1047823
and then alter your code:
if ( getViewport()[0] < 480 ) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
// your desktop code
}

Do something if screen width is less than 960 px

How can I make jQuery do something if my screen width is less than 960 pixels? The code below always fires the 2nd alert, regardless of my window size:
if (screen.width < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
Use jQuery to get the width of the window.
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
You might want to combine it with a resize event:
$(window).resize(function() {
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
});
For R.J.:
var eventFired = 0;
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
eventFired = 1;
}
$(window).on('resize', function() {
if (!eventFired) {
if ($(window).width() < 960) {
alert('Less than 960 resize');
} else {
alert('More than 960 resize');
}
}
});
I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.
I recommend not to use jQuery for such thing and proceed with window.innerWidth:
if (window.innerWidth < 960) {
doSomething();
}
You can also use a media query with javascript.
const mq = window.matchMedia( "(min-width: 960px)" );
if (mq.matches) {
alert("window width >= 960px");
} else {
alert("window width < 960px");
}
// Adds and removes body class depending on screen width.
function screenClass() {
if($(window).innerWidth() > 960) {
$('body').addClass('big-screen').removeClass('small-screen');
} else {
$('body').addClass('small-screen').removeClass('big-screen');
}
}
// Fire.
screenClass();
// And recheck when window gets resized.
$(window).bind('resize',function(){
screenClass();
});
I would suggest (jQuery needed) :
/*
* windowSize
* call this function to get windowSize any time
*/
function windowSize() {
windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
}
//Init Function of init it wherever you like...
windowSize();
// For example, get window size on window resize
$(window).resize(function() {
windowSize();
console.log('width is :', windowWidth, 'Height is :', windowHeight);
if (windowWidth < 768) {
console.log('width is under 768px !');
}
});
Added in CodePen :
http://codepen.io/moabi/pen/QNRqpY?editors=0011
Then you can get easily window's width with the var : windowWidth
and Height with : windowHeight
otherwise, get a js library :
http://wicky.nillia.ms/enquire.js/
use
$(window).width()
or
$(document).width()
or
$('body').width()
I know i'm late to answer this, but i hope it is of some help to anybody who have similar problem. It also works when page refreshes for any reason.
$(document).ready(function(){
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
$(window).resize(function() {
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
else{
$("#up").show();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
else{
$("#up").show();
}
});});
Try this code
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My solution for the question using Vanilla JS is,
window.addEventListener("load", function () {
if (window.innerWidth < 960) { doSomething(); }
}
This works, but with one problem, whenever resizing the screen in dev tools, which is a common thing for developers, the function does something will not be fired.
For example, if we display the webpage on a computer with a screen size of more than 1000px, the function will not be fired, and when we resize the windows to less than the target(here 960px) we expect the event to be fired but that is not what happens.
By the time the script file is already processed and finished and will not be re-read, so we need to fire an event whenever we resize the screen and handle that event using "addEventListener", Just like this;
window.addEventListener("resize", (e) => {
const windowWidth = window.innerWidth;
if (windowWidth > 960) { doSomething(); }
if (windowWidth < 960) { doSomething(); }
});
The best practise is to combine both the code-snippets in the project.
Simple and clean solution using Vanilla JavaScript
let app = document.getElementById('app')
const changeColorFn = ( app, color ) => {
app.setAttribute("style",`background: ${color}`)
}
const winSizeFn = ( winWidth, callback, app, color ) => {
if (window.innerWidth < winWidth ) {
callback(app, color);
}
}
winSizeFn( '1200', changeColorFn, app, 'red' )
winSizeFn( '800', changeColorFn, app, 'green' )
winSizeFn( '500', changeColorFn, app, 'blue' )
window.addEventListener("resize", (e) => {
// add winSizeFn here if you want call function on window resize
})
<div id="app">My app content</div>
nope, none of this will work. What you need is this!!!
Try this:
if (screen.width <= 960) {
alert('Less than 960');
} else if (screen.width >960) {
alert('More than 960');
}

Categories