I'm using jquery to remove a div to make my home screen look different on small screens and it's working fine on a Macbook Air and Iphone X. However on Android the div isn't removed and replaced as intended. This is the address for the website draft:
http://projetocc.learningtodom.com/
This is the code for the jquery bit:
<script>
$(function(){
if (window.matchMedia("(max-width: 750px)").matches) {
$('.desktop').remove();
}
});
$(function(){
if (window.matchMedia("(min-width: 750px)").matches) {
$('.mobiles').remove();
}
});
</script>
Let me know if you need me to post some css code as well.
If you don't have any success with your javascript approach, maybe you could consider using CSS and media queries. You may find that it's easier and gives more consistent results.
Simply add a viewport meta tag in the head of your document
<head>
...
<meta name="viewport" content="width=device-width, initial-scale=1.0">
...
</head>
And then in your CSS add the following
#media(max-width:750px){
.desktop{
display:none;
}
}
#media(min-width:751px){
.mobiles{
display:none;
}
}
I made a minor change to one of your breakpoints. With the code you had posted, both the mobile and desktop divs would be hidden at 750px.
I hope this helps!
Related
I currently have a site that uses <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0" /> to make the page responsive.
The issue I am trying to overcome is using google variant testing on two versions of the homepage, but only having people viewing the full site included.
My proposed solution would be to detect whether the browser is a mobile device and if not display the analytic code:
<!-- Google Analytics Content Experiment code -->
<script>function utmx_section(){}function utmx(){}(function(){var
k='13292219-1',d=document,l=d.location,c=d.cookie;
if(l.search.indexOf('utm_expid='+k)>0)return;
function f(n){if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.
indexOf(';',i);return escape(c.substring(i+n.length+1,j<0?c.
length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;d.write(
'<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':
'://www')+'.google-analytics.com/ga_exp.js?'+'utmxkey='+k+
'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().
valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
'" type="text/javascript" charset="utf-8"><\/sc'+'ript>')})();
</script><script>utmx('url','A/B');</script>
<!-- End of Google Analytics Content Experiment code -->
Does anyone have any suggestions?
My proposed solution would be to detect whether the browser is a mobile device and if not display the analytic code:
One approach is to use the javascript equivalent of CSS #media queries, which is
window.matchMedia();
A standard CSS #media query to detect a mobile browser might be:
#media only screen and (min-device-width:320px) and (max-device-width:480px)
The javascript equivalent would be:
window.matchMedia("(min-device-width:320px) and (max-device-width:480px)");
So you could have something like:
var screen320x480 = window.matchMedia("(min-device-width:320px) and (max-device-width:480px)");
var screen320x568 = window.matchMedia("(min-device-width:320px) and (max-device-width:568px)");
if ((screen320x480.matches) || (screen320x568.matches)) {
[...CODE HERE...]
}
else {
[...DISPLAY ANALYTICS CODE HERE...]
}
Further Reading:
https://developer.mozilla.org/en/docs/Web/API/Window/matchMedia
https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries
To elaborate more on my question, I designed a website specifically to be viewed on a desktop. It does not look good if being tested on a mobile device. Therefore, I made a complete different layout for my website (containing all of the same content) by using jQuery mobile (due to its simplicity).
I realize now that there were probably better ways in doing this, such as implementing the mobile view in my CSS file, based on media queries, but this is the way that I chose to do it and would prefer to stick with it.
So here's my problem:
I want to use my JavaScript file to detect the different screen sizes, in order to display the desktop view or mobile view, based on their specified screen width and height. As of now, my desktop view and mobile view are in two different html files, and I know that is not good.
I don't want two html files, I want to combine the two! That's the only way I would be able to call the two different codes in my .js file, correct? Does anyone know how to do this?
In my mobile view file, I needed to include the jQuery libraries. Without those, it will not work. But when I tried including that in my desktop view file (since I am now trying to combine the files), I tested it alone with just that and it completely messed up the view on my desktop. How do I solve this?? Other than that, I'm assuming I would just separate the codes with two different 's as far as combining the rest of the code, yeah?
For example,
<div id="desktop"> ..... </div> <!-- this is for desktop view -->
and
<div id="mobile"> ..... </div> <!-- this is for mobile view -->
Please, any help would be so appreciated. I've tried researching this, but I can't find anything specific enough to answer my questions.
Here is the beginning of my desktop view file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="hwk5.css">
<script type="text/javascript" src="hwk5.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
And here is the beginning of my mobile view file:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1 maximum-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<style>
img.fullscreen {
max-height:50%;
max-width:50%;
}
</style>
</head>
<body>
As I said in my comment, you could just detect mobile browsing with PHP and redirect the user to the desktop or mobile site accordingly, but if you really want to do this with jQuery, it is possible.
You would want to check the page width onReady and onResize:
$(document).ready(function(){resize();});
$(window).resize(function(){resize();});
function resize()
{
var mobileMaxWidth = 640; //Define this to whatever size you want
if($(window).width() > mobileMaxWidth)
{
$("div#desktop").show();
$("div#mobile").hide();
}
else
{
$("div#desktop").hide();
$("div#mobile").show();
}
}
JSFiddle
As far as jQuery messing up your desktop site, you must be using another DOM. Are you importing MooTools or another popular DOM that uses $? If so, you would need to explicitly mark jQuery code as jQuery("selector")... instead of $ or use jQuery.noConflict.
For more information, see this post.
I Suggest You To Write Two Seperate CSS Files... One For Desktop And Other For Mobile. And According to the current screen size change the css files using javascript.
To achieve this You Can Use this script
<script type="text/javascript">
$(document).ready(function () {
changecss();
});
$(window).resize(function () { changecss(); });
function changecss() {
var windowwidth = $(window).width();
var windowheight = $(window).height();
if (windowwidth >= 1024 && windowheight >= 768) {
//alert('Screen size: 1024x768 or larger');
$("link[rel=stylesheet]:not(:first)").attr({ href: "Style2.css" });
}
else {
$("link[rel=stylesheet]:not(:first)").attr({ href: "Style1.css" });
}
}
</script>
HTML
<div>
The colour of this text will change.
</div>
I am building an android app that uses webviews from an existing mobile web app. The existing mobile web app has a header graphic and also a footer navigation that uses unordered lists.
Since the android app has native navigation and a header already built into the app, when using a webview of the pages in the mobile web app, the web app header and footer are redundant in the android app. Since the mobile web app will be used for devices such as blackberrys and windows phones, I cannot universally remove the header and footer. Also, the web app header uses some CSS so I need to make sure that's in there for the mobile web app.
So what I decided to try was use javascript to detect the android OS, dynamically assign a class name to the header and footer divs when it detects the android OS, and reference the class name in CSS to not display these divs. If the OS is not android then it will create the style pointer to the CSS file that is needed for the header in the mobile web app.
I am not a javascript or CSS expert, so I came up with a simple test to make sure this all works. Everything works except it does not seem to be assigning the class name to the div for it to be not displayed when the android OS is detected. I know it's detecting the android OS because I have an alert in the if statement and that works. I cannot figure out where I am going wrong. I tested this on a Google Nexus 7 using android 4.4 and Chrome, and on a Motorola RAZR Droid with android 4.1.2 using Chrome.
The test code is below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
.android
{
display:none;
}
</style>
<script language="javascript" type="text/javascript">
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
}
};
var divID = "test";
var newClassName = "android";
function changeClass() {
var divReference = document.getElementById(divID);
divReference.className = newClassName;
};
if( isMobile.Android() )
{
alert("android!");
changeClass();
}
else
{
alert("Not android!");
document.write("<link rel='stylesheet' href='header.css' type='text/css'>");
}
</script>
<title>Untitled Document</title>
</head>
<body>
<h1>Detect android device and hide second UL list below. If not android device, then hide the first UL list.</h1>
<div class="notandroid">
<ul>
<li>One</li>
<li>two</li>
<li>three</li>
</ul>
</div>
<h2>This header is after the first UL list</h2>
<div id="test">
<ul>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>
</div>
<h2>This header is after the second UL list</h2>
</body>
</html>
Try putting your script tag at the bottom of the body. The div does not exist at the time that the script is run. Browsers parse and run javascript inside script tags as soon as they encounter it - so you need to run the javascript after the DOM is ready.
You are calling changeClass() before the Element you are trying to document.getElementById() with is defined. Either put your code in onload = function(){/*in here*/}, or put your script tag at the bottom of your body. In short, HTML has to be created before you can get it with JavaScript. Additionally, document.write() is not supported in XHTML. http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite
There are plenty of good reasons for avoiding browser-detection. But if you're determined to go ahead with this, the main issue you're having is that this code is running in the HEAD, but the DIV you're looking for doesn't exist yet, as it's in the body. You might have to do this in two blocks, if you want the document.write for the CSS in the HEAD.
I have a mobile site, unfortunately I can't direct access to do anything on HTML, so I'm using JQuery to style its width, height etc., the problem is the site has actually 762px width(which is a normal site for PC) and I gave 320px width(for an iPhone screen), everything works well but at the time when page loads it comes from the middle of the page to fit the 320px screen size. I strongly believe that my JQuery code for width(320px, although I specified Jquery for some other elements too) is taking action after the contents loaded in the html page.
(I saw this problem on Opera mobile emulator 320x480)
So if I can able to load the JQuery first then the contents(HTML) in the page may solve the issue. You guys have any suggestions?
my script is given below..
$(document).ready(function() {
$('head').append('<meta name="viewport" content="initial-scale=1.0, width=device-width" />');
$("table.bgContent").removeAttr("width");
$("table.bgContent").attr("width","320");
$("table.cart-header").removeAttr("width");
$("table.cart-header").css("background","none");
$("table.cart-header").css("border","none");
$("table.cart-header td:first").html('<img src="images/userdir/logomobile.gif" width="320" height="79" border="0"/>');
$('head').append('<meta name="viewport" content="initial-scale=1.0, width=device-width" />');
$("table:eq(2) td.bgHeaderBarCart").html(" ");
$('table.cart-header td:nth-child(2)').css('display', 'none');
$('hr').css('width','300px');
$('td.FormTextCart').removeAttr("width");
$('.cart-header').css('height','0px');
$('.ContentAreaCart').css('padding','0px');
$('.SpanOrderCenter').css({padding : '0px', textAlign : 'left', fontWeight : 'normal', fontSize : '12px', width : '300px'});
});
Just put a wrapper <div> within your <body> tag, for example:
<html>
<head>
</head>
<body>
<div id="wrapper" style="display:none;">
</div>
</body>
</html>
then on document ready in your js file, add:
$("#wrapper").show();
I used to be able to get hold of
$('[data-role=header]').first().height()
in alpha with jQuery 1.5.2, but no longer can in beta with jQuery 1.6.1. Has something changed?
Full code - this writes 0 to console.log...
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
console.log($('[data-role=header]').first().height());
});
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header">
<h1>Header</h1>
</div>
<div data-role="content">
//lots of code
</div>
</div>
</body>
</html>
However, change this to jQuery 1.5.2 and jQuery Mobile alpha:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js"></script>
and it writes the non-zero height of the header div.
Incidentally, it is also non-zero with jQuery 1.6.1 but without jQuery Mobile. So it's something to do with the jQuery Mobile rendering.
Can't see anything in the release notes to suggest what might have happened, but I'm no jQuery expert.
The change that is causing the difference is "Responsive design helper classes: Now deprecated"
We include a set of responsive design helper classes designed to make it easy to build a responsive design that adapts the layout for various screen widths. At the time, we went with a system of dynamically appended min- and max-width classes on the body that are updated on load, resize and orientation change events as a workaround for the limitation that Internet Explorer doesn’t support media queries.
Basically, the page is getting min-height set to the current page height in the beta which is overriding the .landscape { min-height: 300px; } in the alpha.
It looks like you need to use CSS Media Queries if you want a page layout that changes or you could just add CSS style="height:43px" on the the header if you need a fixed height.
Seems like the page is not ready when you query the height(). There is no document.ready for jQuery.mobile. It doesn't explain why there is a difference between alpha and beta, but I guess a code path changed that exposed the issue.
Wrapping the query in a different event, returns the height as expected.
$("div:jqmData(role='page')").live('pageshow',function(){
console.log($('[data-role=header]').first().height());
});
I found this by examining the offsetHeight of the DOM element in the Chrome console which was non-zero but, as you reported, the height() was always reporting 0. I then created an link when clicked output the height and it was non-zero. I then realised that the height() was being called before the page was fully ready.
Relevant - jQuery mobile $(document).ready equivalent
Looks like they did change some of the syntax, Docs:
http://jquerymobile.com/demos/1.0b1/docs/api/methods.html
When finding elements by their jQuery
Mobile data attribute, please use the
custom selector :jqmData(), as it
automatically incorporates namespaced
data attributes into the lookup when
they are in use. For example, instead
of calling $("div[data-role='page']"),
you should use
$("div:jqmData(role='page')"), which
internally maps to $("div[data-"+
$.mobile.ns +"role='page']") without
forcing you to concatenate a namespace
into your selectors manually.
Try this:
$("div:jqmData(role='header')").first().height()